04-05 - SQL-2up csc343
04-05 - SQL-2up csc343
1
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 first builds the Cartesian product of the
tables in the from clause, then selects only the rows
that satisfy the condition in the where clause and for
each row evaluates the attribute expressions in the
target list.
CSC343 Introduction to Databases — University of Toronto SQL — 3
Example Database
2
Simple SQL Query
Æ"Find the salaries of employees named Brown":
select Salary as Remuneration
from Employee
where Surname = ‘Brown’
ÆResult:
Remuneration
45
80
ÆResult:
3
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
4
Table Aliases
Æ"Find the names of employees and the cities
where they work" (using an alias):
select FirstName, Surname, D.City
from Employee, Department D
where Dept = DeptName
FirstName Surname City
Mary Brown London
ÆResult: Charles White Toulouse
Gus Green London
Jackson Neri Brighton
Charles Brown London
Laurence Chen London
Pauline Bradshaw London
Alice Jackson Toulouse
CSC343 Introduction to Databases — University of Toronto SQL — 9
Predicate Conjunction
Æ"Find the first names and surnames of
employees who work in office number 20 of the
Administration department":
select FirstName, Surname
from Employee
where Office = ‘20’ and
Dept = ‘Administration’
FirstName Surname
ÆResult:
Gus Green
5
Predicate Disjunction
Æ"Find the first names and surnames of
employees who work in either the
Administration or the Production department":
select FirstName, Surname
from Employee
where Dept = ‘Administration’ or
Dept = ‘Production’
FirstName Surname
Mary Brown
ÆResult: Charles White
Gus Green
Pauline Bradshaw
Alice Jackson
6
Operator like
Æ"Find employees with surnames that have ‘r’ as
the second letter and end in ‘n’":
0 or more chars
select *
from Employee
where Surname like ‘_r%n’
exactly 1 char
ÆResult:
7
Algebraic Interpretation of SQL
Queries
ÆThe generic query:
select T1.Attr11, …, Th.Attrhm
from Table1 T1, …, Tablen Tn
where Condition
corresponds to the relational algebra query:
πT1.Attr11,…,Th.Attrhm(σCondition(Table1 ×… ×
Tablen))
Duplicates
ÆIn the 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:
select City select distinct City
from Department from Department
City
London City
Toulouse London
Brighton Toulouse
London Brighton
San José San José
CSC343 Introduction to Databases — University of Toronto SQL — 16
8
Joins in SQL-2
ÆSQL-2 introduced an alternative syntax for the
representation of joins, representing them explicitly in
the from clause:
select AttrExpr [[ as ] Alias ] {, AttrExpr [[as] Alias
from Table [[as] Alias ]
{[JoinType] join Table
[[as] Alias] on JoinConditions }
[ where OtherCondition ]
ÆJoinType can be any of inner, right [outer],
left [outer] or full [outer].
ÆThe keyword natural may precede JoinType
(rarely implemented).
CSC343 Introduction to Databases — University of Toronto SQL — 17
9
Another Example:
Drivers and Cars
Left Join
Æ"Find all drivers and their cars, if any":
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
CSC343 Introduction to Databases — University of Toronto SQL — 20
10
Full Join
Æ"Find all possible drivers and their cars":
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
CSC343 Introduction to Databases — University of Toronto SQL — 21
Table Variables
ÆTable aliases may be interpreted as table variables.
These correspond to the renaming operator ρ.
Æ"Find all first names and surnames of employees who
have the same surname and different first names with
someone in 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
CSC343 Introduction to Databases — University of Toronto SQL — 22
11
The order by Clause
Æorder by — appearing at the end of a 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 with respect to make and
model:
select *
from Automobile
order by Make desc, Model desc
CarRegNo Make Model DriverID
ÆResult: GHI 789 Lancia Delta PZ 1012436B
DEF 456 BMW Z3 VR 2030020Y
ABC 123 BMW 323 VR 2030020Y
BBB 421 BMW 316 MI 2020030U
CSC343 Introduction to Databases — University of Toronto SQL — 23
Aggregate Queries
12
Operator count
Æcount returns the number of elements (or, distinct
elements) of its argument:
count(< * | [ distinct | all ] AttributeList >)
Æ"Find the number of employees":
select count(*)from Employee
Æ"Find the number of different values on attribute
Salary for all tuples in Employee":
select count(distinct Salary)
from Employee
Æ"Find the number of tuples in Employee having non-
null values on the attribute Salary":
select count(all Salary) from Employee
CSC343 Introduction to Databases — University of Toronto SQL — 25
Sum, Average,
Maximum and Minimum
ÆSyntax:
< sum | max | min | avg > ([ distinct | all ]
AttributeExpr )
Æ"Find the sum of all salaries for the Administration
department":
select sum(Salary) as SumSalary
from Employee
where Dept = ‘Administration’
ÆResult: SumSalary
125
13
Aggregate Queries with Join
Æ"Find the maximum salary among the employees
who work in a department based in London":
select max(Salary) as MaxLondonSal
from Employee, Department
where Dept = DeptName and
Department.City = ‘London’
ÆResult: MaxLondonSal
80
14
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 TotSal
Administration 125
ÆResult: Distribution 45
Planning 153
Production 82
15
Semantics of group by Queries - II
Æ… then the query result is divided in subsets
characterized by the same values for the
attributes appearing as argument of the
group by clause (in this case attribute Dept):
ÆFinally, the aggregate operator is applied
separately to each subset
Dept Salary
Administration 45 Dept TotSal
Administration 40
Administration 125
Administration 40
Distribution 45 Distribution 45
Planning 80 Planning 153
Planning 73 Production 82
Production 36
Production 46
16
Group Predicates
ÆWhen conditions are defined 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
CSC343 Introduction to Databases — University of Toronto SQL — 33
where or having?
ÆOnly predicates containing aggregate operators
should appear in the argument of the having
clause
Æ"Find the departments where the average salary
of employees working in office number 20 is
higher than 25":
select Dept
from Employee
where Office = ‘20’
group by Dept
having avg(Salary) > 25
17
Syntax of an SQL Query
…so far!
select TargetList
from TableList
[ where Condition ]
[ group by GroupingAttributeList ]
[ having AggregateCondition ]
[ order by OrderingAttributeList ]
Set Queries
ÆA single select statement cannot represent any set
operation.
ÆSyntax:
SelectSQL { <union | intersect | except >
[all] SelectSQL }
Æ"Find all first names and surnames of employees":
select FirstName as Name from Employee
union
select Surname as Name from Employee
ÆDuplicates are removed (unless the all option is used)
18
Intersection
Æ"Find surnames of employees that are also first
names":
select FirstName as Name
from Employee
intersect
select Surname as Name
from Employee
(equivalent to:
select E1.FirstName as Name
from Employee E1, Employee E2
where E1.FirstName = E2.Surname )
CSC343 Introduction to Databases — University of Toronto SQL — 37
Difference
Æ"Find the surnames of employees that are not
first names":
select Surname as Name
from Employee
except
select FirstName as Name
from Employee
ÆCan also be represented with a nested query
(see later.)
19
Nested Queries
ÆA where clause may include predicates that:
9Compare an attribute (or attribute expression) with
the result of an SQL query;
syntax: ScalarValue Op <any | all> SelectSQL
any — the predicate is true if at least one row
returned by SelectSQL satisfies the comparison
all — predicate is true if all rows satisfy
comparison;
9Use the existential quantifier on an SQL query;
syntax: exists SelectSQL
the predicate is true if SelectSQL is non-empty.
ÆThe query appearing in the where clause is called a
nested query.
CSC343 Introduction to Databases — University of Toronto SQL — 39
20
…Another…
Æ"Find employees of the Planning department, having
the same first name as a member of the Production
department":
9(with a nested query)
select FirstName,Surname from Employee
where Dept = ‘Plan’ and FirstName = any
(select FirstName from Employee
where Dept = ‘Prod’)
9(without nested query)
select E1.FirstName,E1.Surname
from Employee E1, Employee E2
where E1.FirstName=E2.FirstName and
E2.Dept=‘Prod’ and E1.Dept=‘Plan’
CSC343 Introduction to Databases — University of Toronto SQL — 41
21
Operators in and not in
ÆOperator in is a shorthand for = any
select FirstName, Surname
from Employee
where Dept in (select DeptName
from Department
where City = ‘London’)
ÆOperator not in is a shorthand for <> all
select DeptName
from Department
where DeptName not in
(select Dept from Employee
where Surname = ‘Brown’)
CSC343 Introduction to Databases — University of Toronto SQL — 43
22
A Complex Nested Query
ÆA nested query may use variables of the outer query
(‘transfer of bindings’).
ÆSemantics: the nested query is evaluated for each
row of the outer query.
Æ"Find all persons who have the same first name and
surname with someone else ("synonyms"), but
different tax codes":
select * from Person P
where exists (select * from Person P1
where P1.FirstName = P.FirstName
and P1.Surname = P.Surname
and P1.TaxCode <> P.TaxCode)
CSC343 Introduction to Databases — University of Toronto SQL — 45
…Another…
Æ"Find all persons who have no synonyms":
select * from Person P
where not exists
(select * from Person P1
where P1.FirstName =
P.FirstName
and P1.Surname = P.Surname
and P1.TaxCode <> P.TaxCode)
23
Tuple Constructors
ÆThe comparison within a nested query may involve
several attributes bundled into a tuple.
ÆA tuple constructor is represented in terms of a
pair of angle brackets.
ÆThe previous query can also be expressed as:
select * from Person P
where <FirstName,Surname> not in
(select FirstName,Surname
from Person P1
where P1.TaxCode <> P.TaxCode)
24
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)
ÆWhat's wrong?
25
Insertions
ÆSyntax:
insert into TableName [ (AttributeList) ]
< values (ListOfValues) | SelectSQL >
ÆUsing values:
insert into Department(DeptName,City)
values(‘Production’,’Toulouse’)
ÆUsing a subquery:
insert into LondonProducts
(select Code, Description
from Product
where ProdArea = ‘London’)
CSC343 Introduction to Databases — University of Toronto SQL — 51
Notes on Insertions
ÆThe ordering of attributes (if present) and of
values is meaningful -- first value for the first
attribute, etc.
ÆIf AttributeList is omitted, all the relation
attributes are considered, in the order they
appear in the table definition.
ÆIf AttributeList does not contain all the relation
attributes, left-out attributes are assigned default
values (if defined) or the null value.
26
Deletions
ÆSyntax:
delete from TableName [where Condition ]
Æ"Remove the Production department":
delete from Department
where DeptName = ‘Production’
Æ"Remove departments with no employees":
delete from Department
where DeptName not in
(select Dept from Employee)
Notes on Deletions
ÆThe delete statement removes from a table all
tuples that satisfy a condition.
ÆThe removal may produce deletions from other
tables — if a referential integrity constraint with
cascade policy has been defined.
ÆIf the where clause is omitted, delete removes
all tuples. For example, to remove all tuples from
Department (keeping the table schema):
delete from Department
ÆTo remove table Department completely (content
and schema):
drop table Department cascade
CSC343 Introduction to Databases — University of Toronto SQL — 54
27
Updates
ÆSyntax:
update TableName
set Attribute = < Expression | SelectSQL | null |
default >
{, Attribute = < Expression | SelectSQL | null |
default >}
[ where Condition ]
ÆExamples:
update Employee set Salary = Salary + 5
where RegNo = ‘M2047’
update Employee set Salary = Salary * 1.1
where Dept = ‘Administration’
Notes on Updates
ÆAs with any side effect statement, the order of
updates is important:
update Employee
set Salary = Salary * 1.1
where Salary <= 30
update Employee
set Salary = Salary * 1.15
where Salary > 30
ÆIn this example, some employees may get a
double raise! How can we fix this?
CSC343 Introduction to Databases — University of Toronto SQL — 56
28
Generic Integrity Constraints
ÆThe check clause can be used to express arbitrary
constraints during schema definition.
ÆSyntax:
check (Condition)
ÆCondition is what can appear in a where clause —
including nested queries.
ÆFor example, the definition of an attribute Superior
in the schema of table Employee:
Superior character(6)
check (RegNo like “1%” or
Dept = (select Dept from Employee E
where E.RegNo = Superior)
CSC343 Introduction to Databases — University of Toronto SQL — 57
Assertions
ÆAssertions permit the definition of constraints
independently of table definitions.
ÆAssertions are useful in many situations -- e.g., to
express generic inter-relational constraints.
ÆAn assertion associates a name to a check clause;
syntax:
create assertion AssertName check (Condition)
Æ"There must always be at least one tuple in table
Employee":
create assertion AlwaysOneEmployee
check (1 <= (select count(*)
from Employee))
CSC343 Introduction to Databases — University of Toronto SQL — 58
29
Views
ÆViews are "virtual tables" whose rows are computed
from other tables (base relations).
ÆSyntax:
create view ViewName [(AttributeList)] as SelectSQL
[with [local|cascaded] check option ]
ÆExamples:
create view AdminEmployee
(RegNo,FirstName,Surname,Salary) as
select RegNo,FirstName,Surname,Salary
from Employee
where Dept = ‘Admin’ and Salary > 10
create view JuniorAdminEmployee as
select * from AdminEmployee
where Salary < 50 with check option
CSC343 Introduction to Databases — University of Toronto SQL — 59
Notes on Views
ÆSQL views cannot be mutually dependent (no
recursion).
Æcheck option executes when a view is updated.
ÆViews can be used to formulate complex queries --
views decompose a problem and produce more
readable solutions.
ÆViews are sometimes necessary to express certain
queries:
9Queries that combine and nest several aggregate
operators;
9Queries that make fancy use of the union
operator.
CSC343 Introduction to Databases — University of Toronto SQL — 60
30
Views and Queries
31
Views and Queries
Æ"Find the average number of offices per department":
Incorrect solution (SQL does not allow a cascade of
aggregate operators):
select avg(count(distinct Office))
from Employee group by Dept
Correct solution (using a view):
create view
DeptOff(Dept,NoOfOffices) as
select Dept,count(distinct Office)
from Employee group by Dept
select avg(NoOfOffices)
from DeptOffice
CSC343 Introduction to Databases — University of Toronto SQL — 63
Access Control
ÆEvery element of a schema can be protected (tables,
attributes, views, domains, etc.)
ÆThe owner of a resource (the creator) assigns
privileges to the other users.
ÆA predefined user _system represents the database
administrator and has access to all resources.
ÆA privilege is characterized by:
9a resource;
9the user who grants the privilege;
9the user who receives the privilege;
9the action that is allowed on the resource;
9whether or not the privilege can be passed on to
other users.
CSC343 Introduction to Databases — University of Toronto SQL — 64
32
Types of Privileges
ÆSQL offers six types of privilege:
9insert: to insert a new object into the
resource;
9update: to modify the resource content;
9delete: to remove an object from the
resource;
9select: to access the resource content;
9references: to build a referential integrity
constraint with the resource;
9usage: to use the resource in a schema
definition (e.g., a domain)
33
Database Triggers
ÆTriggers (also known as ECA rules) are element of the
database schema.
ÆGeneral form:
on <event> when <condition> then <action>
9Event- request to execute database operation
9Condition - predicate evaluated on databaase state
9Action – execution of procedure that might involve
database updates
ÆExample:
on "updating maximum enrollment limit" if
"# registered > new max enrollment limit "
then "deregister students using LIFO policy"
CSC343 Introduction to Databases — University of Toronto SQL — 67
Trigger Details
ÆActivation — occurrence of the event that
activates the trigger.
ÆConsideration — the point, after activation,
when condition is evaluated; this can be
immediate or deferred.
9Deferred means that condition is evaluated
when the database operation (transaction)
currently executing requests to commit.
ÆCondition might refer to both the state before
and the state after event occurs.
CSC343 Introduction to Databases — University of Toronto SQL — 68
34
Trigger Execution
ÆThis is the point when the action part of the trigger
is carried out.
ÆWith deferred consideration, execution is also
deferred.
ÆWith immediate consideration, execution can occur
immediately after consideration or it can be
deferred
9If execution is immediate, execution can occur
before, after, or instead of triggering event.
9Before triggers adapt naturally to maintaining
integrity constraints: violation results in
rejection of event.
CSC343 Introduction to Databases — University of Toronto SQL — 69
Event Granularity
Event granularity can be:
ÆRow-level: the event involves change of a
single row,
9This means that a single update statement
might result in multiple events;
ÆStatement-level: here events result from the
execution of a whole statement; for example, a
single update statement that changes multiple
rows constitutes a single event.
35
Multiple Trigger Executions
ÆShould we allow multiple triggers to be
activated by a single event?
ÆIf so, how do we handle trigger execution?
9Evaluate one condition at a time and if true
immediately execute action; or
9Evaluate all conditions, then execute all
associated actions.
ÆThe execution of an action can affect the truth
of a subsequently evaluated condition so the
choice is significant.
Triggers in SQL-3
ÆEvents: insert, delete, or update
statements or changes to individual rows
caused by these statements.
ÆCondition: Anything allowed in a where clause.
ÆAction: An individual SQL statement or a
program written in the language of Procedural
Stored Modules (PSM) -- which can contain
embedded SQL statements.
36
Triggers in SQL-3
ÆConsideration = immediate – condition can
refer to both the state of the affected row or
table before and after the event occurs.
ÆExecution = immediate – can be before or
after the execution of the triggering event
ÆNote that the action of a before-trigger cannot
modify the database.
ÆGranularity: Both row-level and statement-
level.
37
After-Trigger with Row Granularity
CREATE TRIGGER LimitSalaryRaise
No salary
AFTER UPDATE OF Salary ON Employee raises greater
REFERENCING OLD AS O than 5%
NEW AS N
FOR EACH ROW
WHEN (N.Salary - O.Salary > 0.05 * O.Salary)
THEN UPDATE Employee -- action
SET Salary = 1.05 * O.Salary
WHERE Id = O.Id
38