Ict Its4 06 0811 Use Advanced Structural Query Language
Ict Its4 06 0811 Use Advanced Structural Query Language
By Muhammed..A
Page
200 hrs
Triggers
Stored procedures
A Trigger is a special kind of stored procedure that executes whenever an attempt is made to modify data in a
table that the trigger protects.
Stored procedure is set of Structured Query Language (SQL) statements that perform particular task.
By Muhammed..A
Page
Numeric types
- Number(p,q) general purpose numeric data type
- Integer(p) signed integer, p digits wide
- Float(p) - floating point in scientific notation with p binary.
- Date/Time type - Date - fixed length date/time in dd-mm-yyyy form
By Muhammed..A
Page
By Muhammed..A
Page
Referential Integrity
Referential integrity maintains the defined relationships between tables when records are entered or deleted.
When you enforce referential integrity, SQL Server prevents users from:
-
Adding records to a related table if there is no associated record in the primary table.
By Muhammed..A
Page
Changing values in a primary table that result in orphaned records in a related table.
Deleting records from a primary table if there are matching related records.
SELECT clause
WHERE Clause
ORDER BY Clause
INNER JOIN Clause
INSERT Statement
UPDATE Statement
DELETE Statement
By Muhammed..A
Page
1.4.
The SQL statements can be run on SQL tables and views, and database physical and logical files.
Character strings specified in an SQL statement (such as those used with WHERE or VALUES clauses) are
case sensitive; that is, uppercase characters must be entered in uppercase and lowercase characters must be
entered in lowercase.
WHERE ADMRDEPT='a00'
WHERE ADMRDEPT='A00'
By M.A
Page 7
The SELECT and FROM clauses must be specified. The other clauses are optional.
With the SELECT clause, you specify the name of each column you want to retrieve.
The FROM clause specifies the table that you want to select data from. You can select columns from more
than one table.
You can specify that only one column be retrieved or as many as 8000 columns. The value of each column
you name is retrieved in the order specified in the SELECT clause.
If you want to retrieve all columns (in the same order as they appear in the table's definition), use an asterisk
(*) instead of naming the columns.
<search_criteria>]>
Cross join
By M.A
Page 8
An Inner Join returns only the rows from each table that have matching values in the join columns.
Any rows that do not have a match between the tables will not appear in the result table.
A Left Outer Join returns values for all of the rows from the first table (the table on the left) and the values
from the second table for the rows that match. Any rows that do not have a match in the second table will
return the null value for all columns from the second table.
A Right Outer Join return values for all of the rows from the second table (the table on the right) and the
values from the first table for the rows that match. Any rows that do not have a match in the first table will
return the null value for all columns from the first table.
A Left Exception Join returns only the rows from the left table that do not have a match in the right table.
Columns in the result table that come from the right table have the null value.
A Right Exception Join returns only the rows from the right table that do not have a match in the left table.
Columns in the result table that come from the left table have the null value.
A Cross Join returns a row in the result table for each combination of rows from the tables being joined (a
Cartesian product).
Subqueries:
A Subquery or Inner query or Nested query is a query within another SQL query, and
embedded within the WHERE clause.
-
You use subqueries to break down a complex query into a series of logical steps and, as a result, to solve a
problem with single statements.
Each select statement in the subquery has its own:
. select list
.
where clause
A subquery is used to return data that will be used in the main query as a condition to further
restrict the data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements (or
inside another subquery) along with the operators like =, <, >, >=, <=, IN, BETWEEN etc.
There are a few rules that subqueries must follow:
A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query
for the subquery to compare its selected columns.
An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP
BY can be used to perform the same function as the ORDER BY in a subquery.
Subqueries that return more than one row can only be used with multiple value operators, such as the IN
operator.
By M.A
Page 9
The BETWEEN operator cannot be used with a subquery; however, the BETWEEN can be used within the
subquery.
Example: For each department that has more than five employees, retrieve the department number and the
number of its employees who are making more than $40,000.
SELECT DNUMBER, COUNT (*) FROM DEPARTMENT, EMPLOYEE
WHERE DNUMBER=DNO AND SALARY>40000 AND
DNO IN (SELECT DNO FROM EMPLOYEE
GROUP BY DNO
HAVING COUNT (*) > 5)
GROUP BY DNUMBER
With the help of set operators, the results of individual table expressions can be combined.
This type of combination is called UNION. SQL supports other set operators besides the UNION
operator.
Here is the complete list:
UNION
UNION ALL
INTERSECT
INTERSECT ALL
EXCEPT
EXCEPT ALL
Each SELECT statement within the UNION must have the same number of columns and similar data types.
By M.A
Page 10
Also, the columns in each SELECT statement must be in the same order.
FROM <table_name>
Note: The UNION operator selects only distinct values by default. To allow duplicate values,
use UNION ALL.
Each SELECT statement within the UNION must have similar data types. If this applies, the table
expressions are union compatible.
An ORDER BY clause can be specified only after the last table expression. The sorting is performed on the
entire end result; after all intermediate results have been combined.
The SELECT clauses should not contain DISTINCT because SQL automatically removes duplicate rows when
using UNION.
Combining with INTERSECT
INTERSECT returns all rows that are both in the result of query1 and in the result of query2. Duplicate
rows are eliminated unless ALL is specified.
If two table expressions are combined with the INTERSECT operator, the end result consists of those rows that
appear in the results of both table expressions.
EXCEPT returns all rows those are in the result of query1 but not in the result of query2. Again, duplicates
are eliminated unless ALL is specified.
If two table expressions are combined with the EXCEPT operator, the end result consists of only the rows that
appear in the result of the first table expression but do not appear in the result of the second.
Just as with the UNION operator, duplicate rows are automatically removed from the result.
By M.A
Page 11
SELECT
If the condition is true, statement1 and statement2 is executed; otherwise statement 3 and
statement 4 is executed.
The expression or condition is any expression built using relational operators which either
yields true or false condition.
Comparison operators are used in conditions that compare one expression with another.
SQL Comparison operator is used mainly with the SELECT statement to filter data based on specific conditions.
C
o
m
pa
ris
on
op
er
at
or
=
<>
,!
Description
equal to
is not equal to
By M.A
Page 12
less than
>
>=
<=
In
N
ot
In
Al
l
[N
ot]
be
tw
ee
n
Is
[n
ot]
nu
ll
greater than
greater than or equal to
less than or equal to
"Equivalent to any member of" test,
Equivalent to "= ANY".
When you want retrieving data using a SELECT statement, you can use logical operators in the WHERE clause
to combine more than one condition.
Example: Retrieve all students first name, last name, subject who are studying either Maths
or Science.
SELECT first_name, last_name,subject FROM student
The NOT operator inverts the result of a comparison expression or a logical expression.
By M.A
Page 13
Does X = Y? Is Y < X?
These are both questions that can be answered using a SQL Equality Operator expression.
SQL operators are generally found inside of queries-- more specifically, in the conditional
statements of the WHERE clause.
SELECT customer,day_of_order FROM orders
WHERE day_of_order > '7/31/08'
SQL mathematical operations can be performed using mathematical operators (+, -, *, /, and % (Modulo) and
comparisons operators ((<, >, and =)).
By M.A
Page 14
EMPLOYEE
2.2.
abs()
floor()
sqrt()
exp()
power()
Round()
abs() : This SQL ABS() returns the absolute value of a number passed as argument
Example: SELECT ABS(-17.36)FROM TRAINEE
floor() : The SQL FLOOR() rounded up any positive or negative decimal value down to the next least integer
unique value
value. SQL DISTINCT along with the SQL FLOOR() function is used to retrieve only
after rounded down to the next least integer value depending on the column specified.
Example: SELECT floor(17.26)FROM TRAINEE
By M.A
Page 15
exp() : The SQL EXP() returns e raised to the n-th power(n is the numeric expression), where e is the base of
natural algorithm and the value of e is approximately 2.71828183.
power() : This SQL POWER() function returns the value of a number raised to another, where both of the
numbers are passed as arguments.
sqrt() : The SQL SQRT() returns the square root of given value in the argument.
Example: SELECT SQRT(Credit)FROM TRAINEE
SQL Character Function
SQL character or string function is a function which takes one or more characters as
parameters and returns a character value. Some Character functions are -
lower() : The SQL LOWER() function is used to convert all characters of a string to lower case.
upper(): The SQL UPPER() function is used to convert all characters of a string to uppercase.
2.3.
AS Testing_Lower
FROM TRAINEE
AS Testing_Upper
FROM TRAINEE
GETDATE()
DATEPART()
DATEADD()
DATEDIFF()
GETDATE() : The GETDATE() function returns the current date and time from the SQL Server.
By M.A
Page 16
DATEPART() : The DATEPART() function is used to return a single part of a date/time, such as year,
month, day, hour, minute, etc.
Syntax: DATEPART(datepart,date)
DATEPART(mm,OrderDate) AS OrderMonth,
DATEPART(dd,OrderDate) AS OrderDay
FROM Orders
WHERE OrderId=1
Datepart
Abbreviation
Abbreviation
Datepart
Year
yy, yyyy
hour
hh
quarter
qq, q
minute
mi, n
month
mm, m
second
ss, s
dayofyear
dy, y
millisecond
ms
day
dd, d
microsecond
mcs
week
wk, ww
nanosecond
ns
weekday
dw, w
By M.A
Page 17
DATEADD() : The DATEADD() function adds or subtracts a specified time interval from a date.
Where date is a valid date expression and number is the number of interval you want to add. The number
can either be positive, for dates in the future, or negative, for dates in the past.
Syntax: DATEADD(datepart,number,date)
FROM Orders
DATEDIFF() : The DATEDIFF() function returns the time between two dates.
Syntax: DATEDIFF(datepart,startdate,enddate)
Example: Now we want to get the number of days between two dates. We use the following SELECT
statement:
Result: 61
Now we want to get the number of days between two dates (notice that the second date is "earlier" than the
first date, and will result in a negative number). We use the following SELECT statement:
SELECT DATEDIFF(day,'2008-08-05','2008-06-05') AS DiffDate
OrderId
1
2
3
4
ProductName
computer
Digital Camera
Printer
Scanner
OrderDate
2008-11-11
2008-11-09
2008-11-11
2008-10-29
Now we want to select the records with an OrderDate of "2008-11-11" from the table above.
ProductName
Computer
Printer
OrderDate
2008-11-11
2008-11-11
Now, assume that the "Orders" table looks like this (notice the time component in the "OrderDate"
column):
OrderId
1
2
3
4
ProductName
Computer
Digital Camera
Printer
Scanner
OrderDate
2008-11-11 13:23:44
2008-11-09 15:45:21
2008-11-11 11:12:01
2008-10-29 14:56:59
We will get no result! This is because the query is looking only for dates with no time portion.
Tip: If you want to keep your queries simple and easy to maintain, do not allow time components in your
dates!
2.4.
An aggregate function operates on many records and produces a summary; works with GROUP BY.
Useful SQL Aggregate Functions
MIN
MAX
SUM
AVG
COUNT
COUNT(*)
SUM()
Aggregate functions are used to compute against a "returned column of numeric data" from your SELECT
statement. They basically summarize the results of a particular column of selected data.
The count function Returns the number of items in expression. The data type returned is of type int.
With the exception of the COUNT (*) function, all aggregate functions return a NULL if no rows satisfy
the WHERE clause. The COUNT (*) function returns a value of zero if no rows satisfy the WHERE clause.
The MAX function Returns the maximum value from expression. Max ignores any NULL values.
The MIN function Returns the smallest value from expression. Min ignores any NULL values.
The SUM function Returns the total of all values in expression. Sum ignores any NULL values.
The AVERAGE function Returns the average of the values in expression. The expression must contain
numeric values. Null values are ignored.
syntax: AVG ([ ALL | DISTINCT ] <expression>)
Example: select ID, avg(Employee.Salary) from dbo. Employee
STDEV: Returns
STDEVP: Returns
VAR: Returns the variance of all values in expression. Var ignores any NULL values.
syntax: VAR( <expression> )
Example: select VAR(Employee.Salary) from dbo. Employee
VARP: Returns the variance for the population of all values in expression. Varp ignores any
NULL values. syntax: VARP( <expression> )
Example: select VARP(Employee.Salary) from dbo. Employee
the standard deviation of all values in expression. Stdev ignores any NULL
values. Syntax: STDEV( <expression> )
Example: select STDEV(Employee.Salary) from dbo. Employee
the standard deviation for the population of all values in expression. Stdevp
ignores any NULL values.
LO3. Write advanced SQL statements that use aggregation and filtering
3.1. SQL - Grouping By Multiple Columns
When an aggregate function is executed, SQL Server summarizes values for an entire table or for groups of
columns within the table, producing a single value for each set of rows for the specified columns.
- You can use aggregate functions with the SELECT statement or in combination with the GROUP BY
clause
- Use the GROUP BY clause on columns or expression to organize rows into groups and to summarize those
groups. The GROUP BY clause groups rows on the basis of similarities between them.
.
.
.
.
When you use the GROUP BY clause, consider the following facts and guidelines:
SQL Server returns only single rows for each group that you specify; it does not return detail information.
All columns that are specified in the GROUP BY clause must be included in the select list.
If you include a WHERE clause, SQL Server groups only the rows that satisfy the search conditions.
Do not use the GROUP BY clause on columns that contain multiple null values.
Example1: For each department, retrieve the department name, the number of employees in the
department, and their average salary; catagorize by the TraineeID, Departement and name respectively.
SELECT DEPARTEMENT.Dname ,
Example2: Retrieve all trainees TraineeID, Name, Departement , the number of course taken by each trainee and
catagorize by the TraineeID, Departement and name.
select TRAINEE .TraineeID ,
TRAINEE .Name,
TRAINEE .Departement,
group by customer_name
The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate
functions.
Basic syntax of having clause:
HAVING condition
3.1.3. SQL: Sub-select, sorting by aggregate review data
Subquery or Inner query or Nested query is a query in a query. A subquery is usually added in the
WHERE Clause of the sql statement. Most of the time, a subquery is used when you know how to
search for a value using a SELECT statement, but do not know the exact value.
Subqueries can be used with select, insert, update, and delete along with the comparision operators like
=, <, >, >=, <= etc.
Example: SELECT first_name, last_name, subject
FROM student_details
WHERE games NOT IN ('Cricket', 'Football');
1) Usually, a subquery should return only one record, but sometimes it can also return multiple records
when used with operators like IN, NOT IN in the where clause. The query would be like,
The output would be similar to:
first_
name
----------- Shek
ar
last
_na
me
---------- Go
wda
subj
ect
-------- Bad
mint
on
Cha
Che
ndr
ss
a
2) Lets consider the student_details table which we have used earlier. If you know the name of the students
who are studying science subject, you can get their id's by using this query below,
Priya
FROM student_details
WHERE first_name IN ('Rahul', 'Stephen');
but, if you do not know their names, then to get their id's you need to write the query in this manner,
SELECT id, first_name
FROM student_details
WHERE first_name IN (SELECT first_name
FROM student_details
WHERE subject= 'Science');
Output:
id
first_name
--- --------------- 100
Rahul
102
Stephen
In the above sql statement, first the inner query is processed first and then the outer query is processed.
3) Subquery can be used with INSERT statement to add rows of data from one or more tables to another
table. Lets try to group all the students who study Maths in a table 'maths_group'.
INSERT INTO maths_group(id, name)
SELECT id, first_name || ' ' || last_name
FROM student_details WHERE subject= 'Maths'
4) A subquery can be used in the SELECT statement as follows. Lets use the product and order_items table
defined in the sql_joins section.
select p.product_name, p.supplier_name, (select order_id from order_items where
product_id = 101) as order_id from product p where p.product_id = 101
product_
name
supplier
_name
-----------------
-----------------
Television
Onida
or
de
r_i
d
------ 51
03
Correlated Subquery
A query is called correlated subquery when both the inner query and the outer query are interdependent.
For every row processed by the inner query, the outer query is processed as well. The inner query depends
on the outer query before it can be processed.
SELECT p.product_name FROM product p
WHERE p.product_id = (SELECT o.product_id FROM order_items o
WHERE o.product_id = p.product_id);
NOTE:
1) You can nest as many queries you want but it is recommended not to nest more than 16 subqueries in
oracle.
2) If a subquery is not dependent on the outer query it is called a non-correlated subquery.
SQL SubSelect-SubQueries
A sub query or sub select is a select statement that returns a single value
output result and it can be nested inside other subquery or any SELECT, INSERT,
DELETE OR UPDATE statement.
Example:
USE NORTHWIND
SELECT P.PRODUCTNAME,
(SELECT CATEGORYNAME FROM CATEGORIES WHERE CATEGORYID = P.CATEGORYID)
FROM PRODUCTS P
Subquery used in the above example returns the category name of each product
in every tuple.
Example:
SELECT P.PRODUCTNAME, P.UNITPRICE, P.CATEGORYID
FROM
PRODUCTS P
WHERE
P.PRODUCTID = (SELECT PRODUCTID FROM PRODUCTS WHERE PRODUCTNAME='VEGIE-SPREAD')
Here subquery returns product id as single value to the main SQL query.
Example:
SELECT C.CATEGORYNAME,
(SELECT TOP 1 P.PRODUCTNAME FROM PRODUCTS P WHERE P.CATEGORYID=C.CATEGORYID ORDER BY
P.UNITPRICE DESC),
(SELECT TOP 1 P.UNITPRICE FROM PRODUCTS P WHERE P.CATEGORYID=C.CATEGORYID ORDER BY
P.UNITPRICE DESC),
(SELECT MAX(P.UNITPRICE) FROM PRODUCTS P WHERE P.CATEGORYID=C.CATEGORYID)
4.1
4.2
Subqueries
A subquery is a query that is nested inside a SELECT, INSERT, UPDATE, or DELETE statement, or inside
another subquery.
- Subquery is an inner query or inner select, while the statement containing a subquery is also called an outer
query or outer select.
- You use subqueries to break down a complex query into a series of logical steps and, as a result, to solve a
problem with single statements.
- Each select statement in the subquery has its own:
. select list
.
where clause
Example: For each department that has more than five employees, retrieve the department number and the
number of its employees who are
making more than $40,000.
4.3.
The IN operator is an operator that allows you to specify multiple values in a WHERE clause.
A row from a table satisfies a condition with the IN operator if the value of a particular column occurs in a
set of expressions. The expressions in such a set entered one by one by a user.
Syntax to use IN
Examle: SELECT *
SELECT *
Any operator
ANY operator is an operator that compares a value to each value in a list or results from a query and
evaluates to true if the result of an inner query contains at least one row. ANY must be preceded by
comparison operators.
Syntax to use Any operator: SELECT column_name(s)
FROM table_name
where Dnumber='ict001')
All operators
ALL operator is used to select all records of a SELECT STATEMENT. It compares a value to every value
in a list or results from a query. The ALL must be preceded by the comparison operators and evaluates to
TRUE if the query returns no rows. For example, ALL means greater than every value, means greater than
the maximum value. Suppose ALL (1, 2, 3) means greater than 3.
Syntax to use All operator: SELECT column_name(s)
FROM table_name
WHERE Dnum=5);
SOME operators
SOME operator is the same as ANY operator (SOME and ANY perform the same function).
SOME compares a value to each value in a list or results from a query and evaluates to true if the result of
an inner query contains at least one row.
SOME must match at least one row in the subquery and must be preceded by comparison operators.
Example: SELECT ID,Fname,Lname FROM EMPLOYEE
WHERE Gender='Female');
EXISTS operator
The EXIST operator checks the existence of a result of a subquery. The EXISTS subquery tests whether a
subquery fetches at least one row. When no data is returned then this operator returns 'FALSE'.
- A valid EXISTS subquery must contain an outer reference and it must be a correlated subquery.
- You can use the EXISTS and NON EXISTS operators to determine whether data exists in a list of values.
- Use the EXISTS and NOT EXISTS operators with correlated subqueries to restrict the result set of an outer
query to rows that satisfy the subquery.
Example: SELECT DepID ,Fname ,Gender FROM DEPENDENTED
You can use the EXISTS operator with the group by as wel as order by clause to determine whether data
exists in a list of values.
Example: SELECT dnum,COUNT (*)'Number of employee who has dependent' FROM EMPLOYEE
group by EmpID)
group by Dnum
order by Dnum
having clause
Use the HAVING clause on columns or expressions to set conditions on the groups included in a result set.
The HAVING clause sets conditions on the GROUP BY clause in much the same way that the WHERE
clauses interacts with the SELECT statement.
Example: SELECT dnum ,count(*)'number of employee' FROM EMPLOYEE
group by Dnum
having COUNT(*)>2
4.4.
Correlated subqueries
In a SQL database query, a correlated sub-query (also known as a synchronized subquery) is a sub-query
(a query nested inside another query) that uses values from the outer query in its WHERE clause.
-
Correlated subquery is one that is executed after the outer query is executed. So correlated subqueries take
an approach opposite to that of the normal subqueries.
In a correlated subquery, the inner query uses information from the outer query and executes once for every
row in the outer query.
A practical use of a correlated subquery is to transfer data from one table to another.
where
a.column_name_a=b.column_name_b)
Example: find out the name of all EMPLOYEES who has less or equal to two dependent using correlated
subquery.
SELECT columns
FROM tables
WHERE predicates
ORDER BY column ASC/DESC;
The SQL ORDER BY clause sorts the result set based on the columns specified. If the ASC or DESC value
is omitted, it is sorted by ASC.
ASC indicates ascending order. (default)
DESC indicates descending order.
SQL ORDER BY
The ORDER BY clause is used in a SELECT statement to sort results either in ascending or descending
order. Oracle sorts query results in ascending order by default.
Syntax for using SQL ORDER BY clause to sort data is:
SELECT column-list
FROM table_name [WHERE condition]
[ORDER BY column1 [, column2, .. columnN] [DESC]];
n
a
m
e
R
a
m
1
e
s
h
H
r
i
t
1
h
i
k
sal
locatio
n
Elec
trica
l
25
Bangal
ore
Elec
troni
cs
35
Bangal
ore
dept
H
a
Aer
r
onau
2
35
Mysore
s
tics
h
a
S
o
Elec
u
Bangal
troni
2
20
m
ore
cs
y
a
P
r
Info
Mangal
i
2
30
Tech
ore
y
a
For Example: If you want to sort the employee table by salary of the employee, the sql query would be.
The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on one or
more columns. Some database sorts query results in ascending order by default.
Syntax:
The basic syntax of ORDER BY clause is as follows:
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to
sort, that column should be in column-list.
Description
The ORDER BY clause orders or sorts the result of a query according to the values in one or more specific
columns. More than one columns can be ordered one within another. It depends on the user that, whether to
order them in ascending or descending order. The default order is ascending.
The SQL ORDER BY clause is used with the SQL SELECT statement.
Note : SQL ORDER BY clause always come at the end of a SELECT statement.
Syntax
1. SELECT <column_list> FROM < table name >.
2. WHERE <condition>
3. ORDER BY <columns> [ASC | DESC];
- See more at: http://www.w3resource.com/sql/order-by.php#sthash.INkeMeAW.dpuf