Querying Relational Databases using SQL
Part--3
Cong Gao
Professor
School of Computer Science and Engineering
Nanyang Technological University, Singapore
1
Summary and roadmap
Introduction to SQL Next
SELECT NULL
FROM
WHERE Outerjoin
Eliminating duplicates Insert/Delete tuples
Renaming attributes Create/Alter/Delete
Expressions in SELECT Clause tables
Patterns for Strings
Constraints (primary key)
Ordering
Joins Views
Subquery More constraints
Aggregations Triggers
UNION, INTERSECT, EXCEPT Indexes
2
NULL in SQL
In SQL, whenever we want to leave a value
blank, we set it as NULL
The DBMS regards NULL as “an unknown
value”
This makes sense but it leads to a lot of
complications…
3
Issues with NULL
Any arithmetic operations Product
involving NULL would
PName Price
result in NULL
iPhone 4 888
iPad 2 668
iPhone xx NULL
EOS 550D 1199
SELECT Price * 10
FROM Product Price
WHERE PName = ‘iPad 2’ 6680
4
Issues with NULL (cont.)
Any arithmetic operations Product
involving NULL would
PName Price
result in NULL
iPhone 4 888
iPad 2 668
iPhone xx NULL
EOS 550D 1199
SELECT Price * 10
FROM Product Price
WHERE PName = ‘iPhone xx’ NULL
5
Issues with NULL (cont.)
Any comparison involving Product
NULL results in FALSE
PName Price
iPhone 4 888
iPad 2 668
iPhone xx NULL
EOS 550D 1199
SELECT * PName Price
FROM Product iPhone 4 888
WHERE Price < 1000 iPad 2 668
6
Issues with NULL (cont.)
Any comparison involving Product
NULL results in FALSE
PName Price
iPhone 4 888
iPad 2 668
iPhone xx NULL
EOS 550D 1199
SELECT * PName Price
FROM Product EOS 550D 1199
WHERE Price >= 1000
7
Issues with NULL (cont.)
Product
Any comparison involving
PName Price
NULL results in FALSE
iPhone 4 888
iPad 2 668
iPhone xx NULL
EOS 550D 1199
SELECT *
FROM Product
PName Price
WHERE Price < 1000
iPhone 4 888
OR Price >= 1000
iPad 2 668
EOS 550D 1199
8
Issues with NULL (cont.)
Product
Any comparison involving
PName Price
NULL results in FALSE
iPhone 4 888
iPad 2 668
iPhone xx NULL
EOS 550D 1199
SELECT *
FROM Product
PName Price
WHERE Price < 1000
iPhone 4 888
OR Price >= 1000
iPad 2 668
OR Price = NULL
EOS 550D 1199
9
Issues with NULL (cont.)
Product
Any comparison involving
PName Price
NULL results in FALSE
iPhone 4 888
Use IS NULL to check
iPad 2 668
whether a value is NULL
iPhone xx NULL
EOS 550D 1199
SELECT *
FROM Product
WHERE Price < 1000 PName Price
OR Price >= 1000 iPhone 4 888
OR Price IS NULL iPad 2 668
iPhone xx NULL
EOS 550D 119910
Issues with NULL (cont.)
Product
Any comparison involving
PName Price
NULL results in FALSE
iPhone 4 888
iPad 2 668
iPhone xx NULL
EOS 550D 1199
SELECT *
FROM Product
PName Price
WHERE Price <> NULL
11
Issues with NULL (cont.)
Product
Any comparison involving
PName Price
NULL results in FALSE
iPhone 4 888
Use IS NOT NULL to
iPad 2 668
check whether a value is
iPhone xx NULL
not NULL
EOS 550D 1199
SELECT *
FROM Product PName Price
WHERE Price IS NOT NULL iPhone 4 888
iPad 2 668
EOS 550D 1199
12
Issues with NULL (cont.)
Product
What about GROUP BY?
PName Price
NULLs are taken into iPhone 4 888
account in group formation
iPad 2 668
iPhone xx NULL
EOS 550D 1199
SELECT Price,
Price Cnt
COUNT(*) AS Cnt
NULL 1
FROM Product
GROUP BY Price 668 1
888 1
1199 1 13
Issues with NULL (cont.)
What about joins?
Phone Tablet
PName Price PName Price
iPhone 4 888 ipad 2 668
iPhone xx NULL IdeaPad NULL
SELECT P.PName, T.PName PName PName
FROM Phone P, Tablet T iPhone 4 ipad 2
WHERE P.Price > T.Price
14
Issues with NULL (cont.)
What about joins?
Phone Tablet
PName Price PName Price
iPhone 4 888 ipad 2 668
iPhone xx NULL IdeaPad NULL
SELECT P.PName, T.PName PName PName
FROM Phone P, Tablet T
WHERE P.Price = T.Price
15
Issues with NULL (cont.)
NULLs are ignored in Product
SUM, PName Price
MIN, iPhone 4 888
MAX iPad 2 668
iPhone xx NULL
EOS 550D 1199
SumPrice
SELECT SUM(Price) as SumPrice 2755
FROM Product
16
Issues with NULL (cont.)
NULLs are ignored in AVG Product
PName Price
iPhone 4 888
iPad 2 668
iPhone xx NULL
EOS 550D 1199
SELECT AVG(Price) as AvgPrice AvgPrice
FROM Product 918
17
Issues with NULL (cont.)
SQL ignores NULLs when Product
counting the number of PName Price
values in a column iPhone 4 888
iPad 2 668
NULL NULL
EOS 550D 1199
SELECT COUNT(Price)
FROM Product 3
18
Issues with NULL (cont.)
But NULLs are still counted Product
in COUNT(*) PName Price
iPhone 4 888
iPad 2 668
NULL NULL
EOS 550D 1199
SELECT COUNT(*)
4
FROM Product
19
Issues with NULL (cont.)
But NULLs are still counted Product
in COUNT(*) PName Price
iPhone 4 888
Avoid NULLs in tables
whenever possible. iPad 2 668
This can usually be achieved Milestone NULL
with proper schema design. EOS 550D 1199
SELECT COUNT(*)
4
FROM Product
20
Summary and roadmap
Introduction to SQL Next
SELECT Outerjoin
FROM
WHERE Insert/Delete tuples
Eliminating duplicates Create/Alter/Delete
Renaming attributes tables
Expressions in SELECT Clause Constraints (primary key)
Patterns for Strings
Views
Ordering
Joins More constraints
Subquery Triggers
Aggregations Indexes
UNION, INTERSECT, EXCEPT
NULL
21
Join Sold
Product PName Price PName Shop
iPhone 4 888 iPhone 4 Suntec
SELECT P.PName, Price, Shop
FROM Product AS P, Sold AS S
WHERE P.PName = S.PName
PName Price Shop
iPhone 4 888 Suntec
SELECT P.PName, Price, Shop
FROM Product AS P JOIN Sold AS S
ON P.PName = S.PName
22
Join Sold
Product PName Price PName Shop
iPhone 4 888 iPhone 4 Suntec
iPad 2 668
PName Price Shop
iPhone 4 888 Suntec
SELECT P.PName, Price, Shop
FROM Product AS P JOIN Sold AS S
ON P.PName = S.PName
23
Outerjoins Sold
Product PName Price PName Shop
iPhone 4 888 iPhone 4 Suntec
iPad 2 668
PName Price Shop
How? iPhone 4 888 Suntec
iPad 2 668 NULL
SELECT P.PName, Price, Shop
FROM Product AS P JOIN Sold AS S
ON P.PName = S.PName
24
Outerjoins (cont.) Sold
Product PName Price PName Shop
iPhone 4 888 iPhone 4 Suntec
iPad 2 668
Include the left
PName Price Shop
tuples even
when there is iPhone 4 888 Suntec
no match iPad 2 668 NULL
SELECT P.PName, Price, Shop
FROM Product AS P LEFT OUTER JOIN Sold AS S
ON P.PName = S.PName
25
Outerjoins (cont.) Sold
Product PName Price PName Shop
iPhone 4 888 iPhone 4 Suntec
NULL ION
Include the right
tuples even
when there is no PName Price Shop
match iPhone 4 888 Suntec
NULL NULL ION
SELECT P.PName, Price, Shop
FROM Product AS P RIGHT OUTER JOIN Sold AS S
ON P.PName = S.PName
26
Outerjoins (cont.) Sold
Product PName Price PName Shop
iPhone 4 888 iPhone 4 Suntec
iPad 2 668 NULL ION
Include both left PName Price Shop
and right tuples
iPhone 4 888 Suntec
even if there is
no match iPad 2 668 NULL
NULL NULL ION
SELECT P.PName, Price, Shop
FROM Product AS P FULL OUTER JOIN Sold AS S
ON P.PName = S.PName
27
More join type: Inner Join
Syntax
• R INNER JOIN S USING (<attribute list>)
• R INNER JOIN S ON R.column_name = S.column_name
Example
TableA TableB
Column1 Column2 Column1 Column3
1 2 1 3
The INNER JOIN of TableA and TableB on Column1 will return:
TableA.Column1 TableA.Column2 TableB.Column1 TableB.Column3
1 2 1 3
SELECT * FROM TableA INNER JOIN TableB USING (Column1)
SELECT * FROM TableA INNER JOIN TableB ON TableA.Column1 =
28
TableB.Column1 47/50
Natural Join
Syntax R NATURAL JOIN S
Example
TableA TableB
Column1 Column2 Column1 Column3
1 2 1 3
The NATURAL JOIN of TableA and TableB will return:
Column1 Column2 Column3
1 2 3
SELECT * FROM TableA NATURAL JOIN TableB
- The repeated columns are avoided.
- One can not specify the joining columns in a natural join.
29
Summary and roadmap
Introduction to SQL Next
SELECT Insert/Delete tuples
FROM
WHERE Create/Alter/Delete
Eliminating duplicates tables
Renaming attributes Constraints (primary key)
Expressions in SELECT Clause Views
Patterns for Strings
More constraints
Ordering
Joins Triggers
Subquery Indexes
Aggregations
UNION, INTERSECT, EXCEPT
NULL
Outerjoin
30
Inserting One Tuple
Product
INSERT INTO Product PName Price
VALUES( ‘iPhone 5’, 999 ) iPhone 4 888
iPad 2 668
Alternative approaches:
INSERT INTO
Product( PName, Price)
VALUES( ‘iPhone 5’, 999 ) PName Price
iPhone 4 888
INSERT INTO iPad 2 668
Product( Price, PName,)
VALUES( 999, ‘iPhone 5’ ) iPhone 5 999
31
Partial Insertion
Product
INSERT INTO PName Price
Product( PName ) iPhone 4 888
VALUES( ‘iPhone 5’ ) iPad 2 668
PName Price
iPhone 4 888
iPad 2 668
iPhone 5 NULL
32
Tuple Insertion via Subqueries
Product
The ‘Sold’ table is initially PName Price
empty. iPhone 4 888
iPad 2 668
INSERT INTO Sold
SELECT PName, ‘Suntec’ Sold
FROM Product
PName Shop
iPhone 4 Suntec
iPad 2 Suntec
33
Tuple Insertion via Subqueries
Sold
Assume that a new shop at PName Shop
the ION sells all products iPhone 4 Suntec
sold at the Suntec shop iPad 2 Suntec
INSERT INTO Sold
SELECT PName, ‘ION’ PName Shop
FROM Sold iPhone 4 Suntec
iPad 2 Suntec
iPhone 4 ION
iPad 2 ION
34
Tuple Deletion
Sold
DELETE FROM Sold PName Shop
WHERE PName = ‘iPad 2’ iPhone 4 Suntec
iPad 2 Suntec
PName Shop
iPhone 4 Suntec
35
Tuple Deletion (cont.)
Product Sold
PName Price PName Shop
iPhone 4 888 iPhone 4 Suntec
iPad 2 668 iPad 2 Suntec
Remove from the Suntec shop
all products over 800 dollars
PName Shop
DELETE FROM Sold
WHERE Shop = ‘Suntec’ iPad 2 Suntec
AND Sold.PName IN
(SELECT P.PName FROM Product AS P
WHERE Price > 800)
36
Deleting All Tuples
Sold
DELETE FROM Sold; PName Shop
iPhone 4 Suntec
iPad 2 Suntec
PName Shop
37
Exercise
Sold
Remove (i) any product from PName Shop
Suntec that is also sold at
ION iPhone 4 Suntec
and (ii) any product iPad 2 Suntec
from ION that is also sold
at Suntec iPhone 4 ION
DELETE FROM Sold
WHERE (Sold.Shop = ‘Suntec’ AND
Sold.PName IN
(Select S1.PName FROM Sold AS S1
WHERE S1.Shop = ‘ION’))
OR (Sold.Shop = ‘ION’ AND Sold.PName IN
(Select S2.PName FROM Sold AS S2
WHERE S2.Shop = ‘Suntec’))
38
Tuple Update
Product
Assume that the price of PName Price
iPhone 4 should be reduced iPhone 4 888
to 777 iPad 2 668
UPDATE Product
SET Price = 777 PName Price
WHERE PName = ‘iPhone 4’ iPhone 4 777
iPad 2 668
39
Tuple Update (cont.)
Product
Assume that Google PName Price Company
buys Apple and reduces iPhone 4 888 Apple
the prices of all its iPad 2 668 Apple
products by 100
UPDATE Product
SET Price = Price – 100, PName Price Company
Company = ‘Google’ iPhone 4 788 Google
WHERE Company = iPad 2 568 Google
‘Apple’
40
Tuple Update (cont.) Maker
Product PName Price PName Company
iPhone 4 888 iPhone 4 Apple
iPad 2 668 iPad 2 Apple
Milestone 798 Milestone Motorola
Reduce the price of all Apple products by 10%
UPDATE Product
SET Price = Price * 0.9
WHERE Product.PName IN
(SELECT Maker.PName FROM Maker
WHERE Company = ‘Apple’)
41
Tuple Update (cont.) Maker
Product PName Price PName Company
iPhone 4 888 iPhone 4 Apple
iPad 2 668 iPad 2 Apple
Milestone 798 Milestone Motorola
Reduce the price of all products by 10%
UPDATE Product
SET Price = Price * 0.9
42
Tuple Update (cont.)
Product PName Price
iPhone 4 888
iPad 2 668
Milestone 798
Set the price of every product to half of the
price of iPhone 4
UPDATE Product
SET Price =
( SELECT P.Price / 2
FROM Product AS P
WHERE P.PName = ‘iPhone 4’)
43
Exercise
Beer Wine
Name Maker Price Name Maker Price
Update the price of every beer to the
average price of the wine by the same maker
UPDATE Beer
SET Beer.Price =
(SELECT AVG(Wine.Price)
FROM Wine
WHERE Wine.Maker = Beer.Maker)
44
Exercise
Beer Wine
Name Maker Price Name Maker Price
Delete any beer by a maker that does not
produce any wine
DELETE FROM Beer
WHERE NOT EXISTS
(SELECT *
FROM Wine
WHERE Wine.Maker = Beer.Maker)
45
Exercise
Beer Wine
Name Maker Price Name Maker Price
For each beer, if there does not exist a wine
with the same name, then create a wine with
the same name and maker, but twice the price
INSERT INTO Wine
SELECT B.Name, B.Maker, B.Price * 2
FROM Beer AS B
WHERE NOT EXISTS
(SELECT * FROM Wine
WHERE Wine.Name = B.Name)
46
Table Creation Product
PName Price
CREATE TABLE Product(
PName VARCHAR(30),
Price INT );
In general:
CREATE TABLE <table name> (
<column name 1> <column type 1>,
<column name 2> <column type 2>,
… );
47
Column Types
INT or INTEGER (synonyms)
REAL or FLOAT (synonyms)
CHAR(n): fixed-length string of n
characters
VARCHAR(n): variable-length string of up
to n characters
DATE: = In ’yyyy-mm-dd’ format
…
48
Summary and roadmap
Introduction to SQL Next
SELECT Constraints (primary key)
FROM
WHERE Views
Eliminating duplicates More constraints
Renaming attributes Triggers
Expressions in SELECT Clause
Indexes
Patterns for Strings
Ordering
Joins
Subquery
Aggregations
UNION, INTERSECT, EXCEPT
NULL
Outerjoin
Insert/Delete tuples
Create/Alter/Delete tables 49
Table Creation (cont.) Product
PName Price
CREATE TABLE Product(
PName VARCHAR(30), Price INT );
What if we want to make sure that all
products have distinct names?
Solution: declare PName as PRIMARY KEY
or UNIQUE
50
PRIMARY KEY Product
PName Price
CREATE TABLE Product(
PName VARCHAR(30), Price INT );
What if we want to make sure that all
products have distinct names?
CREATE TABLE Product(
PName VARCHAR(30), Price INT,
PRIMARY KEY (PName) );
51
UNIQUE Product
PName Price
CREATE TABLE Product(
PName VARCHAR(30), Price INT );
What if we want to make sure that all
products have distinct names?
CREATE TABLE Product(
PName VARCHAR(30), Price INT,
UNIQUE(PName) );
52
PRIMARY KEY (cont.) Catalog
PName Shop Price
We want to make sure that there is no
duplicate PName with the same Shop
CREATE TABLE Catalog(
PName VARCHAR(30),
Shop VARCHAR(30),
Price INT,
PRIMARY KEY (PName, Shop) );
53
UNIQUE (cont.) Catalog
PName Shop Price
We want to make sure that there is no
duplicate PName with the same Shop
CREATE TABLE Catalog(
PName VARCHAR(30),
Shop VARCHAR(30),
Price INT,
UNIQUE (PName, Shop) );
54
PRIMARY KEY vs. UNIQUE
Catalog
Difference 1 PName Shop Price
Only ONE set of attributes in a table can be
declared as PRIMARY KEY
But we can declare multiple sets of attributes
as UNIQUE
CREATE TABLE Catalog( PName VARCHAR(30),
Shop VARCHAR(30), Price INT,
UNIQUE (PName, Shop), UNIQUE (Shop, Price)
);
55
PRIMARY KEY vs. UNIQUE
Catalog
Difference 2 PName Shop Price
If set of attributes are declared as PRIMARY
KEY, then none of these attributes can be
NULL
UNIQUE attributes still allow NULLs
CREATE TABLE Catalog(
PName VARCHAR(30),
Shop VARCHAR(30),
Price INT,
UNIQUE (PName, Shop) );
56
NOT NULL Catalog
PName Shop Price
We want to make sure that the price of
each product is not NULL
CREATE TABLE Catalog(
PName VARCHAR(30),
Shop VARCHAR(30),
Price INT NOT NULL);
57
NOT NULL (cont.) Catalog
PName Shop Price
We want to make sure that the price as
well as PName of each product is not NULL
CREATE TABLE Catalog(
PName VARCHAR(30) NOT NULL,
Shop VARCHAR(30),
Price INT NOT NULL);
58
NOT NULL (cont.) Catalog
PName Shop Price
CREATE TABLE Catalog(
PName VARCHAR(30) NOT NULL,
Shop VARCHAR(30),
Price INT NOT NULL);
NOT NULL may prevent partial insertions
INSERT INTO Product(PName)
Error!
Values( ‘iPhone 5’ )
59
DEFAULT Catalog
PName Shop Price
We want to specify that, by default, the
shop and price of a product is ‘Suntec’ and
1, respectively
CREATE TABLE Catalog(
PName VARCHAR(30) DEFAULT ‘Suntec’,
Shop VARCHAR(30),
Price INT DEFAULT 1);
60
Combination Catalog
PName Shop Price
We want to specify that, by default, the
shop and price of a product is ‘Suntec’ and
1, respectively. In addition, the shop
should not be NULL
CREATE TABLE Catalog(
PName VARCHAR(30) NOT NULL
DEFAULT ‘Suntec’,
Shop VARCHAR(30),
Price INT DEFAULT 1);
61
Table Deletion Catalog
PName Shop Price
DROP TABLE Catalog
62
Table Modification
Adding a new attribute
ALTER TABLE Catalog Catalog
ADD Price INT PName Shop
We can also add some declarations
ALTER TABLE Catalog
ADD Price INT NOT NULL
DEFAULT 1 Catalog
PName Shop Price
63
Table Modification
Deleting an attribute
ALTER TABLE Catalog Catalog
DROP Price PName Shop Price
Catalog
PName Shop
64
Summary and roadmap
Introduction to SQL Next
SELECT
FROM Views
WHERE More constraints
Eliminating duplicates
Renaming attributes
FOREIGN KEY
Expressions in SELECT Clause CHECK
Patterns for Strings ASSERTION
Ordering
Joins
Triggers
Subquery Indexes
Aggregations
UNION, INTERSECT, EXCEPT
NULL
Outerjoin
Insert/Delete tuples
Create/Alter/Delete tables
Constraints (primary key)
65