SQL Notes Detail 1 PDF
SQL Notes Detail 1 PDF
SQL Notes Detail 1 PDF
F-1
SQL (cont.)
SQL was developed at IBM (San Jose Lab) during the 1970s, and
standardised in 1986.
SQL (in some form) looks likely to survive in the next generation of
database systems.
F-2
SQL (cont.)
recursive queries
SQL:2003 ...
PostgreSQL ...
F-5
SQL (cont.)
Relational algebra:
t u v x y
R 1 a 2.5 S h 1
1 b 1.7 j 2
2 a 3.0 k 3
2 b 2.4
t u v
select[t=1](R) 1 a 2.5
1 b 1.7
t
project[t](R) 1
2
t u v x y
join[t=y](R,S) 1 a 2.5 h 1
1 b 1.7 h 1
2 a 3.0 j 2
2 b 2.4 j 2
F-7
Example Databases
F-8
Example Database #1
F-9
Example Database #1 (cont.)
Foreign Key
Primary Key Owner account customer
Branch branchName address assets Foreign Key
F-10
Example Database #1 (cont.)
F-13
Example Database #2 (cont.)
F-14
Example Database #2 (cont.)
F-15
Example Database #2 (cont.)
F-16
Example Database #2 (cont.)
F-17
Example Database #2 (cont.)
F-18
Example Database #2 (cont.)
F-19
SQL Syntax
F-20
SQL Syntax (cont.)
F-21
SQL Keywords
There are 225 reserved words in SQL92 ... not a small language.
F-22
SQL Keywords (cont.)
Note that some SQL92 reserved words are not reserved words in PostgreSQL.
F-23
SQL Identifiers
Example identifiers:
Oracle SQL also allows unquoted hash (#) and dollar ($) in identifiers.
F-24
SQL Identifiers (cont.)
Since SQL does not distinguish case, the following are all treated as
being the same identifier:
Most RDBMSs will let you give the same name to different kinds of
objects (e.g. a table called Beer and an attribute called Beer).
F-27
SQL Data Types
All attributes in SQL relations are typed (i.e. have domain specified)
F-28
SQL Data Types (cont.)
F-29
SQL Data Types (cont.)
F-31
SQL Data Types (cont.)
F-32
Tuple and Set Literals
Examples:
INSERT INTO Student(stude#, name, course)
VALUES (2177364, Jack Smith, BSc)
-- tuple literal
F-33
Tuple and Set Literals (cont.)
Examples:
Boolean operators AND, OR, NOT are available within WHERE expressions to
combine results of comparisons.
Most data types also have type-specific operations available (e.g. arith-
metic for numbers).
String comparison:
F-36
SQL Operators (cont.)
F-37
SQL Operators (cont.)
Attr ~ RegExp
F-38
SQL Operators (cont.)
F-39
SQL Operators (cont.)
String manipulation:
F-40
SQL Operators (cont.)
Arithmetic operations:
+ - * / abs ceil floor power sqrt sin
F-41
SQL Operators (cont.)
sum(1,2,3,4,5,6) = 21
sum(1,2,NULL,4,NULL,6) = 13
avg(1,2,3,4,5) = 3
avg(NULL,2,NULL,4) = 3
F-42
SQL Operators (cont.)
F-43
SQL: Schemas
F-44
Relational Data Definition
describe tables
F-45
Relational Data Definition (cont.)
database schemas
Foreign Key
Primary Key Owner account customer
Branch branchName address assets Foreign Key
names of tables
F-47
Defining a Database Schema
where constraints can include details about primary keys, foreign keys, default values,
and constraints on attribute values.
This not only defines the table schema but also creates an empty in-
stance of the table.
Foreign Key
This shows explicitly the connection between foreign key attributes and their corre-
sponding key attributes.
The SQL DDL provides notation for expressing this in the table definition.
F-49
Defining a Database Schema (cont.)
F-50
Defining a Database Schema (cont.)
Note: the not null captures total participation, i.e. every customer has a home
branch.
F-51
Defining a Database Schema (cont.)
Note: the not null captures total participation, i.e. every accountis held at some
branch.
F-52
Defining a Database Schema (cont.)
Note: it is not possible in SQL to capture the semantics that Accounts are required
to be owned by some Customer.
F-53
Declaring Keys
Primary keys:
F-54
Declaring Keys (cont.)
PostgreSQLs version:
F-55
Declaring Keys (cont.)
Foreign keys:
F-56
Declaring Keys (cont.)
F-57
Declaring Keys (cont.)
Example:
If we want to delete a tuple from Branch, and there are tuples in Account
that refer to it, we could ...
F-58
Declaring Keys (cont.)
-- to cascade deletes
customer integer
REFERENCES Customer(customerNo)
ON DELETE CASCADE
F-59
Declaring Keys (cont.)
F-60
Branch
branchName address assets Account After deletion with SET NULL
F-61
Other Attribute Properties (cont.)
Example:
CREATE TABLE Account (
accountNo char(5) PRIMARY KEY,
branchName varchar(30)
REFERENCES Branch(name)
DEFAULT Central,
balance float DEFAULT 0.0
);
F-62
Attribute Value Constraints
The Condition can be arbitrarily complex, and may even involve other
attributes, relations and SELECT queries.
(but many RDBMSs (e.g. Oracle and PostgreSQL) dont allow SELECT in CHECK)
F-63
Attribute Value Constraints (cont.)
Example:
F-64
Named Constraints
Example:
F-65
SQL: Building Databases
F-66
Creating Databases
$ createdb DBname
F-67
Creating Databases (cont.)
$ dropdb DBname
F-68
Creating Databases (cont.)
$ createdb mydb
$ psql mydb
...
mydb=# \i schema.sql
...
or
$ dropdb mydb
$ createdb mydb
$ psql -f schema.sql mydb
$ psql mydb
...
mydb=# drop Table1;
mydb=# drop Table2;
etc. etc. in correct order
mydb=# \i schema.sql
F-70
...
F-71
Creating Databases (cont.)
F-72
Data Modification in SQL
(See description of relational model for details of which checking applied when)
F-73
Data Modification in SQL (cont.)
F-74
Insertion
F-75
Insertion (cont.)
F-76
Insertion (cont.)
And then try to insert a new drinker whose phone number we dont
know:
F-80
Insertion from Queries (cont.)
F-81
Bulk Insertion of Data
F-82
Bulk Insertion of Data (cont.)
DELETE FROM R;
F-84
Deletion (cont.)
F-85
Semantics of Deletion
Example: Delete all beers for which there is another beer by the same
manufacturer.
F-88
Updates
UPDATE R
SET list of assignments
WHERE Condition
Assignments may:
UPDATE Drinkers
SET phone = 9385-2222
WHERE name = Adam;
UPDATE Drinkers
SET addr = Coogee,
phone = 9665-4321
WHERE name = John;
F-90
Updates (cont.)
Can update many tuples at once (all tuples that satisfy condition)
UPDATE Sells
SET price = 3.00
WHERE price > 3.00;
UPDATE Sells
SET price = price * 1.10;
F-91
Changing Tables
add a new column (attribute) (set value to NULL unless default given)
remove an attribute
F-92
Changing Tables (cont.)
This appends a new column to the table and sets value for this attribute
to Unlisted in every tuple.
UPDATE Bars
SET phone = 9665-0000
WHERE name = Coogee Bay Hotel;
F-94
SQL: Queries
F-95
Queries
F-96
Queries in SQL
SELECT attributes
FROM relations
WHERE condition
F-97
SELECT Example
Notes:
upper- and lower-case are not distinguished, except in strings.
quotes are escaped by doubling them ( is like C \)
F-98
Semantics of SELECT
SELECT Attributes
FROM R
WHERE Condition
P roj[Attributes](Sel[Condition](R))
F-99
Semantics of SELECT (cont.)
Operational semantics:
F-100
Projection in SQL
SELECT X FROM R
name
--------
Adam
Gernot
John
Justin
F-101
Projection in SQL (cont.)
name | addr
--------+----------
Adam | Randwick
Gernot | Newtown
John | Clovelly
Justin | Mosman
F-102
Projection in SQL (cont.)
F-103
Renaming via AS
beer | brewer
---------------------+---------------
80/- | Caledonian
Bigfoot Barley Wine | Sierra Nevada
Burragorang Bock | George IV Inn
Crown Lager | Carlton
Fosters Lager | Carlton
...
F-104
Expressions as Values in Columns
F-105
Text in Result Table
drinker | wholikes
---------+----------------
Gernot | likes Coopers
Justin | likes Coopers
F-106
Selection in SQL
F-107
Selection in SQL (cont.)
Example: Find the price that The Regent charges for New
SELECT price
FROM Sells
WHERE bar = Regent Hotel AND beer = New;
price
-------
2.2
price
---------
$ 2.20
SELECT Attributes
FROM R1, R2, ...
WHERE Condition
F-109
Multi-relation SELECT Queries (cont.)
brewer
---------------
Caledonian
Sierra Nevada
Sierra Nevada
Lord Nelson
F-110
Multi-relation SELECT Queries (cont.)
F-111
Semantics of Multi-Relation SELECT
SELECT Attributes
FROM R1, R2, ... Rn
WHERE Condition
P roj[Attributes](Sel[Condition](R1 R2 ...Rn))
F-112
Semantics of Multi-Relation SELECT (cont.)
Requires one tuple variable for each relation, and nested loops over relations. This is
not how its actually computed!
F-113
Name Clashes in Conditions
If a selection condition
SELECT Bars.name
FROM Bars, Beers
WHERE Bars.name = Beers.name;
(The answer to this query is empty, but there is nothing special about this)
F-114
Name Clashes in Conditions (cont.)
SELECT Sells.beer
FROM Sells
WHERE Sells.price > 3.00;
Advice:
Note:
F-115
Explicit Tuple Variables
To handle this, we need to define new names for each instance of the
relation in the FROM clause.
Syntax:
F-116
Explicit Tuple Variables (cont.)
name | name
---------------------+------------------
Crown Lager | Fosters Lager
Crown Lager | Invalid Stout
Crown Lager | Melbourne Bitter
Crown Lager | Victoria Bitter
Fosters Lager | Invalid Stout
Fosters Lager | Melbourne Bitter
...
F-117
Explicit Tuple Variables (cont.)
F-118
Explicit Joins
The natural join and join using forms assume that the join attributes
are named the same in each relation.
F-119
Explicit Joins (cont.)
F-120
Explicit Joins (cont.)
or
F-121
Outer Join
Join only produces tuples where there are matching values in both of
the relations involved in the join.
Often, it is useful to produce results for all tuples in one relation, even
if it has no matches in the other.
Consider the query: for each region, find out who drinks there.
F-122
Outer Join (cont.)
A regular join only gives results for regions where people drink.
SELECT B.addr, F.drinker
FROM Bars as B join Frequents as F
on (bar = name)
ORDER BY addr;
addr | drinker
-----------+---------
Coogee | Adam
Coogee | John
Kingsford | Justin
Sydney | Justin
The Rocks | John
But what if we want a result that shows all regions, even if there are
no drinkers there?
F-123
Outer Join (cont.)
F-124
Outer Join (cont.)
addr | drinker
------------+---------
Coogee | Adam
Coogee | John
Kingsford | Justin
Randwick |
Sydney | Justin
The Rocks | John
F-125
Outer Join (cont.)
Can treat the result as a single constant value and use in expressions.
Syntax:
SELECT *
FROM R
WHERE R.a = (SELECT x FROM S WHERE Cond)
-- assume only one result
F-127
Subqueries (cont.)
Example: Find bars that serve New at the same price as the Coogee
Bay Hotel charges for VB.
SELECT bar
FROM Sells
WHERE beer = New AND
price =
(SELECT price
FROM Sells
WHERE bar = Coogee Bay Hotel
AND beer = Victoria Bitter);
bar
-------------
Royal Hotel
The inner query finds the price of VB at the CBH, and uses this as an argument to a
test in the outer query.
F-128
Subqueries (cont.)
Parentheses around the subquery are required (and set the scope).
F-129
Subqueries (cont.)
In general, expressing a query via joins will be much more efficient than
expressing it with sub-queries.
F-130
Subqueries (cont.)
F-131
The IN Operator
Syntax:
SELECT *
FROM R
WHERE R.a IN (SELECT x FROM S WHERE Cond)
-- assume multiple results
F-132
The IN Operator (cont.)
Example: Find the name and brewer of beers that John likes.
SELECT *
FROM Beers
WHERE name IN
(SELECT beer
FROM Likes
WHERE drinker = John);
name | manf
---------------------+---------------
80/- | Caledonian
Bigfoot Barley Wine | Sierra Nevada
Pale Ale | Sierra Nevada
Three Sheets | Lord Nelson
The subexpression answers the question What are the names of the
beers that John likes?
F-133
The IN Operator (cont.)
Note that this query can be answered equally well without using IN.
name | manf
---------------------+---------------
80/- | Caledonian
Bigfoot Barley Wine | Sierra Nevada
Pale Ale | Sierra Nevada
Three Sheets | Lord Nelson
The version with the subquery corresponds more closely to the way the
original query was expressed, and is probably more natural.
Example: Find the beers that are the unique beer by their manufac-
turer.
Note the scoping rule: to refer to outer Beers in the inner subquery, we
need to define a named tuple variable (in this example b1).
SELECT beer
FROM Sells
WHERE price >=
ALL(SELECT price FROM sells);
E.g. Im better than any of you vs. Im better than all of you.
F-136
Union, Intersection, Difference
Oracle deviates from the SQL standard and uses MINUS for EXCEPT; PostgreSQL follows
the standard.
F-137
Union, Intersection, Difference (cont.)
Example: Find the drinkers and beers such that the drinker likes the
beer and frequents a bar that sells it.
drinker | beer
---------+-----------------
Adam | New
John | Three Sheets
Justin | Victoria Bitter
F-138
Bag Semantics of SQL
This changes the semantics of the set operators UNION, INTERSECT and
MINUS.
F-139
Bag Semantics of SQL (cont.)
Bag Union
Bag Intersection
Bag Difference
F-141
Forcing Bag/Set Semantics (cont.)
manf
---------------
Caledonian
Carlton
Cascade
Coopers
George IV Inn
Lord Nelson
Sierra Nevada
Tooheys
Not all SQL implementations provide a divide operator, but the same
effect can be achieved by combination of existing operations.
Example: Find bars that each sell all of the beers Justin likes.
F-143
Selection with Aggregation
SELECT AVG(price)
FROM Sells
WHERE beer = New;
avg
------------------
2.38749998807907
Note:
the bag semantics of SQL gives the correct result here
the price for New in all hotels will be included, even if two hotels sell it at the
same price
if we used set semantics, wed get the average of all the different prices for New.
F-144
Selection with Aggregation (cont.)
count
-------
6
Without DISTINCT, the result is 15 ... the number of entries in the Sells
table.
F-145
Aggregation operators
count
-------
18
F-146
Grouping
There is one entry for each beer by each brewer in the Beers table ...
F-147
Grouping (cont.)
F-148
Grouping (cont.)
manf | count
---------------+-------
Caledonian | 1
Carlton | 5
Cascade | 1
Coopers | 2
George IV Inn | 1
Lord Nelson | 2
Sierra Nevada | 2
Tooheys | 4
F-149
Grouping (cont.)
SELECT attributes/aggregations
FROM relations
WHERE condition
GROUP BY attribute
Semantics:
F-150
Grouping (cont.)
The query
select manf,count(manf) from Beers group by manf;
F-151
Grouping (cont.)
Example: For each drinker, find the average price of New at the bars
they go to.
SELECT drinker, AVG(price) as "Avg.Price"
FROM Frequents, Sells
WHERE beer = New
AND Frequents.bar = Sells.bar
GROUP BY drinker;
drinker | Avg.Price
---------+-----------
Adam | 2.25
John | 2.25
Justin | 2.5
F-152
Restrictions on SELECT Lists
SELECT bar
FROM Sells
WHERE beer = New AND
price <= (SELECT MIN(price)
FROM Sells
WHERE beer = New);
bar
--------------
Regent Hotel
F-154
Restrictions on SELECT Lists (cont.)
F-155
Restrictions on SELECT Lists (cont.)
name | manf
---------------------+---------------
80/- | Caledonian
Crown Lager | Carlton
Fosters Lager | Carlton
Invalid Stout | Carlton
Melbourne Bitter | Carlton
Victoria Bitter | Carlton
Premium Lager | Cascade
...
In some queries, you can use the WHERE condition to eliminate groups.
F-157
Eliminating Groups (cont.)
SELECT attributes/aggregations
FROM relations
WHERE condition (on tuples)
GROUP BY attribute
HAVING condition (on group);
Semantics of HAVING:
Example: Find the average price of common beers (i.e. those that are
served in more than one hotel).
SELECT beer,
to_char(AVG(price),9.99)
as "$$$"
FROM Sells
GROUP BY beer
HAVING COUNT(bar) > 1;
beer | $$$
-----------------+-------
New | 2.39
Old | 2.53
Victoria Bitter | 2.40
F-159
Eliminating Groups (cont.)
The HAVING condition can have components that do not use aggregation.
Example: Find the average price of beers that are either commonly
served (in more than one hotel) or are manufactured by Coopers.
beer | avg
-----------------+------------------
F-160
New | 2.38749998807907
Old | 2.53333330154419
Sparkling Ale | 2.79999995231628
Victoria Bitter | 2.39999997615814
Eliminating Groups (cont.)
Example: Find bars that each sell all of the beers Justin likes.
F-161
SQL: Views
F-162
Views
Views are defined only after their base tables are defined.
F-164
Views (cont.)
name | manf
------------------+---------
Crown Lager | Carlton
Fosters Lager | Carlton
Invalid Stout | Carlton
Melbourne Bitter | Carlton
Victoria Bitter | Carlton
F-165
Views (cont.)
name | license
-----------------+---------
Australia Hotel | 123456
Lord Nelson | 123888
Marble Bar | 122123
F-166
Views (cont.)
brewer | nbeers
---------------+--------
Caledonian | 1
Carlton | 5
Cascade | 1
...
F-167
Renaming View Attributes
F-168
Using Views
F-169
Using Views (cont.)
Attributes not in the views SELECT will be set to NULL in the base relation
after an insert into the view.
F-171
Updating Views (cont.)
when we SELECT from the view, this new tuple does not satisfy the view
condition:
F-172
Updating Views (cont.)
F-175
Evaluating Views (cont.)
SELECT name
FROM InnerCityHotels
WHERE license = 123456;
SELECT name
FROM Bars
WHERE addr IN (The Rocks, Sydney)
AND license = 123456;
F-176
Evaluating Views (cont.)
Some abbreviations
n = name, l = license
L = license = 123456
InnerCityHotels = (n,l)((A)(Bars))
F-177
Evaluating Views (cont.)
= (n)((L)(InnerCityHotels))
= (n)((L)((n,l)((A)(Bars))))
= (n)((n,l)((L)((A)(Bars))))
= (n)((L)((A)(Bars)))
= (n)((L & A)(Bars))
= (n)((A & L)(Bars))
F-179