1. MS SQL Server 2005
Lab # 4 :
Practicing Queries, part #2
Complex Queries
Adavnced Database Programming 1
2. 2. Complex Queries
WHERE Clause Form:
USE database_name
SELECT Column_List
[ INTO New_table ]
From table1[table2,….]
[ WHERE conditions ]
[ GROUP BY group_by_expression ]
[ HAVING search_conditions ]
[ ORDER BY order_expression[ASC|DESC] ]
Adavnced Database Programming 2
3. Subqueries
An Outer query contains an Inner query,
which can be included in the WHERE Clause
or in the FROM Clause
Outer Query:
SELECT
FROM
WHERE (Inner Query)
Outer Query:
SELECT
FROM (Inner Query)
Adavnced Database Programming 3
4. Subqueries And Comparison Operators
Example :
Q: View all Employees First & Last name who work in
Innovation Department
A:
Use Company
Select FName, LName
From Employee
where DNO=( Select DNumber
From Department
Where DName=‘Innovation’)
Adavnced Database Programming 4
5. Subqueries And Comparison Operators
Example :
Q: View all Employees Last name who work on project Building
A:
Use Company
SelectLName
From Employee
where SSN IN( Select ESSN
From Works_On
Where PNO IN(SELECT PNumber
From Project
WHERE PName=‘Building’))
Can we Substitute the IN clause with = ?
Adavnced Database Programming 5
6. Subqueries (Inner Query included in FROM
Clause)
Example :
Q: View all Employees Last name who their SSN
is greater than 1000
A:
Use Company
Select LName Should I give
the inner query
From (Select * result a name?
From Employee
Where SSN>1000) AS NewEmp
Adavnced Database Programming 6
7. Subqueries ( ANY & ALL Operators )
ANY: Returns true if the result of an inner query
contains at least one row that satisfies the
comparison
ALL: Evaluates true if the evaluation of the table
column in the inner query returns all values of that
column
Syntax :
Outer_query column operator [ANY | ALL] Inner_query
Adavnced Database Programming 7
8. Subqueries ( ANY & ALL Operators )
Example :
Q: View the oldest Employees SSN who their
BDate is less than all other employees
A:
Use Company
Select SSN
From Employee
where Bdate>=ALL (Select BDate
From Employee)
Adavnced Database Programming 8
9. EXIST Function
Checks the inner query of a subquery and
evaluates to true if its result contains at least
one row
Syntax:
[NOT] EXISTS (query)
Adavnced Database Programming 9
10. EXIST Function
Q: View all employees info only if there is an
employee who’s salary is 5000
A:
Use Company
Select *
From Employee
where Exists (Select *
From Employee
Where salary=5000)
Adavnced Database Programming 10
11. GROUP BY Clause
Defines one or more columns as a group
such that all rows within any group have the
same values for those columns
ALL columns specified in the SELECT clause
must appear in the GROUP BY clause
If an aggregate function appears in the
SELECT clause, then you can’t include a
simple column in it unless if its used in the
Group By clause
Adavnced Database Programming 11
12. GROUP BY Clause
Q: For each Project View all employees SSN
with hours working on more than 20 hours
A:
Use Company
Select PNO,Hours,ESSN
From Works_On
where hours>20
Group by PNO,Hours,ESSN
Adavnced Database Programming 12
13. GROUP BY Clause
Example :
Q: How many Employees works in each
project?
A:
Use Company
Select PNumber ,COUNT(*) emp_count
From Works_IN
Group by PNumber
Adavnced Database Programming 13
14. HAVING Clause
Defines conditions that is then applied to groups of
rows (Such as WHERE Clause condition applied on
rows) and its Syntax: HAVING condition
Q: Get Project numbers for all projects employing less
than four persons
A:
Use Company
Select PNO
From Works_On
Group by PNO
Having Count(*)<4
Adavnced Database Programming 14
15. HAVING Clause
Example :
Q: View Projects names that their name starts
with S
A:
Use Company
Select PName
From Project
Group by PName
HAVING PName LIKE ‘S%’
Adavnced Database Programming 15
16. ORDER BY Clause
Defines the order of the rows in the result and its
Syntax:
ORDER BY [col_name | col_no [ASC | DESC]] , …
Q: Get employees all info ordered by their SSN
A:
Use Company
Select *
From Employee
Order BY SSN
Adavnced Database Programming 16
17. ORDER BY Clause
Q: Get employees first & last names ordered by
their last name then their first name
A:
Use Company
Select FName, LName
From Employee
Order BY LName, FName
Adavnced Database Programming 17
18. ORDER BY Clause
Q: Get employees first & last names ordered by
their last name Ascending and then their first
name Descending
A:
Use Company
Select FName, LName
From Employee
Order BY 2 Asc, 1 DESC
Adavnced Database Programming 18
19. INTO Clause
It performs two parts:
1. Create a new table with columns as same the
columns specified in the select clause
2. Insert the rows that matches the query into the
new table
Basic INTO form:
Use database_name
Select columns_List
INTO NewTableName
From table(s)
Adavnced Database Programming 19
20. INTO Clause
Q: Create a separate table for all employees
who aren’t supervised
A:
Use Company
Select *
INTO Head_Supervisors
From Employee
Where MGRSSN IS NULL
Adavnced Database Programming 20
21. Set Operators
UPDATE table_name SET column_name =
newValue
WHERE condition
EX.
UPDATE employee SET Salary=32400
WHERE SSN=2341
Adavnced Database Programming 21
22. Set Operators
Union
is the set of all elements appearing in either
or both of tables
Form: Query_1 UNION [ALL]Query_2 …
ALL option includes all resulting rows
including duplicates are to be displayed
Adavnced Database Programming 22
23. Set Operators ( UNION)
Q: View all employees numbers who either belong to department 5
or work on their project more than 20 hours in ascending order of
employee number
A:
Use Company
Select SSN
From Employee
Where DNO=5
UNION
Select ESSN
From Works_On
Where Hours>20
Order By 1
Adavnced Database Programming 23
24. Set Operators
INTERSECTION
is the set of all elements belongs to both of
the tables
Form: Query_1 INTERSECT Query_2 …
Adavnced Database Programming 24
25. Set Operators ( INTERSECT)
Q: View all employees numbers who belong to department 5 and
work on their project more than 20 hours in ascending order of
employee number
A:
Use Company
Select SSN
From Employee
Where DNO=5
INTERSECT
Select ESSN
From Works_On
Where Hours>20
Order By 1
Adavnced Database Programming 25
26. Set Operators
DIFFERENCE
is the set of all elements belongs to the first
table but doesn’t belong to the second table
Form: Query_1 EXCEPT Query_2 …
Adavnced Database Programming 26
27. Set Operators (EXCEPT)
Q: View all employees numbers who belongs to department 5
except those who work on their project more than 20 hours in
ascending order of employee number
A:
Use Company
Select SSN
From Employee
Where DNO=5
EXCEPT
Select ESSN
From Works_On
Where Hours>20
Order By 1
Adavnced Database Programming 27
28. CASE Expression
CASE Basic form:
CASE expression_1
{WHEN exp_2 THEN result_1}
{ELSE result_n}
END
Adavnced Database Programming 28
29. CASE Expression
Q: View all employees SSN,FNAME,Lname and Grade as following:
Salary Employee Grade:
0-6000 1 , 6000-15000 2 , 15000-22000 3 ,
>22000 4
A:
Use Company
Select SSN,FNAME,LNAME,
CASE
when Salary>0 and Salary<=6000 Then 1
when Salary>6000 and Salary<=15000 Then 2
when Salary>15000 and Salary<=22000 Then 3
ELSE 4
END Employee_Grade Column name after END
From Employee
Adavnced Database Programming 29
30. COMPUTE Clause
Uses aggregate function(Min, Max,…) to calculate
summary values that appear as additional rows in
the result of query
Basic COMPUTE form:
Use database_name
Select columns_List
From table(s)
Where condition
COMPUTE aggre_Func(column_name)
Adavnced Database Programming 30
31. COMPUTE Clause
Q: View all employees numbers, project their working
on, and working hours for employees work on
project 3 or 10. And view the minimum working
hours
A:
Use Company
Select *
From Works_on
Where PNO=3 OR PNO=10
Compute MIN(Hours)
Adavnced Database Programming 31
32. COMPUTE Clause (Using BY option)
Q: View all employees numbers, project their working
on, and working hours for employees work on
project 3 or 10. And view the minimum working
hours for each project
A:
Use Company
Select *
From Works_on
Where PNO=3 OR PNO=10
Order By PNO
Compute MIN(Hours) BY PNO
Adavnced Database Programming 32
33. COMPUTE Clause(Multiple aggregate
function)
Q: View all employees numbers, project their working on,
and working hours for employees work on project 3 or
10. And view the minimum, maximum, avrage working
hours
A:
Use Company
Select *
From Works_on
Where PNO=3 OR PNO=10
Compute MIN(Hours), MAX(Hours), AVG(Hours)
Adavnced Database Programming 33
34. COMPUTE Clause
SELCET INTO is not allowed (because the
result of the COMPUTE clause is not a
table)
All columns in the COMPUTE clause must
appear in the SELECT list
The name of each column in the COMPUTE
BY clause must appear in the ORDER BY
clause
The order of the columns in the COMPUTE
BY & ORDER BY clauses must be identical
Adavnced Database Programming 34