SQL Basics: Querying and Managing Data
SQL Basics: Querying and Managing Data
SQL
1
Purposes of SQL
2
The SQL Query Language
3
Querying Multiple Relations
• What does the following SELECT [Link], [Link]
query compute? FROM Students S, Enrolled E
WHERE [Link]=[Link] AND [Link]=“A”
Enrolled
Given the following instances of sid cid grade
Enrolled and Students: 53831 Carnatic101 C
Students
53831 Reggae203 B
53650 Topology112 A
sid name login age gpa
53666 History105 B
53666 Jones jones@cs 18 3.4
we get: ??
53688 Smith smith@eecs 18 3.2
53650 Smith smith@math 19 3.8
4
Querying Multiple Relations
• What does the following SELECT [Link], [Link]
query compute? FROM Students S, Enrolled E
WHERE [Link]=[Link] AND [Link]=“A”
Enrolled
Given the following instances of sid cid grade
Enrolled and Students: 53831 Carnatic101 C
Students
53831 Reggae203 B
53650 Topology112 A
sid name login age gpa
53666 History105 B
53666 Jones jones@cs 18 3.4
we get:
53688 Smith smith@eecs 18 3.2
53650 Smith smith@math 19 3.8 [Link] [Link]
Smith Topology112
5
Creating Relations in SQL
CREATE TABLE Students
• Creates the “Students” relation
(sid CHAR(20),
– the type (domain) of each field is name CHAR(20),
specified login CHAR(10),
– enforced by the DBMS whenever tuples age INTEGER,
are added or modified gpa REAL)
7
Adding and Deleting Tuples
8
Integrity Constraints (ICs)
• IC: condition that must be true for any instance of the database
– e.g., domain constraints
– ICs are specified when schema is defined
– ICs are checked when relations are modified
9
Keys in a Database
10
Primary Key Constraints
• A set of fields is a key for a relation if :
1. No two distinct tuples can have same values in all key fields, and
2. This is not true for any subset of the key
• If there are > 1 keys for a relation, one of the keys is chosen
(by DBA = DB admin) to be the primary key
– E.g., sid is a key for Students
– The set {sid, gpa} is a superkey.
11
Primary and Candidate Keys in SQL
• Possibly many candidate keys
– specified using UNIQUE
– one of which is chosen as the primary key.
12
Primary and Candidate Keys in SQL
• Possibly many candidate keys
– specified using UNIQUE
– one of which is chosen as the primary key.
13
Primary and Candidate Keys in SQL
• Possibly many candidate keys
– specified using UNIQUE
– one of which is chosen as the primary key.
CREATE TABLE Enrolled
(sid CHAR(20)
• “For a given student and course, there is a cid CHAR(20),
single grade.”
grade CHAR(2),
PRIMARY KEY (sid, cid) )
• vs.
CREATE TABLE Enrolled
• “Students can take only one course, and (sid CHAR(20)
receive a single grade for that course; further,
cid CHAR(20),
no two students in a course receive the same
grade CHAR(2),
grade.”
PRIMARY KEY ???,
UNIQUE ??? )
14
Primary and Candidate Keys in SQL
• Possibly many candidate keys
– specified using UNIQUE
– one of which is chosen as the primary key.
CREATE TABLE Enrolled
(sid CHAR(20)
• “For a given student and course, there is a cid CHAR(20),
single grade.”
grade CHAR(2),
• vs. PRIMARY KEY (sid,cid) )
• “Students can take only one course, and CREATE TABLE Enrolled
receive a single grade for that course; further, (sid CHAR(20)
no two students in a course receive the same
cid CHAR(20),
grade.”
grade CHAR(2),
PRIMARY KEY sid,
UNIQUE (cid, grade))
15
Primary and Candidate Keys in SQL
• Possibly many candidate keys
– specified using UNIQUE
– one of which is chosen as the primary key.
CREATE TABLE Enrolled
(sid CHAR(20)
• “For a given student and course, there is a cid CHAR(20),
single grade.”
grade CHAR(2),
• vs. PRIMARY KEY (sid,cid) )
• “Students can take only one course, and CREATE TABLE Enrolled
receive a single grade for that course; further, (sid CHAR(20)
no two students in a course receive the same
cid CHAR(20),
grade.”
grade CHAR(2),
PRIMARY KEY sid,
• Used carelessly, an IC can prevent the storage
UNIQUE (cid, grade))
of database instances that arise in practice!
16
Foreign Keys, Referential Integrity
• Foreign key : Set of fields in one relation that is used to
`refer’ to a tuple in another relation
– Must correspond to primary key of the second relation
– Like a `logical pointer’
17
Foreign Keys in SQL
• Only students listed in the Students relation should be
allowed to enroll for courses
CREATE TABLE Enrolled
(sid CHAR(20), cid CHAR(20), grade CHAR(2),
PRIMARY KEY (sid,cid),
FOREIGN KEY (sid) REFERENCES Students )
Enrolled
Students
sid cid grade
sid name login age gpa
53666 Carnatic101 C
53666 Jones jones@cs 18 3.4
53666 Reggae203 B
53650 Topology112 A 53688 Smith smith@eecs 18 3.2
53666 History105 B 53650 Smith smith@math 19 3.8
18
Enforcing Referential Integrity
• Consider Students and Enrolled
– sid in Enrolled is a foreign key that references Students.
• Key and foreign key ICs are the most common; more general
ICs supported too
38
Example Instances
• What does the key (sid, bid, day) in Sailor
Reserves mean? sid sname rating age
22 dustin 7 45
31 lubber 8 55
• If the key for the Reserves relation
contained only the attributes (sid, 58 rusty 10 35
bid), how would the semantics
differ? Reserves
sid bid day
22 101 10/10/96
58 103 11/12/96
22
Basic SQL Query
SELECT [DISTINCT] <target-list>
FROM <relation-list>
WHERE <qualification>
23
Can see the next few slides first
24
Example of Conceptual Evaluation
Sailor
SELECT [Link]
FROM Sailors S, Reserves R sid sname rating age
WHERE [Link]=[Link] AND [Link]=103 22 dustin 7 45
31 lubber 8 55
58 rusty 10 35
Step 1: Form cross product of Sailor and Reserves
Reserves
sid sname rating age sid bid day sid bid day
22 dustin 7 45 22 101 10/10/96 22 101 10/10/96
22 dustin 7 45 58 103 11/12/96 58 103 11/12/96
31 lubber 8 55 22 101 10/10/96
31 lubber 8 55 58 103 11/12/96
58 rusty 10 35 22 101 10/10/96
58 rusty 10 35 58 103 11/12/96
25
Example of Conceptual Evaluation
Sailor
SELECT [Link]
FROM Sailors S, Reserves R sid sname rating age
WHERE [Link]=[Link] AND [Link]=103 22 dustin 7 45
31 lubber 8 55
58 rusty 10 35
Step 2: Discard tuples that do not satisfy <qualification>
Reserves
sid sname rating age sid bid day sid bid day
22 dustin 7 45 22 101 10/10/96 22 101 10/10/96
22 dustin 7 45 58 103 11/12/96 58 103 11/12/96
31 lubber 8 55 22 101 10/10/96
31 lubber 8 55 58 103 11/12/96
58 rusty 10 35 22 101 10/10/96
58 rusty 10 35 58 103 11/12/96
26
Example of Conceptual Evaluation
Sailor
SELECT [Link]
FROM Sailors S, Reserves R sid sname rating age
WHERE [Link]=[Link] AND [Link]=103 22 dustin 7 45
31 lubber 8 55
58 rusty 10 35
Step 3: Select the specified attribute(s)
Reserves
sid sname rating age sid bid day sid bid day
22 dustin 7 45 22 101 10/10/96 22 101 10/10/96
22 dustin 7 45 58 103 11/12/96 58 103 11/12/96
31 lubber 8 55 22 101 10/10/96
31 lubber 8 55 58 103 11/12/96
58 rusty 10 35 22 101 10/10/96
58 rusty 10 35 58 103 11/12/96
27
A Note on “Range Variables”
• Really needed only if the same relation appears twice
in the FROM clause
– sometimes used as a short-name
• The previous query can also be written as:
SELECT [Link]
FROM Sailors S, Reserves R It is good style,
however, to use
WHERE [Link]=[Link] AND bid=103
range variables
always!
OR SELECT sname
FROM Sailors, Reserves
WHERE [Link]=[Link]
AND bid=103
28
Joins
sid sname rating age
• Condition/Theta-Join 22 dustin 7 45
• Equi-Join 31 lubber 8 55
58 rusty 10 35
• Natural-Join
• (Left/Right/Full) Outer-Join sid bid day
22 101 10/10/96
58 103 11/12/96
29
Condition/Theta Join
SELECT * sid sname rating age
FROM Sailors S, Reserves R 22 dustin 7 45
WHERE [Link]=[Link] and age >= 40
31 lubber 8 55
58 rusty 10 35
Form cross product, discard rows that do not satisfy the condition
sid sname rating age sid bid day sid bid day
22 dustin 7 45 22 101 10/10/96 22 101 10/10/96
22 dustin 7 45 58 103 11/12/96 58 103 11/12/96
31 lubber 8 55 22 101 10/10/96
31 lubber 8 55 58 103 11/12/96
58 rusty 10 35 22 101 10/10/96
58 rusty 10 35 58 103 11/12/96
30
Equi Join
SELECT * sid sname rating age
FROM Sailors S, Reserves R 22 dustin 7 45
WHERE [Link]=[Link] and age = 45
31 lubber 8 55
A special case of theta join 58 rusty 10 35
Join condition only has equality predicate =
sid sname rating age sid bid day sid bid day
22 dustin 7 45 22 101 10/10/96 22 101 10/10/96
22 dustin 7 45 58 103 11/12/96 58 103 11/12/96
31 lubber 8 55 22 101 10/10/96
31 lubber 8 55 58 103 11/12/96
58 rusty 10 35 22 101 10/10/96
58 rusty 10 35 58 103 11/12/96
31
Natural Join
SELECT * sid sname rating age
FROM Sailors S NATURAL JOIN Reserves R 22 dustin 7 45
31 lubber 8 55
A special case of equi join 58 rusty 10 35
Equality condition on ALL common predicates (sid)
Duplicate columns are eliminated
sid sname rating age bid day sid bid day
22 dustin 7 45 101 10/10/96 22 101 10/10/96
22 dustin 7 45 103 11/12/96 58 103 11/12/96
31 lubber 8 55 101 10/10/96
31 lubber 8 55 103 11/12/96
58 rusty 10 35 101 10/10/96
58 rusty 10 35 103 11/12/96
32
Outer Join
SELECT [Link], R. bid sid sname rating age
FROM Sailors S LEFT OUTER JOIN Reserves R 22 dustin 7 45
ON [Link]=[Link]
31 lubber 8 55
58 rusty 10 35
Preserves all tuples from the left table whether or not there is a match
if no match, fill attributes from right with null
Similarly RIGHT/FULL outer join sid bid day
22 101 10/10/96
sid bid 58 103 11/12/96
22 101
31 null
58 103
33
Expressions and Strings
SELECT [Link], age1=[Link]-5, 2*[Link] AS age2
FROM Sailors S
WHERE [Link] LIKE ‘B_%B’
34
Find sid’s of sailors who’ve reserved a red or a
green boat Sailors (sid, sname, rating, age)
Reserves(sid, bid, day)
Boats(bid, bname, color)
• Assume a Boats relation SELECT [Link]
FROM Sailors S, Boats B, Reserves R
• UNION: Can be used to
WHERE [Link]=[Link] AND [Link]=[Link]
compute the union of any AND ([Link]=‘red’ OR [Link]=‘green’)
two union-compatible sets of
tuples
– can themselves be the result of
SELECT [Link]
SQL queries
FROM Sailors S, Boats B, Reserves R
• If we replace OR by AND in the WHERE [Link]=[Link] AND [Link]=[Link]
first version, what do we get? AND [Link]=‘red’
UNION
• Also available: EXCEPT (What SELECT [Link]
do we get if we replace UNION FROM Sailors S, Boats B, Reserves R
by EXCEPT?) WHERE [Link]=[Link] AND [Link]=[Link]
AND [Link]=‘green’
35
Sailors (sid, sname, rating, age)
Find sid’s of sailors who’ve reserved Reserves(sid, bid, day)
a red and a green boat Boats(bid, bname, color)
36
Sailors (sid, sname, rating, age)
Find sid’s of sailors who’ve reserved Reserves(sid, bid, day)
a red and a green boat Boats(bid, bname, color)
SELECT [Link]
FROM Sailors S, Boats B1, Reserves R1,
• INTERSECT: Can be used to Boats B2, Reserves R2
compute the intersection of WHERE [Link]=[Link] AND [Link]=[Link]
AND [Link]=[Link] AND [Link]=[Link]
any two union-compatible AND ([Link]=‘red’ AND [Link]=‘green’)
sets of tuples.
– Included in the SQL/92 SELECT [Link] Key field!
standard, but some systems FROM Sailors S, Boats B, Reserves R
don’t support it WHERE [Link]=[Link] AND [Link]=[Link]
AND [Link]=‘red’
INTERSECT
SELECT [Link]
FROM Sailors S, Boats B, Reserves R
WHERE [Link]=[Link] AND [Link]=[Link]
AND [Link]=‘green’
37
Nested Queries
Find names of sailors who’ve reserved boat #103:
SELECT [Link] Sailors (sid, sname, rating, age)
FROM Sailors S Reserves(sid, bid, day)
WHERE [Link] IN (SELECT [Link] Boats(bid, bname, color)
FROM Reserves R
WHERE [Link]=103)
39
Nested Queries with Correlation
Find names of sailors who’ve reserved boat #103
at most once:
SELECT [Link]
FROM Sailors S
WHERE UNIQUE (SELECT [Link]
FROM Reserves R
WHERE [Link]=103 AND [Link]=[Link])
40
More on Set-Comparison Operators
• We’ve already seen IN, EXISTS and UNIQUE
• Can also use NOT IN, NOT EXISTS and NOT UNIQUE.
• Also available: op ANY, op ALL, op IN
– where op : >, <, =, <=, >=
• Find sailors whose rating is greater than that of some
sailor called Horatio
– similarly ALL SELECT *
FROM Sailors S
WHERE [Link] > ANY (SELECT [Link]
FROM Sailors S2
WHERE [Link]=‘Horatio’)
41
Aggregate Operators
COUNT (*)
COUNT ( [DISTINCT] A)
Check yourself:
What do these queries compute? SUM ( [DISTINCT] A)
AVG ( [DISTINCT] A)
MAX (A)
MIN (A)
SELECT COUNT (*)
single column
FROM Sailors S
SELECT [Link]
SELECT AVG ([Link]) FROM Sailors S
FROM Sailors S WHERE [Link]= (SELECT MAX([Link])
WHERE [Link]=10 FROM Sailors S2)
51
Null Values
• Field values in a tuple are sometimes
– unknown, e.g., a rating has not been assigned, or
– inapplicable, e.g., no spouse’s name
– SQL provides a special value null for such situations.
52
Standard Boolean 2-valued logic
• True = 1, False = 0
• Suppose X = 5
– (X < 100) AND (X >= 1) is T ∧ T = T
– (X > 100) OR (X >= 1) is F ∨ T = T
– (X > 100) AND (X >= 1) is F ∧ T = F
– NOT(X = 5) is ¬T = F
• Intuitively,
– T = 1, F = 0
– For V1, V2 ∈ {1, 0}
– V1 ∧ V2 = MIN (V1, V2)
– V1 ∨ V2 = MAX(V1, V2)
– ¬(V1) = 1 – V1
53
2-valued logic does not work for nulls
54
3-Valued Logic For Null
• TRUE (= 1), FALSE (= 0), UNKNOWN (= 0.5)
– unknown is treated as 0.5
• Therefore,
– NOT UNKNOWN = UNKNOWN
– UNKNOWN OR TRUE = TRUE
– UNKNOWN AND TRUE = UNKNOWN
– UNKNOWN AND FALSE = FALSE
– UNKNOWN OR FALSE = UNKNOWN
55
New issues for Null
• The presence of null complicates many issues. E.g.:
– Special operators needed to check if value IS/IS NOT NULL
– Be careful!
– “WHERE X = NULL” does not work!
– Need to write “WHERE X IS NULL”
• Meaning of constructs must be defined carefully
– e.g., WHERE clause eliminates rows that don’t evaluate to true
– So not only FALSE, but UNKNOWNs are eliminated too
– very important to remember!
• But NULL allows new operators (e.g. outer joins)
• Arithmetic with NULL
– all of +, -, *, / return null if any argument is null
• Can force ”no nulls” while creating a table
– sname char(20) NOT NULL
– primary key is always not null
56
Aggregates with NULL
sid sname rating age • What do you get for
22 dustin 7 45 • SELECT count(*) from R1?
31 lubber 8 55
• SELECT count(rating) from R1?
58 rusty 10 35
R1
57
Aggregates with NULL
sid sname rating age
22 dustin 7 45 • What do you get for
31 lubber 8 55
• SELECT count(*) from R1?
58 rusty 10 35
R1 • SELECT count(rating) from R1?
• Ans: 3 for both
58
Aggregates with NULL
sid sname rating age
22 dustin 7 45 • What do you get for
31 lubber 8 55
• SELECT count(*) from R1?
58 rusty 10 35
R1 • SELECT count(rating) from R1?
sid sname rating age • Ans: 3 for both
22 dustin 7 45 • What do you get for
31 lubber null 55 • SELECT count(*) from R2?
58 rusty 10 35 • SELECT count(rating) from R2?
R2
59
Aggregates with NULL
sid sname rating age
22 dustin 7 45 • What do you get for
31 lubber 8 55
• SELECT count(*) from R1?
58 rusty 10 35
R1 • SELECT count(rating) from R1?
sid sname rating age • Ans: 3 for both
22 dustin 7 45 • What do you get for
31 lubber null 55 • SELECT count(*) from R2?
58 rusty 10 35 • SELECT count(rating) from R2?
R2 • Ans: First 3, then 2
60
Aggregates with NULL
• COUNT, SUM, AVG, MIN, MAX (with or without DISTINCT)
– Discards null values first
– Then applies the aggregate
– Except count(*)
• If only applied to null values, the result is null
63
“WITH” clause – very useful!
• You will find “WITH” clause very useful!
WITH Temp1 AS
(SELECT ….. ..),
Temp2 AS
(SELECT ….. ..)
SELECT X, Y
FROM TEMP1, TEMP2
WHERE….
64
Overview: General Constraints
CREATE TABLE Sailors
( sid INTEGER,
• Useful when more general ICs sname CHAR(10),
than keys are involved rating INTEGER,
age REAL,
PRIMARY KEY (sid),
• There are also ASSERTIONS to CHECK ( rating >= 1
specify constraints that span AND rating <= 10 )
across multiple tables
CREATE TABLE Reserves
( sname CHAR(10),
• There are TRIGGERS too : bid INTEGER,
day DATE,
procedure that starts
PRIMARY KEY (bid,day),
automatically if specified changes CONSTRAINT noInterlakeRes
occur to the DBMS CHECK (`Interlake’ <>
( SELECT [Link]
FROM Boats B
WHERE [Link]=bid))) 65
Only FYI, not covered in detail
Triggers
• Trigger: procedure that starts automatically if specified
changes occur to the DBMS
• Three parts:
– Event (activates the trigger)
– Condition (tests whether the triggers should run)
– Action (what happens if the trigger runs)
66
Summary
• SQL has a huge number of constructs and possibilities
– You need to learn and practice it on your own
– Given a problem, you should be able to write a SQL query and verify
whether a given one is correct
67