sql server lab_4
TRANSCRIPT
Adavnced Database Programming 1
MS SQL Server MS SQL Server 20052005
Lab # 4 : Practicing Queries, part #2
Complex Queries
Adavnced Database Programming 2
2. Complex Queries
WHERE Clause Form:
USE database_nameSELECT 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 3
Subqueries
An Outer query contains an Inner query, which can be included in the WHERE Clause or in the FROM Clause
Outer Query:SELECTFROMWHERE (Inner Query)
Outer Query:SELECTFROM (Inner Query)
Adavnced Database Programming 4
Subqueries And Comparison Operators
Example :Q:Q: View all Employees First & Last name who work in Innovation Department
A:A:Use CompanySelect FName, LNameFrom Employeewhere DNO=( Select DNumber
From Department Where DName=‘Innovation’)
Adavnced Database Programming 5
Subqueries And Comparison Operators
Example :Q:Q: View all Employees Last name who work on project Building
A:A:Use CompanySelect LNameFrom Employeewhere 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 6
Subqueries (Inner Query included in FROM Clause)
Example :Q:Q: View all Employees Last name who their SSN is greater than 1000
A:A:Use CompanySelect LNameFrom (Select *
From Employee Where SSN>1000) AS NewEmp
Should I give the inner query result a name?
Adavnced Database Programming 7
Subqueries ( ANY & ALL Operators )
ANY:ANY: Returns true if the result of an inner query contains at least one row that satisfies the comparison
ALL: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 8
Subqueries ( ANY & ALL Operators )
Example :Q:Q: View the oldest Employees SSN who their BDate is less than all other employees
A:A:Use CompanySelect SSNFrom Employeewhere Bdate>=ALL (Select BDate
From Employee)
Adavnced Database Programming 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 10
EXIST Function
Q:Q: View all employees info only if there is an employee who’s salary is 5000
A:A:
Use CompanySelect *
From Employeewhere Exists (Select *
From Employee
Where salary=5000)
Adavnced Database Programming 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 12
GROUP BY Clause
Q:Q: For each Project View all employees SSN with hours working on more than 20 hours
A:A:
Use CompanySelect PNO,Hours,ESSN
From Works_Onwhere hours>20
Group by PNO,Hours,ESSN
Adavnced Database Programming 13
GROUP BY Clause
Example :
Q:Q: How many Employees works in each project?A:A:
Use CompanySelect PNumber ,COUNT(*)
emp_count
From Works_IN
Group by PNumber
Adavnced Database Programming 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:Q: Get Project numbers for all projects employing less than four persons
A:A:Use CompanySelect PNOFrom Works_OnGroup by PNOHaving Count(*)<4
Adavnced Database Programming 15
HAVING Clause
Example :
Q:Q: View Projects names that their name starts with SA: A:
Use CompanySelect PName
From Project
Group by PName
HAVING PName LIKE ‘S%’
Adavnced Database Programming 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:Q: Get employees all info ordered by their SSN
A:A:
Use CompanySelect *
From Employee
Order BY SSN
Adavnced Database Programming 17
ORDER BY Clause
Q:Q: Get employees first & last names ordered by their last name then their first name
A:A:
Use CompanySelect FName, LName
From Employee
Order BY LName, FName
Adavnced Database Programming 18
ORDER BY Clause
Q:Q: Get employees first & last names ordered by their last name Ascending and then their first name Descending
A:A:
Use CompanySelect FName, LName
From Employee
Order BY 2 Asc, 1 DESC
Adavnced Database Programming 19
INTO Clause
It performs two parts:1. Create a new table with columns as same the
columns specified in the select clause2. Insert the rows that matches the query into the
new table
Basic INTO form:Use database_nameSelect columns_ListINTO NewTableNameFrom table(s)
Adavnced Database Programming 20
INTO Clause
Q:Q: Create a separate table for all employees who aren’t supervised
A:A:
Use CompanySelect *INTO Head_Supervisors
From Employee
Where MGRSSN IS NULL
Adavnced Database Programming 21
Set Operators
UPDATE table_name SET column_name = newValueWHERE condition
EX.UPDATE employee SET Salary=32400WHERE SSN=2341
Adavnced Database Programming 22
Set Operators
UnionUnionis the set of all elements appearing in either or both of tablesForm: Query_1 UNION [ALL]Query_2 …ALL option includes all resulting rows including duplicates are to be displayed
Adavnced Database Programming 23
Set Operators ( UNION)
Q: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:A:Use CompanySelect SSNFrom EmployeeWhere DNO=5
UNIONSelect ESSNFrom Works_OnWhere Hours>20Order By 1
Adavnced Database Programming 24
Set Operators
INTERSECTIONINTERSECTION is the set of all elements belongs to both of the tables
Form: Query_1 INTERSECT Query_2 …
Adavnced Database Programming 25
Set Operators ( INTERSECT)
Q: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:A:Use CompanySelect SSNFrom EmployeeWhere DNO=5
INTERSECTSelect ESSNFrom Works_OnWhere Hours>20Order By 1
Adavnced Database Programming 26
Set Operators
DIFFERENCEDIFFERENCEis 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 27
Set Operators (EXCEPT)
Q: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:A:Use CompanySelect SSNFrom EmployeeWhere DNO=5
EXCEPTSelect ESSNFrom Works_OnWhere Hours>20Order By 1
Adavnced Database Programming 28
CASE Expression
CASE Basic form:CASE Basic form:CASE expression_1
{WHEN exp_2 THEN result_1}{ELSE result_n}
END
Adavnced Database Programming 29
CASE Expression
Q:Q: View all employees SSN,FNAME,Lname and Grade as following:Salary Employee Grade:0-6000 1 , 6000-15000 2 , 15000-22000 3 ,
>22000 4A:A:
Use CompanySelect SSN,FNAME,LNAME, CASE
when Salary>0 and Salary<=6000 Then 1when Salary>6000 and Salary<=15000 Then 2when Salary>15000 and Salary<=22000 Then 3ELSE 4
END Employee_GradeFrom Employee
Column name after END
Adavnced Database Programming 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_nameSelect columns_List
From table(s)
Where condition
COMPUTE aggre_Func(column_name)
Adavnced Database Programming 31
COMPUTE Clause
Q: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:A:
Use CompanySelect *
From Works_on
Where PNO=3 OR PNO=10
Compute MIN(Hours)
Adavnced Database Programming 32
COMPUTE Clause (Using BY option)Q: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:A:Use CompanySelect *From Works_onWhere PNO=3 OR PNO=10Order By PNOCompute MIN(Hours) BY PNO
Adavnced Database Programming 33
COMPUTE Clause(Multiple aggregate function)Q: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:A:
Use CompanySelect *
From Works_on
Where PNO=3 OR PNO=10
Compute MIN(Hours), MAX(Hours), AVG(Hours)
Adavnced Database Programming 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