06 Ch6 TheDatabaseLanguageSQL
06 Ch6 TheDatabaseLanguageSQL
TO
DATABASE
L E A R N B Y E X A M P L E S
THE DATABASE
LANGUAGE SQL
SQL Language Overview
tblLocation
locNum
tblDependent
tblWorksOn depName
locName
I2DB: Algebraic Query Language
empSSN empSSN
proNum depSex
workHours depBirthdate
depRelationship
tblDepLocation
depNum
locNum
tblProject tblEmployee
proNum empSSN
proName empName
tblDepartment
locNum depNum empAddress
depNum depName empSalary
mgrSSN empSex
mgrAssDate empBirthdate
depNum
supervisorSSN
SQL Queries and Relational
Algebra
Syntax
I2DB: Algebraic Query Language
SELECT L
FROM R L(C(R))
WHERE C
T-SQL : Basic Syntax for a simple
SELECT queries
SELECT [ ALL | DISTINCT ]
[ TOP n [ PERCENT ] ]
* | {column_name | expression [alias],…}
I2DB: Algebraic Query Language
[FROM table]
[WHERE conditions]
SELECT identifies what columns
ALL: Specifies that duplicate rows can appear in the result set. ALL is the default
DISTINCT: Specifies that only unique rows can appear in the result set. Null values are considered equal for the
between 0 and 4294967295. If PERCENT is also specified, only the first n percent of the rows are output from
the result set. When specified with PERCENT, n must be an integer between 0 and 100
FROM identifies which table
The WHERE clause follows the FROM clause. Condition: is composed of column names,
expressions, constants, and a comparison operator
Common Query in SQL
Example 3:
Listing full name and salary of all employees whose
Arithmetic operators
▪ +, -, *, /
Comparison operators
▪ =, <>, <, >, , ≥
Logical operators
▪ and, or, not
Example 4
I2DB: Algebraic Query Language
male employees
Comparison of Strings
Two strings are equal (=) if they are the same sequence of
characters
I2DB: Algebraic Query Language
ak+1<bk+1
Example
fodder < foo
SELECT SELECT
FROM FROM
WHERE s LIKE p; WHERE s NOT LIKE p;
Example 5.1:
I2DB: Algebraic Query Language
Example 5.2
Find all employees whose name is ended at ‘Anh’
Pattern Matching in SQL
Matching any s string that begins and ends with the character %
Dates and Times
DATE ‘1948-05-14’
Comparison operations
Null Values
Value withheld: we are not entitled to know the value that belongs here
x y x AND y x OR y NOT x
TRUE TRUE TRUE TRUE FALSE
TRUE UNKNOWN UNKNOWN TRUE FALSE
TRUE FALSE FALSE TRUE FALSE
UNKNOWN TRUE UNKNOWN TRUE UNKNOWN
UNKNOWN UNKNOWN UNKNOWN UNKNOWN UNKNOWN
UNKNOWN FALSE FALSE UNKNOWN UNKNOWN
FALSE TRUE FALSE TRUE TRUE
FALSE UNKNOWN FALSE UNKNOWN TRUE
FALSE FALSE FALSE FALSE TRUE
The Truth-Value Unknown
Order by clause follows Where and any other clauses. The ordering is
performed on the result of the From, Where, and other clauses, just
before Select clause
Using keyword ASC for ascending order and DESC for descending order
Ordering the Output
Example 6:
I2DB: Algebraic Query Language
Example 7:
I2DB: Algebraic Query Language
need
We use tuple variables to refer to each
occurrence of R
Disambiguating Attributes
Example 8:
I2DB: Algebraic Query Language
same relation?
Example 9:
Find all those project numbers which have more than
two members
Union, Intersection, Difference of
Queries
Example 10.1
I2DB: Algebraic Query Language
Example 10.2
I2DB: Algebraic Query Language
Example 10.3
I2DB: Algebraic Query Language
clause
Sub-queries can appear in FROM clauses, followed by a tuple
variable
Sub-queries that Produce Scalar
Values
Example 11:
I2DB: Algebraic Query Language
department
Sub-queries that Produce Scalar
Values
Example 11:
I2DB: Algebraic Query Language
department
Sub-queries that Produce Scalar
Values
Example 11:
I2DB: Algebraic Query Language
department
Conditions Involving Relations
unary R
(s > ANY R = True) s is greater than at least one
value in unary R
Conditions Involving Tuples
values between ()
If a tuple t has the same number of components
as a relation R, then we may compare t and R
with IN, ANY, ALL
Sub-queries that Produce Scalar
Values
Example 12:
I2DB: Algebraic Query Language
number 1
Correlated Sub-queries
Example 13:
I2DB: Algebraic Query Language
projectA
Correlated Sub-queries
Another example:
I2DB: Algebraic Query Language
Find the titles that have been used for two or movies
SELECT title
(SELECT year
FROM Movies
Example 15.1
I2DB: Algebraic Query Language
Example 15.2
Find departments and employees who work in those
departments, respectively
SQL Join Expression
More Example
I2DB: Algebraic Query Language
Natural Joins
Example 17.1:
I2DB: Algebraic Query Language
in it
Outer joins
Example 17.2:
I2DB: Algebraic Query Language
duplicates automatically
Use ALL keyword after Union, Intersect, and
Except to prevent elimination of duplicates
Syntax:
R UNION ALL S;
R INTERSECT ALL S;
R EXCEPT ALL S;
Grouping and Aggregation in SQL
Example 18.1
I2DB: Algebraic Query Language
Example 18.2
Find number of employees
Grouping
Syntax
Example 19.1:
I2DB: Algebraic Query Language
Example 19.2
List number of employees for each department number
Grouping
attributes
Grouping Attributes, that appear in GROUP BY clause
clause
Grouping
Example 20
I2DB: Algebraic Query Language
groups
The count of empty bag is 0, other aggregation of empty
bag is NULL
Grouping, Aggregation, and Nulls
A B
NULL NULL
Syntax:
I2DB: Algebraic Query Language
Example 21:
I2DB: Algebraic Query Language
Example:
SELECT proNum, COUNT(empSSN) AS Number_Of_Employees,
I2DB: Algebraic Query Language
FROM tblWorksOn
GROUP BY proNum
HAVING AVG(workHours)>20
tuples
Insertion
If the list of attributes does not include all attributes of the relation R,
then the tuple created has default values for all missing attributes
The basic form allows to insert only one tuple at once
The extended form allows to insert a set of tuples as result of a sub
query:
INSERT INTO R(A1, ..., An)
Example:
remove a department named ‘Phòng Kế Toán’
remove a department which depNum is 7
be performed on database
These may operate on the same data
We’ll get unexpected results
Serializability
flight
User 1 finds a
time seat empty
User2 finds a seat
empty
User1 sets seat
22A occupied
User2 sets seat
22A occupied
Serializability
be performed together
A certain transaction must be serializable with
respect to other transactions, that is, the
transactions run serially – one at a time, no
overlap
Atomicity
$500
I2DB: Algebraic Query Language
ACC: 3209
$500
ACC: 3208
Transactions
TRANSACTION
Two ways to end a transaction
The SQL statement COMMIT causes the transaction to
end successfully
The SQL statement ROLLBACK causes the transaction
Consistency
Isolation
Durability
ACID properties of Transaction
violated
Consistency: a transaction should be consistency preserving,
meaning that if it is completely executed from beginning to end
without interference from other transactions, it should take the
database from one consistent state to another.
ACID properties of Transaction
transaction
SET TRANSACTION READ ONLY;
yet committed
Dirty read: read of dirty data written by another
transaction
Problem: the transaction that wrote it may eventually
abort, and the dirty data will be removed
Sometimes the dirty read matters, sometimes it
doesn’t
Dirty Reads
I2DB: Algebraic Query Language
a given transaction
SET TRANSACTION READ WRITE