SQL Queries Basics & Advanced
SQL Queries Basics & Advanced
Chapter 4: SQL
SQL queries
• SQL queries are expressed by the select statement
• Syntax:
select AttrExpr [[ as ] Alias ] {, AttrExpr [[ as ] Alias ] }
from Table [[ as ] Alias ] {, [[ as ] Alias ] }
[ where Condition ]
• The three parts of the query are usually called:
– target list
– from clause
– where clause
• The query considers the cartesian product of the tables in the
from clause, considers only the rows that satisfy the condition
in the where clause and for each row evaluates the attribute
expressions in the target list
McGraw-Hill and Atzeni, Ceri, Paraboschi, Torlone 1999
21
Database Systems (Atzeni, Ceri, Paraboschi, Torlone)
Chapter 4: SQL
Example database
EMPLOYEE FirstName Surname Dept Office Salary City
Mary Brown Administration 10 45 London
Charles White Production 20 36 Toulouse
Gus Green Administration 20 40 Oxford
Jackson Neri Distribution 16 45 Dover
Charles Brown Planning 14 80 London
Laurence Chen Planning 7 73 Worthing
Pauline Bradshaw Administration 75 40 Brighton
Alice Jackson Production 20 46 Toulouse
• Result:
Remuneration
45
80
• Result:
Attribute expressions
• Find the monthly salary of the employees named White:
select Salary / 12 as MonthlySalary
from Employee
where Surname = ‘White’
• Result:
MonthlySalary
3.00
Table aliases
• Find the names of the employees and the cities in which they
work (using an alias):
select FirstName, Surname, D.City
from Employee, Department D
where Dept = DeptName
Predicate conjunction
• Find the first names and surnames of the employees who work
in office number 20 of the Administration department:
select FirstName, Surname
from Employee
where Office = ‘20’ and
Dept = ‘Administration’
• Result:
FirstName Surname
Gus Green
Predicate disjunction
• Find the first names and surnames of the employees who work
in either the Administration or the Production department:
select FirstName, Surname
from Employee
where Dept = ‘Administration’ or
Dept = ‘Production’
• Result:
FirstName Surname
Mary Brown
Charles White
Gus Green
Pauline Bradshaw
Alice Jackson
Operator like
• Find the employees with surnames that have ‘r’ as the second
letter and end in ‘n’:
select *
from Employee
where Surname like ‘_r%n’
• Result:
Duplicates
• In relational algebra and calculus the results of queries do not
contain duplicates
• In SQL, tables may have identical rows
• Duplicates can be removed using the keyword distinct
Left join
• Find the drivers with their cars, including the drivers without
cars:
select FirstName, Surname, Driver.DriverID
CarRegNo, Make, Model
from Driver left join Automobile on
(Driver.DriverID = Automobile.DriverID)
• Result:
FirstName Surname DriverID CarRegNo Make Model
Mary Brown VR 2030020Y ABC 123 BMW 323
Mary Brown VR 2030020Y DEF 456 BMW Z3
Charles White PZ 1012436B GHI 789 Lancia Delta
Marco Neri AP 4544442R NULL NULL NULL
Full join
• Find all the drivers and all the cars, showing the possible
relationships between them:
select FirstName, Surname, Driver.DriverID
CarRegNo, Make, Model
from Driver full join Automobile on
(Driver.DriverID = Automobile.DriverID)
• Result:
FirstName Surname DriverID CarRegNo Make Model
Mary Brown VR 2030020Y ABC 123 BMW 323
Mary Brown VR 2030020Y DEF 456 BMW Z3
Charles White PZ 1012436B GHI 789 Lancia Delta
Marco Neri AP 4544442R NULL NULL NULL
NULL NULL NULL BBB 421 BMW 316
Table variables
• Table aliases may be interpreted as table variables
• They correspond to the renaming operator ρ of relational
algebra
• Find all the same surname (but different first names) of an
employee belonging to the Administration department:
select E1.FirstName, E1.Surname
from Employee E1, Employee E2
where E1.Surname = E2.Surname and
E1.FirstName <> E2.FirstName and
E2.Dept = ‘Administration’
• Result:
FirstName Surname
Charles Brown
Ordering
• The order by clause, at the end of the query, orders the rows
of the result; syntax:
order by OrderingAttribute [ asc | desc ]
{, OrderingAttribute [ asc | desc ] }
• Extract the content of the AUTOMOBILE table in descending order
of make and model:
select *
from Automobile
order by Make desc, Model desc
• Result: CarRegNo Make Model DriverID
GHI 789 Lancia Delta PZ 1012436B
DEF 456 BMW Z3 VR 2030020Y
ABC 123 BMW 323 VR 2030020Y
BBB 421 BMW 316 MI 2020030U
McGraw-Hill and Atzeni, Ceri, Paraboschi, Torlone 1999
41
Database Systems (Atzeni, Ceri, Paraboschi, Torlone)
Chapter 4: SQL
Aggregate queries
• Aggregate queries cannot be represented in relational algebra
• The result of an aggregate query depends on the consideration
of sets of rows
• SQL-2 offers five aggregate operators:
– count
– sum
– max
– min
– avg
Operator count
• count returns the number of rows or distinct values; syntax:
count(< * | [ distinct | all ] AttributeList >)
• Find the number of employees:
select count(*)
from Employee
• Find the number of different values on the attribute Salary for all
the rows in EMPLOYEE:
select count(distinct Salary)
from Employee
• Find the number of rows of EMPLOYEE having a not null value on
the attribute Salary:
select count(all Salary)
from Employee
McGraw-Hill and Atzeni, Ceri, Paraboschi, Torlone 1999
43
Database Systems (Atzeni, Ceri, Paraboschi, Torlone)
Chapter 4: SQL
• Result: SumSalary
125
• Result: MaxLondonSal
80
Group by queries
• Queries may apply aggregate operators to subsets of rows
• Find the sum of salaries of all the employees of the same
department:
select Dept, sum(Salary)as TotSal
from Employee
group by Dept
Dept Salary
Administration 45
Production 36
Administration 40
Distribution 45
Planning 80
Planning 73
Administration 40
Production 46
Group predicates
• When conditions are on the result of an aggregate operator, it is
necessary to use the having clause
• Find which departments spend more than 100 on salaries:
select Dept
from Employee
group by Dept
having sum(Salary) > 100
• Result:
Dept
Administration
Planning
where or having?
select Dept
from Employee
where Office = ‘20’
group by Dept
having avg(Salary) > 25
Set queries
• A single select cannot represent unions
• Syntax:
Intersection
• Find the surnames of employees that are also first names:
select FirstName as Name
from Employee
intersect
select Surname
from Employee
• equivalent to:
select E1.FirstName as Name
from Employee E1, Employee E2
where E1.FirstName = E2.Surname
Difference
• Find the surnames of employees that are not also first names:
select FirstName as Name
from Employee
except
select Surname
from Employee
Nested queries
• In the where clause may appear predicates that:
– compare an attribute (or attribute expression) with the result
of an SQL query; syntax:
ScalarValue Operator < any | all > SelectSQL
• any: the predicate is true if at least one row returned by
SelectSQL satisfies the comparison
• all: the predicate is true if all the rows returned by
SelectSQL satisfy the comparison
– use the existential quantifier on an SQL query; syntax:
exists SelectSQL
• the predicate is true if SelectSQL returns a non-empty
result
• The query appearing in the where clause is called nested query
Tuple constructor
• The comparison with the nested query may involve more than
one attribute
• The attributes must be enclosed within a pair of curved brackets
(tuple constructor)
• The previous query can be expressed in this way:
select *
from Person P
where (FirstName,Surname) not in
(select FirstName, Surname
from Person P1
where P1.TaxCode <> P.TaxCode)
Scope of variables
• Incorrect query:
select *
from Employee
where Dept in
(select DeptName
from Department D1
where DeptName = ‘Production’) or
Dept in (select DeptName
from Department D2
where D2.City = D1.City)
• The query is incorrect because variable D1 is not visible in the
second nested query