0% found this document useful (0 votes)
69 views38 pages

04-05 - SQL-2up csc343

This document provides an overview of SQL concepts to be covered in weeks 4 and 5, including select statements, joins, aggregate functions, nested queries, data manipulation statements, and additional SQL features like views, triggers, and assertions. It presents examples of basic SQL queries on an example employee database to retrieve, filter, and join data. The document also discusses the logical interpretation of SQL queries as relational algebra operations.

Uploaded by

Partha Kuri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views38 pages

04-05 - SQL-2up csc343

This document provides an overview of SQL concepts to be covered in weeks 4 and 5, including select statements, joins, aggregate functions, nested queries, data manipulation statements, and additional SQL features like views, triggers, and assertions. It presents examples of basic SQL queries on an example employee database to retrieve, filter, and join data. The document also discusses the logical interpretation of SQL queries as relational algebra operations.

Uploaded by

Partha Kuri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Week 4 & 5: SQL

The SQL Query Language


Select Statements
Joins, Aggregate and Nested Queries
Insertions, Deletions and Updates
Assertions, Views, Triggers and Access
Control

CSC343 Introduction to Databases — University of Toronto SQL — 1

SQL as a Query Language

ÆSQL expresses queries in declarative way —


queries specify the properties of the result, not
the way to obtain it.
ÆQueries are translated by the query optimizer
into the procedural language internal to the
DBMS.
ÆThe programmer focuses on readability, not on
efficiency.

CSC343 Introduction to Databases — University of Toronto SQL — 2

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

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

DEPARTMENT DeptName Address City


Administration Bond Street London
Production Rue Victor Hugo Toulouse
Distribution Pond Road Brighton
Planning Bond Street London
Research Sunset Street San José

CSC343 Introduction to Databases — University of Toronto SQL — 4

2
Simple SQL Query
Æ"Find the salaries of employees named Brown":
select Salary as Remuneration
from Employee
where Surname = ‘Brown’

ÆResult:

Remuneration
45
80

CSC343 Introduction to Databases — University of Toronto SQL — 5

* in the Target List


Æ"Find all the information relating to employees
named Brown":
select *
from Employee
where Surname = ‘Brown’

ÆResult:

FirstName Surname Dept Office Salary City


Mary Brown Administration 10 45 London
Charles Brown Planning 14 80 London

CSC343 Introduction to Databases — University of Toronto SQL — 6

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

CSC343 Introduction to Databases — University of Toronto SQL — 7

Simple Join Query


Æ"Find the names of employees and their cities of work":
select Employee.FirstName,
Employee.Surname, Department.City
from Employee, Department
where Employee.Dept = Department.DeptName

FirstName Surname City


ÆResult: Mary Brown London
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 — 8

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

CSC343 Introduction to Databases — University of Toronto SQL — 10

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

CSC343 Introduction to Databases — University of Toronto SQL — 11

Complex Logical Expressions

Æ"Find the first names of employees named Brown


who work in the Administration department or the
Production department":
select FirstName
from Employee
where Surname = ‘Brown’ and
(Dept = ‘Administration’ or
Dept = ‘Production’)
ÆResult: FirstName
Mary

CSC343 Introduction to Databases — University of Toronto SQL — 12

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:

FirstName Surname Dept Office Salary City


Mary Brown Administration 10 45 London
Gus Green Administration 20 40 Oxford
Charles Brown Planning 14 80 London

CSC343 Introduction to Databases — University of Toronto SQL — 13

Management of Null Values


ÆNull values may mean that:
9a value is not applicable
9a value is applicable but unknown
9it is unknown if a value is applicable or not
ÆSQL-89 uses a two-valued logic
9a comparison with null returns FALSE
ÆSQL-2 uses a three-valued logic
9a comparison with null returns UNKNOWN
ÆTo test for null values:
Attribute is [ not ] null

CSC343 Introduction to Databases — University of Toronto SQL — 14

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))

CSC343 Introduction to Databases — University of Toronto SQL — 15

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

Inner Join in SQL-2


Æ"Find the names of the employees and the cities in
which they work":
select FirstName, Surname, D.City
from Employee inner join Department as D
on 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 — 18

9
Another Example:
Drivers and Cars

DRIVER FirstName Surname DriverID


Mary Brown VR 2030020Y
Charles White PZ 1012436B
Marco Neri AP 4544442R

AUTOMOBILE CarRegNo Make Model DriverID


ABC 123 BMW 323 VR 2030020Y
DEF 456 BMW Z3 VR 2030020Y
GHI 789 Lancia Delta PZ 1012436B
BBB 421 BMW 316 MI 2020030U

CSC343 Introduction to Databases — University of Toronto SQL — 19

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

ÆAggregate queries cannot be represented in


relational algebra.
ÆThe result of an aggregate query depends on
functions that take as an argument a set of
tuples.
ÆSQL-2 offers five aggregate operators:
9count
9sum
9max
9min
9avg
CSC343 Introduction to Databases — University of Toronto SQL — 24

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

CSC343 Introduction to Databases — University of Toronto SQL — 26

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

CSC343 Introduction to Databases — University of Toronto SQL — 27

Aggregate Queries and Target List


ÆIncorrect query:
select FirstName,Surname,max(Salary)
from Employee, Department
where Dept = DeptName and
Department.City = ‘London’
(Whose name? The target list must be homogeneous!)
ÆFind the maximum and minimum salaries among all
employees:
select max(Salary) as MaxSal,
min(Salary) as MinSal
from Employee
MaxSal MinSal
ÆResult: 80 36
CSC343 Introduction to Databases — University of Toronto SQL — 28

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

CSC343 Introduction to Databases — University of Toronto SQL — 29

Semantics of group by Queries - I

ÆFirst, the query is executed without group by


and without aggregate operators:
select Dept, Salary
from Employee
Dept Salary
Administration 45
Production 36
Administration 40
Distribution 45
Planning 80
Planning 73
Administration 40
Production 46

CSC343 Introduction to Databases — University of Toronto SQL — 30

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

CSC343 Introduction to Databases — University of Toronto SQL — 31

group by Queries and Target List


ÆIncorrect query:
select Office from Employee
group by Dept
ÆIncorrect query:
select DeptName, count(*), D.City
from Employee E join Department D
on (E.Dept = D.DeptName)
group by DeptName
ÆCorrect query:
select DeptName,count(*),D.City
from Employee E join Department D
on (E.Dept = D.DeptName)
group by DeptName, D.City
CSC343 Introduction to Databases — University of Toronto SQL — 32

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

CSC343 Introduction to Databases — University of Toronto SQL — 34

17
Syntax of an SQL Query
…so far!

ÆConsidering all clauses discussed so far, the


syntax of an SQL query is:

select TargetList
from TableList
[ where Condition ]
[ group by GroupingAttributeList ]
[ having AggregateCondition ]
[ order by OrderingAttributeList ]

CSC343 Introduction to Databases — University of Toronto SQL — 35

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)

CSC343 Introduction to Databases — University of Toronto SQL — 36

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.)

CSC343 Introduction to Databases — University of Toronto SQL — 38

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

Simple Nested Query


Æ"Find the employees who work in departments in
London":
select FirstName, Surname
from Employee
where Dept = any (select DeptName
from Department
where City = ‘London’)
(Equivalent to:
select FirstName, Surname
from Employee, Department D
where Dept = DeptName and
D.City = ‘London’ )
CSC343 Introduction to Databases — University of Toronto SQL — 40

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

Negation with Nested Queries


Æ"Find departments where there is no one named
Brown":
select DeptName
from Department
where DeptName <>
all (select Dept from Employee
where Surname = ‘Brown’)
Æ(Alternatively:)
select DeptName from Department
except
select Dept from Employee
where Surname = ‘Brown’
CSC343 Introduction to Databases — University of Toronto SQL — 42

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

max and min within a Nested Query


ÆQueries using the aggregate operators max and min
can be expressed with nested queries
Æ"Find the department of the employee earning the
highest salary":
9with max:
select Dept from Employee
where Salary in (select max(Salary)
from Employee)
9with a nested query:
select Dept from Employee
where Salary >= all (select Salary
from Employee
CSC343 Introduction to Databases — University of Toronto SQL — 44

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)

CSC343 Introduction to Databases — University of Toronto SQL — 46

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)

CSC343 Introduction to Databases — University of Toronto SQL — 47

Comments on Nested Queries


ÆThe use of nested queries may produce less
declarative queries, but often results in
improved readability.
ÆComplex queries can become very difficult to
understand.
ÆThe use of variables must respect scoping
conventions: a variable can be used only within
the query where it is defined, or within a query
that is recursively nested in the query where it
is defined.
CSC343 Introduction to Databases — University of Toronto SQL — 48

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?

CSC343 Introduction to Databases — University of Toronto SQL — 49

Data Modification in SQL


ÆModification statements include:
9Insertions (insert);
9Deletions (delete);
9Updates of attribute values (update).
ÆAll modification statements operate on a set of
tuples (no duplicates.)
ÆIn the condition part of an update statement it
is possible to access other relations.

CSC343 Introduction to Databases — University of Toronto SQL — 50

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.

CSC343 Introduction to Databases — University of Toronto SQL — 52

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)

CSC343 Introduction to Databases — University of Toronto SQL — 53

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’

CSC343 Introduction to Databases — University of Toronto SQL — 55

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

Æ"Find the department with highest salary


expenditures" (without using a view):
select Dept from Employee
group by Dept
having sum(Salary) >= all
(select sum(Salary) from
Employee
group by Dept)
ÆThis solution may not work with all SQL
systems.
CSC343 Introduction to Databases — University of Toronto SQL — 61

Views and Queries

Æ"Find the department with highest salary


expenditures" (using a view):
create view SalBudget
(Dept,SalTotal) as
select Dept,sum(Salary)
from Employee group by Dept
select Dept from SalBudget
where SalTotal =
(select max(SalTotal) from
SalBudget)
CSC343 Introduction to Databases — University of Toronto SQL — 62

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)

CSC343 Introduction to Databases — University of Toronto SQL — 65

grant and revoke


ÆTo grant a privilege to a user:
grant < Privileges | all privileges > on
Resource
to Users [ with grant option ]
Ægrant option specifies whether the privilege can
be propagated to other users.
ÆFor example,
grant select on Department to
Stefano
ÆTo take away privileges:
revoke Privileges on Resource from Users
[ restrict | cascade ]
CSC343 Introduction to Databases — University of Toronto SQL — 66

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.

CSC343 Introduction to Databases — University of Toronto SQL — 70

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.

CSC343 Introduction to Databases — University of Toronto SQL — 71

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.

CSC343 Introduction to Databases — University of Toronto SQL — 72

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.

CSC343 Introduction to Databases — University of Toronto SQL — 73

Before-Trigger with Row Granularity


CREATE TRIGGER Max_EnrollCheck Check that
enrollment
BEFORE INSERT ON Transcript ≤ limit
REFERENCING NEW AS N --row to be added
FOR EACH ROW
WHEN
((SELECT COUNT (T.StudId) FROM Transcript T
WHERE T.CrsCode = N.CrsCode
AND T.Semester = N.Semester)
>=
(SELECT C.MaxEnroll FROM Course C
WHERE C.CrsCode = N.CrsCode ))
THEN ABORT TRANSACTION Action
CSC343 Introduction to Databases — University of Toronto SQL — 74

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

[Note: The action itself is a triggering event; however,


in this case a chain reaction is not possible.]
CSC343 Introduction to Databases — University of Toronto SQL — 75

After-Trigger with Statement


Granularity
CREATE TRIGGER RecordNewAverage
AFTER UPDATE OF Salary ON Employee
FOR EACH STATEMENT
THEN INSERT INTO Log Keep track of
VALUES (CURRENT_DATE, salary averages
SELECT AVG (Salary) in the log
FROM Employee)
Employee

CSC343 Introduction to Databases — University of Toronto SQL — 76

38

You might also like