SlideShare a Scribd company logo
SQL - 1
Week 6
2
Basic form of SQL Queries
• target-list A list of attributes of output relations in
relation-list
• relation-list A list of relation names (possibly with a
range-variable after each name)
e.g. Sailors S, Reserves R
• qualification Comparisons (Attr op const or Attr1 op
Attr2, where op is one of <, >, ≤, ≥, =, ≠) combined using
AND, OR and NOT.
SELECT target-list
FROM relation-list
WHERE qualification
3
Whatʼs contained in an SQL Query?
Every SQL Query must have:
• SELECT clause: specifies columns to be retained in
result
• FROM clause: specifies a cross-product of tables
The WHERE clause (optional) specifies selection
conditions on the tables mentioned in the FROM clause
SELECT target-list
FROM relation-list
WHERE qualification
4
General SQL Conceptual Evaluation
Strategy
• Semantics of an SQL query defined in terms of
the following conceptual evaluation strategy:
– Compute the cross-product of relation-list.
– Discard resulting tuples if they fail qualifications.
– Delete attributes that are not in target-list.
• This strategy is probably the least efficient way
to compute a query! An optimizer will find more
efficient strategies to compute the same answers.
5
Conceptual Evaluation Strategy
Nested loops evaluation:
Foreach tuple t1 in R1
…
Foreach tuple tn in Rn
1. Substitute the attribute names in the qualification part
with values from t1, …, tn
2. If the modified qualification part evaluates True
then output target-attribute-values
else do nothing
end
…
end
SELECT target-attribute-list
FROM R1, …, Rn
WHERE qualification
6
Table Definitions
We will be using the following relations in our
examples:
Sailors(sid, sname, rating, age)
Boats(bid, bname, color)
Reserves(sid, bid, day)
7
sid sname rating age
22 Dustin 7 45.0
29 Brutus 1 33.0
31 Lubber 8 55.5
32 Andy 8 25.5
58 Rusty 10 35.0
64 Horatio 7 35.0
71 Zorba 10 16.0
74 Horatio 9 35.0
85 Art 3 25.5
95 Bob 3 63.5
sid bid day
22 101 10/10/04
22 102 10/10/04
22 103 10/08/04
22 104 10/07/04
31 102 11/10/04
31 103 11/06/04
31 104 11/12/04
64 101 09/05/04
64 102 09/08/04
74 103 09/08/04
bid bname Color
101 Interlake blue
102 Interlake red
103 Clipper green
104 Marine red
Sailors Reserves
Boats
8
A Simple SQL Query
Find the names and
ages of all sailors
sid sname rating age
22 Dustin 7 45.0
29 Brutus 1 33.0
31 Lubber 8 55.5
32 Andy 8 25.5
58 Rusty 10 35.0
64 Horatio 7 35.0
71 Zorba 10 16.0
74 Horatio 9 35.0
85 Art 3 25.5
95 Bob 3 63.5
9
Result of Previous Query
SELECT S.sname, S.age
FROM Sailors S;
Duplicate Results
sname age
Dustin 45.0
Brutus 33.0
Lubber 55.5
Andy 25.5
Rusty 35.0
Horatio 35.0
Zorba 16.0
Horatio 35.0
Art 25.5
Bob 63.5
10
Preventing Duplicate Tuples in
the Result
• Use the DISTINCT keyword in the
SELECT clause:
SELECT DISTINCT S.sname, S.age
FROM Sailors S;
11
Results of Original Query
without Duplicates
Appears only once
sname age
Dustin 45.0
Brutus 33.0
Lubber 55.5
Andy 25.5
Rusty 35.0
Horatio 35.0
Zorba 16.0
Art 25.5
Bob 63.5
12
Example SQL Query…1
Find the names of sailors who have reserved boat
103
Relational Algebra:
πsname ((σbid=103Reserves) Sailors)
SQL:
SELECT S.sname
FROM Sailors S, Reserves R
WHERE S.sid=R.sid AND R.bid=103;
13
Result of Previous Query
sid bid day
22 103 10/08/04
31 103 11/06/04
74 103 09/08/04
sid sname rating age
22 Dustin 7 45.0
29 Brutus 1 33.0
31 Lubber 8 55.5
32 Andy 8 25.5
58 Rusty 10 35.0
64 Horatio 7 35.0
71 Zorba 10 16.0
74 Horatio 9 35.0
85 Art 3 25.5
95 Bob 3 63.5
sname
Dustin
Lubber
Horatio
Result:
14
A Note on Range Variables
• Really needed only if the same relation appears twice
in the FROM clause. The previous query can also be
written as:
SELECT S.sname
FROM Sailors S, Reserves R
WHERE S.sid=R.sid AND R.bid=103;
OR
SELECT sname
FROM Sailors, Reserves
WHERE Sailors.sid=Reserves.sid AND bid=103;
However, it is a good
style to always use
range variables!
15
Example SQL Query…2
Find the sids of sailors who have reserved a red boat
16
Example SQL Query…3
Find the names of sailors who have reserved a red boat
17
Example SQL Query…4
Find the colors of boats reserved by ʻLubberʼ
18
Example SQL Query…5
Find the names of sailors who have reserved at
least one boat
19
Expressions and Strings
• AS and = are two ways to name fields in
result.
• LIKE is used for string matching. ʻ_ʼ
stands for exactly one arbitrary character
and ʻ%ʼ stands for 0 or more arbitrary
characters.
20
Expressions and Strings Example
Find triples (of ages of sailors and two fields defined by
expressions, i.e. current age-1 and twice the current age) for
sailors whose names begin and end with B and contain at
least three characters.
SELECT S.age, age1=S.age-1, 2*S.age AS age2
FROM Sailors S
WHERE S.sname LIKE ʻB_%Bʼ;
age age1 age2
63.5 62.5 127.0
63.5
3
Bob
95
25.5
3
Art
85
35.0
9
Horatio
74
16.0
10
Zorba
71
35.0
7
Horatio
64
35.0
10
Rusty
58
25.5
8
Andy
32
55.5
8
Lubber
31
33.0
1
Brutus
29
45.0
7
Dustin
22
age
rating
sname
sid
63.5
3
Bob
95
25.5
3
Art
85
35.0
9
Horatio
74
16.0
10
Zorba
71
35.0
7
Horatio
64
35.0
10
Rusty
58
25.5
8
Andy
32
55.5
8
Lubber
31
33.0
1
Brutus
29
45.0
7
Dustin
22
age
rating
sname
sid
Result:
21
UNION, INTERSECT, EXCEPT
• UNION: Can be used to compute the union of any
two union-compatible sets of tuples (which are
themselves the result of SQL queries).
• EXCEPT: Can be used to compute the set-
difference operation on two union-compatible sets
of tuples (Note: In ORACLE, the command for
set-difference is MINUS).
• INTERSECT: Can be used to compute the
intersection of any two union-compatible sets of
tuples.
22
Illustration of UNION…1
Find the names of sailors who have reserved a red or a
green boat
Intuitively, we would write:
SELECT S.sname
FROM Sailors S, Boats B, Reserves R
WHERE S.sid=R.sid AND R.bid=B.bid
AND (B.color=ʻredʼ OR B.color=ʻgreenʼ);
23
Illustration of UNION…2
We can also do this using a UNION keyword:
SELECT S.sname
FROM Sailors S, Boats B, Reserves R
WHERE S.sid=R.sid AND R.bid=B.bid
AND B.color=ʻredʼ
UNION
SELECT S.sname
FROM Sailors S, Boats B, Reserves R
WHERE S.sid=R.sid AND R.bid=B.bid
AND B.color=ʻgreenʼ;
Unlike other operations, UNION
eliminates duplicates! Same as INTERSECT,
EXCEPT. To retain duplicates, use
“UNION ALL”
24
Illustration of INTERSECT…1
Find names of sailors whoʼve reserved a red and a green
boat
Intuitively, we would write the SQL query as:
SELECT S.sname
FROM Sailors S, Boats B1, Reserves R1, Boats B2,
Reserves R2
WHERE S.sid=R1.sid AND R1.bid=B1.bid
AND S.sid=R2.sid AND R2.bid=B2.bid
AND (B1.color=ʻredʼ AND B2.color=ʻgreenʼ);
25
Illustration of INTERSECT…2
We can also do this using a INTERSECT keyword:
SELECT S.sname
FROM Sailors S, Boats B, Reserves R
WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=ʻredʼ
INTERSECT
SELECT S2.sname
FROM Sailors S2, Boats B2, Reserves R2
WHERE S2.sid=R2.sid AND R2.bid=B2.bid AND B2.color=ʻgreenʼ;
(Is this correct??)
26
(Semi-)Correct SQL Query for
the Previous Example
SELECT S.sid
FROM Sailors S, Boats B, Reserves R
WHERE S.sid=R.sid AND R.bid=B.bid
AND B.color=ʻredʼ
INTERSECT
SELECT S2.sid
FROM Sailors S2, Boats B2, Reserves R2
WHERE S2.sid=R2.sid AND R2.bid=B2.bid
AND B2.color=ʻgreenʼ;
(This time we have actually extracted the sids of sailors, and not their
names.)
(But the query asks for the names of the sailors.)
27
Illustration of EXCEPT
Find the sids of all sailors who have reserved red boats but
not green boats:
SELECT S.sid
FROM Sailors S, Boats B, Reserves R
WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=ʻredʼ
EXCEPT
SELECT S2.sid
FROM Sailors S2, Boats B2, Reserves R2
WHERE S2.sid=R2.sid AND R2.bid=B2.bid AND B2.color=ʻgreenʼ;
Use MINUS instead of EXCEPT in Oracle
28
Nested Queries
• A nested query is a query that has another query
embedded within it; this embedded query is called the
subquery.
• Subqueries generally occur within the WHERE clause
(but can also appear within the FROM and HAVING
clauses)
• Nested queries are a very powerful feature of SQL. They
help us write short and efficient queries.
(Think of nested for loops in C++. Nested queries in SQL are similar)
29
Nested Query 1
Find names of sailors who have reserved boat 103
SELECT S.sname
FROM Sailors S
WHERE S.sid IN ( SELECT R.sid
FROM Reserves R
WHERE R.bid=103);
30
Nested Query 2
Find names of sailors who have not reserved boat 103
SELECT S.sname
FROM Sailors S
WHERE S.sid NOT IN ( SELECT R.sid
FROM Reserves R
WHERE R.bid=103 )
31
Nested Query 3
Find the names of sailors who have reserved a red boat
SELECT S.sname
FROM Sailors S
WHERE S.sid IN (SELECT R.sid
FROM Reserves R
WHERE R.bid IN (SELECT B.bid
FROM Boats B
WHERE B.color = ‘red’));
What about Find the names of sailors who have NOT reserved a red boat?
Revisit a previous query
Find names of sailors whoʼve reserved a red and a green boat
SELECT S.sid
FROM Sailors S, Boats B, Reserves R
WHERE S.sid=R.sid AND R.bid=B.bid
AND B.color=ʻredʼ
INTERSECT
SELECT S2.sid
FROM Sailors S2, Boats B2, Reserves R2
WHERE S2.sid=R2.sid AND R2.bid=B2.bid
AND B2.color=ʻgreenʼ;
32
SELECT S.sname
FROM Sailor S
WHERE S.sid IN (SELECT R.sid
FROM Boats B, Reserves R
WHERE R.bid=B.bid AND B.color=‘red’
INTERSECT
SELECT R2.sid
FROM Boats B2, Reserves R2
WHERE R2.bid=B2.bid AND B2.color=‘green’);
34
Revisit a previous query
Find names of sailors whoʼve reserved a red and a green boat
35
Correlated Nested Queries…1
• Thus far, we have seen nested queries where
the inner subquery is independent of the outer
query.
• We can make the inner subquery depend on
the outer query. This is called correlation.
36
Correlated Nested Queries…2
Find names of sailors who have reserved boat 103
SELECT S.sname
FROM Sailors S
WHERE EXISTS (SELECT *
FROM Reserves R
WHERE R.bid=103 AND R.sid=S.sid);
Tests whether the set
is nonempty. If it is,
then return TRUE.
(For finding sailors who have not reserved boat 103, we
would use NOT EXISTS)
38
ANY and ALL operators
Find sailors whose rating is better than some sailor named
Horatio
SELECT S.sid
FROM Sailors S
WHERE S.rating > ANY (SELECT S2.rating
FROM Sailors S2
WHERE S2.sname=ʻHoratioʼ);
(Can you find the probable bug in this SQL query??)
Hint: what if there are several sailors named Horatio?
39
Using ALL operator
Find sailors whose rating is better than every sailor named
Horatio
SELECT S.sid
FROM Sailors S
WHERE S.rating > ALL(SELECT S2.rating
FROM Sailors S2
WHERE S2.sname=ʻHoratioʼ);
40
Aggregate operators
• What is aggregation?
– Computing arithmetic expressions, such as
Minimum or Maximum
• The aggregate operators supported by SQL are:
COUNT, SUM, AVG, MIN, MAX
41
Aggregate Operators
• COUNT(A): The number of values in the column A
• SUM(A): The sum of all values in column A
• AVG(A): The average of all values in column A
• MAX(A): The maximum value in column A
• MIN(A): The minimum value in column A
(We can use DISTINCT with COUNT, SUM and AVG to compute
only over non-duplicated columns)
42
Using the COUNT operator
Count the number of sailors
SELECT COUNT (*)
FROM Sailors S;
43
Example of SUM operator
Find the sum of ages of all sailors with a rating of 10
SELECT SUM (S.age)
FROM Sailors S
WHERE S.rating=10;
44
Example of AVG operator
Find the average age of all sailors with rating 10
SELECT AVG (S.age)
FROM Sailors S
WHERE S.rating=10;
45
Example of MAX operator
Find the name and age of the oldest sailor
SELECT S.sname, MAX(S.age)
FROM Sailors S;
But this is illegal in SQL!!
46
Correct SQL Query for MAX
SELECT S.sname, S.age
FROM Sailors S
WHERE S.age = ( SELECT MAX(S2.age)
FROM Sailors S2 );
47
Another Aggregate Query
Count the number of different sailors
SELECT COUNT (DISTINCT S.sname)
FROM Sailors S
48
More to come…
• BETWEEN…AND
Advanced SQL concepts :
• GROUP BY
• ORDER BY
• HAVING

More Related Content

PPT
Introduction to SQL brief notes for academic.ppt
PPT
lecture05-14f.ppt
PDF
SQL Queries related to DDL and DML and DCL
PDF
dbmshkxjgzigyih you ucifu Yoyxoych5.pdf
PDF
dbmoyyohhhhhhhuhcyo Yxi hi uYes usch5.pdf
PPT
Database Management systems lecture notes
PDF
APznzab-krNx9xYwUY9_3k8Hh19mmThz2R8IODQ0Q7QpGzIRd4klcTiJbr1Xbm6ooppFjMsR6TZ6B...
PPT
asal12 sqliii
Introduction to SQL brief notes for academic.ppt
lecture05-14f.ppt
SQL Queries related to DDL and DML and DCL
dbmshkxjgzigyih you ucifu Yoyxoych5.pdf
dbmoyyohhhhhhhuhcyo Yxi hi uYes usch5.pdf
Database Management systems lecture notes
APznzab-krNx9xYwUY9_3k8Hh19mmThz2R8IODQ0Q7QpGzIRd4klcTiJbr1Xbm6ooppFjMsR6TZ6B...
asal12 sqliii

Similar to Every SQL Query must have: • SELECT clause: specifies columns to be retained in result • FROM clause: specifies a cross-product of tables The WHERE clause (optional) specifies selection conditions on the tables mentioned in the FROM clause (20)

PPTX
Lecture8-SQL-PartI-Jan30-2018 test Lecture8-SQL-PartI-Jan30-2018 test
PPTX
U-2.pptx igxitditdursruzyezrzmyayeTeYrsyrsurzursursursursursrusursruzruRuUeYe...
PDF
Ch4_Algebra.pdf
PPTX
Database managment System Relational Algebra
PDF
Sql ch 5
PPT
Ch7
PDF
Tech Jam 01 - Database Querying
PDF
03-advanced-sqdkdkdkdkdkddkkkkkl-annotated.pdf
PPTX
vnd.openxmlformats-officedocument.presentationml.presentation&rendition=1.pptx
PPT
04.SQL.ppt
PPT
Unit04 dbms
PPT
Rdbms (2)
PPT
Relational Algebra DBMS formal language used to query and manipulate relation...
PPT
sql-basic.ppt
PPT
Relational Algebra brief lecture notes for SQL.ppt
PPT
lecture-SQL_Working.ppt
PPTX
PPT
Algebra
PPT
Relational algebra in database management system
PPTX
The SQL Query Language: Simple SELECT Commands
Lecture8-SQL-PartI-Jan30-2018 test Lecture8-SQL-PartI-Jan30-2018 test
U-2.pptx igxitditdursruzyezrzmyayeTeYrsyrsurzursursursursursrusursruzruRuUeYe...
Ch4_Algebra.pdf
Database managment System Relational Algebra
Sql ch 5
Ch7
Tech Jam 01 - Database Querying
03-advanced-sqdkdkdkdkdkddkkkkkl-annotated.pdf
vnd.openxmlformats-officedocument.presentationml.presentation&rendition=1.pptx
04.SQL.ppt
Unit04 dbms
Rdbms (2)
Relational Algebra DBMS formal language used to query and manipulate relation...
sql-basic.ppt
Relational Algebra brief lecture notes for SQL.ppt
lecture-SQL_Working.ppt
Algebra
Relational algebra in database management system
The SQL Query Language: Simple SELECT Commands
Ad

More from 10300PEDDIKISHOR (7)

PPT
c-Functions power point presentation on c functions
PPT
c-step-by-step-execution power point presentation
PPT
Structures-in-C programming with examples
PPTX
file handling in c programming with file functions
PPT
Unity JDBC ICEIS ppt UnityJDBC ICEIS ppt
PPT
JDBC DriversPros and Cons of Each Driver
PPT
Java Database Connectivity Java Database
c-Functions power point presentation on c functions
c-step-by-step-execution power point presentation
Structures-in-C programming with examples
file handling in c programming with file functions
Unity JDBC ICEIS ppt UnityJDBC ICEIS ppt
JDBC DriversPros and Cons of Each Driver
Java Database Connectivity Java Database
Ad

Recently uploaded (20)

PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
Computing-Curriculum for Schools in Ghana
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
GDM (1) (1).pptx small presentation for students
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
Orientation - ARALprogram of Deped to the Parents.pptx
PDF
RMMM.pdf make it easy to upload and study
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
Cell Structure & Organelles in detailed.
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PPTX
Lesson notes of climatology university.
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Classroom Observation Tools for Teachers
PDF
Complications of Minimal Access Surgery at WLH
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Weekly quiz Compilation Jan -July 25.pdf
PPTX
Microbial diseases, their pathogenesis and prophylaxis
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Chinmaya Tiranga quiz Grand Finale.pdf
Computing-Curriculum for Schools in Ghana
Anesthesia in Laparoscopic Surgery in India
STATICS OF THE RIGID BODIES Hibbelers.pdf
GDM (1) (1).pptx small presentation for students
O5-L3 Freight Transport Ops (International) V1.pdf
Orientation - ARALprogram of Deped to the Parents.pptx
RMMM.pdf make it easy to upload and study
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Cell Structure & Organelles in detailed.
Module 4: Burden of Disease Tutorial Slides S2 2025
Lesson notes of climatology university.
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
Final Presentation General Medicine 03-08-2024.pptx
Classroom Observation Tools for Teachers
Complications of Minimal Access Surgery at WLH
O7-L3 Supply Chain Operations - ICLT Program
Weekly quiz Compilation Jan -July 25.pdf
Microbial diseases, their pathogenesis and prophylaxis

Every SQL Query must have: • SELECT clause: specifies columns to be retained in result • FROM clause: specifies a cross-product of tables The WHERE clause (optional) specifies selection conditions on the tables mentioned in the FROM clause

  • 2. 2 Basic form of SQL Queries • target-list A list of attributes of output relations in relation-list • relation-list A list of relation names (possibly with a range-variable after each name) e.g. Sailors S, Reserves R • qualification Comparisons (Attr op const or Attr1 op Attr2, where op is one of <, >, ≤, ≥, =, ≠) combined using AND, OR and NOT. SELECT target-list FROM relation-list WHERE qualification
  • 3. 3 Whatʼs contained in an SQL Query? Every SQL Query must have: • SELECT clause: specifies columns to be retained in result • FROM clause: specifies a cross-product of tables The WHERE clause (optional) specifies selection conditions on the tables mentioned in the FROM clause SELECT target-list FROM relation-list WHERE qualification
  • 4. 4 General SQL Conceptual Evaluation Strategy • Semantics of an SQL query defined in terms of the following conceptual evaluation strategy: – Compute the cross-product of relation-list. – Discard resulting tuples if they fail qualifications. – Delete attributes that are not in target-list. • This strategy is probably the least efficient way to compute a query! An optimizer will find more efficient strategies to compute the same answers.
  • 5. 5 Conceptual Evaluation Strategy Nested loops evaluation: Foreach tuple t1 in R1 … Foreach tuple tn in Rn 1. Substitute the attribute names in the qualification part with values from t1, …, tn 2. If the modified qualification part evaluates True then output target-attribute-values else do nothing end … end SELECT target-attribute-list FROM R1, …, Rn WHERE qualification
  • 6. 6 Table Definitions We will be using the following relations in our examples: Sailors(sid, sname, rating, age) Boats(bid, bname, color) Reserves(sid, bid, day)
  • 7. 7 sid sname rating age 22 Dustin 7 45.0 29 Brutus 1 33.0 31 Lubber 8 55.5 32 Andy 8 25.5 58 Rusty 10 35.0 64 Horatio 7 35.0 71 Zorba 10 16.0 74 Horatio 9 35.0 85 Art 3 25.5 95 Bob 3 63.5 sid bid day 22 101 10/10/04 22 102 10/10/04 22 103 10/08/04 22 104 10/07/04 31 102 11/10/04 31 103 11/06/04 31 104 11/12/04 64 101 09/05/04 64 102 09/08/04 74 103 09/08/04 bid bname Color 101 Interlake blue 102 Interlake red 103 Clipper green 104 Marine red Sailors Reserves Boats
  • 8. 8 A Simple SQL Query Find the names and ages of all sailors sid sname rating age 22 Dustin 7 45.0 29 Brutus 1 33.0 31 Lubber 8 55.5 32 Andy 8 25.5 58 Rusty 10 35.0 64 Horatio 7 35.0 71 Zorba 10 16.0 74 Horatio 9 35.0 85 Art 3 25.5 95 Bob 3 63.5
  • 9. 9 Result of Previous Query SELECT S.sname, S.age FROM Sailors S; Duplicate Results sname age Dustin 45.0 Brutus 33.0 Lubber 55.5 Andy 25.5 Rusty 35.0 Horatio 35.0 Zorba 16.0 Horatio 35.0 Art 25.5 Bob 63.5
  • 10. 10 Preventing Duplicate Tuples in the Result • Use the DISTINCT keyword in the SELECT clause: SELECT DISTINCT S.sname, S.age FROM Sailors S;
  • 11. 11 Results of Original Query without Duplicates Appears only once sname age Dustin 45.0 Brutus 33.0 Lubber 55.5 Andy 25.5 Rusty 35.0 Horatio 35.0 Zorba 16.0 Art 25.5 Bob 63.5
  • 12. 12 Example SQL Query…1 Find the names of sailors who have reserved boat 103 Relational Algebra: πsname ((σbid=103Reserves) Sailors) SQL: SELECT S.sname FROM Sailors S, Reserves R WHERE S.sid=R.sid AND R.bid=103;
  • 13. 13 Result of Previous Query sid bid day 22 103 10/08/04 31 103 11/06/04 74 103 09/08/04 sid sname rating age 22 Dustin 7 45.0 29 Brutus 1 33.0 31 Lubber 8 55.5 32 Andy 8 25.5 58 Rusty 10 35.0 64 Horatio 7 35.0 71 Zorba 10 16.0 74 Horatio 9 35.0 85 Art 3 25.5 95 Bob 3 63.5 sname Dustin Lubber Horatio Result:
  • 14. 14 A Note on Range Variables • Really needed only if the same relation appears twice in the FROM clause. The previous query can also be written as: SELECT S.sname FROM Sailors S, Reserves R WHERE S.sid=R.sid AND R.bid=103; OR SELECT sname FROM Sailors, Reserves WHERE Sailors.sid=Reserves.sid AND bid=103; However, it is a good style to always use range variables!
  • 15. 15 Example SQL Query…2 Find the sids of sailors who have reserved a red boat
  • 16. 16 Example SQL Query…3 Find the names of sailors who have reserved a red boat
  • 17. 17 Example SQL Query…4 Find the colors of boats reserved by ʻLubberʼ
  • 18. 18 Example SQL Query…5 Find the names of sailors who have reserved at least one boat
  • 19. 19 Expressions and Strings • AS and = are two ways to name fields in result. • LIKE is used for string matching. ʻ_ʼ stands for exactly one arbitrary character and ʻ%ʼ stands for 0 or more arbitrary characters.
  • 20. 20 Expressions and Strings Example Find triples (of ages of sailors and two fields defined by expressions, i.e. current age-1 and twice the current age) for sailors whose names begin and end with B and contain at least three characters. SELECT S.age, age1=S.age-1, 2*S.age AS age2 FROM Sailors S WHERE S.sname LIKE ʻB_%Bʼ; age age1 age2 63.5 62.5 127.0 63.5 3 Bob 95 25.5 3 Art 85 35.0 9 Horatio 74 16.0 10 Zorba 71 35.0 7 Horatio 64 35.0 10 Rusty 58 25.5 8 Andy 32 55.5 8 Lubber 31 33.0 1 Brutus 29 45.0 7 Dustin 22 age rating sname sid 63.5 3 Bob 95 25.5 3 Art 85 35.0 9 Horatio 74 16.0 10 Zorba 71 35.0 7 Horatio 64 35.0 10 Rusty 58 25.5 8 Andy 32 55.5 8 Lubber 31 33.0 1 Brutus 29 45.0 7 Dustin 22 age rating sname sid Result:
  • 21. 21 UNION, INTERSECT, EXCEPT • UNION: Can be used to compute the union of any two union-compatible sets of tuples (which are themselves the result of SQL queries). • EXCEPT: Can be used to compute the set- difference operation on two union-compatible sets of tuples (Note: In ORACLE, the command for set-difference is MINUS). • INTERSECT: Can be used to compute the intersection of any two union-compatible sets of tuples.
  • 22. 22 Illustration of UNION…1 Find the names of sailors who have reserved a red or a green boat Intuitively, we would write: SELECT S.sname FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND (B.color=ʻredʼ OR B.color=ʻgreenʼ);
  • 23. 23 Illustration of UNION…2 We can also do this using a UNION keyword: SELECT S.sname FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=ʻredʼ UNION SELECT S.sname FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=ʻgreenʼ; Unlike other operations, UNION eliminates duplicates! Same as INTERSECT, EXCEPT. To retain duplicates, use “UNION ALL”
  • 24. 24 Illustration of INTERSECT…1 Find names of sailors whoʼve reserved a red and a green boat Intuitively, we would write the SQL query as: SELECT S.sname FROM Sailors S, Boats B1, Reserves R1, Boats B2, Reserves R2 WHERE S.sid=R1.sid AND R1.bid=B1.bid AND S.sid=R2.sid AND R2.bid=B2.bid AND (B1.color=ʻredʼ AND B2.color=ʻgreenʼ);
  • 25. 25 Illustration of INTERSECT…2 We can also do this using a INTERSECT keyword: SELECT S.sname FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=ʻredʼ INTERSECT SELECT S2.sname FROM Sailors S2, Boats B2, Reserves R2 WHERE S2.sid=R2.sid AND R2.bid=B2.bid AND B2.color=ʻgreenʼ; (Is this correct??)
  • 26. 26 (Semi-)Correct SQL Query for the Previous Example SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=ʻredʼ INTERSECT SELECT S2.sid FROM Sailors S2, Boats B2, Reserves R2 WHERE S2.sid=R2.sid AND R2.bid=B2.bid AND B2.color=ʻgreenʼ; (This time we have actually extracted the sids of sailors, and not their names.) (But the query asks for the names of the sailors.)
  • 27. 27 Illustration of EXCEPT Find the sids of all sailors who have reserved red boats but not green boats: SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=ʻredʼ EXCEPT SELECT S2.sid FROM Sailors S2, Boats B2, Reserves R2 WHERE S2.sid=R2.sid AND R2.bid=B2.bid AND B2.color=ʻgreenʼ; Use MINUS instead of EXCEPT in Oracle
  • 28. 28 Nested Queries • A nested query is a query that has another query embedded within it; this embedded query is called the subquery. • Subqueries generally occur within the WHERE clause (but can also appear within the FROM and HAVING clauses) • Nested queries are a very powerful feature of SQL. They help us write short and efficient queries. (Think of nested for loops in C++. Nested queries in SQL are similar)
  • 29. 29 Nested Query 1 Find names of sailors who have reserved boat 103 SELECT S.sname FROM Sailors S WHERE S.sid IN ( SELECT R.sid FROM Reserves R WHERE R.bid=103);
  • 30. 30 Nested Query 2 Find names of sailors who have not reserved boat 103 SELECT S.sname FROM Sailors S WHERE S.sid NOT IN ( SELECT R.sid FROM Reserves R WHERE R.bid=103 )
  • 31. 31 Nested Query 3 Find the names of sailors who have reserved a red boat SELECT S.sname FROM Sailors S WHERE S.sid IN (SELECT R.sid FROM Reserves R WHERE R.bid IN (SELECT B.bid FROM Boats B WHERE B.color = ‘red’)); What about Find the names of sailors who have NOT reserved a red boat?
  • 32. Revisit a previous query Find names of sailors whoʼve reserved a red and a green boat SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=ʻredʼ INTERSECT SELECT S2.sid FROM Sailors S2, Boats B2, Reserves R2 WHERE S2.sid=R2.sid AND R2.bid=B2.bid AND B2.color=ʻgreenʼ; 32
  • 33. SELECT S.sname FROM Sailor S WHERE S.sid IN (SELECT R.sid FROM Boats B, Reserves R WHERE R.bid=B.bid AND B.color=‘red’ INTERSECT SELECT R2.sid FROM Boats B2, Reserves R2 WHERE R2.bid=B2.bid AND B2.color=‘green’); 34 Revisit a previous query Find names of sailors whoʼve reserved a red and a green boat
  • 34. 35 Correlated Nested Queries…1 • Thus far, we have seen nested queries where the inner subquery is independent of the outer query. • We can make the inner subquery depend on the outer query. This is called correlation.
  • 35. 36 Correlated Nested Queries…2 Find names of sailors who have reserved boat 103 SELECT S.sname FROM Sailors S WHERE EXISTS (SELECT * FROM Reserves R WHERE R.bid=103 AND R.sid=S.sid); Tests whether the set is nonempty. If it is, then return TRUE. (For finding sailors who have not reserved boat 103, we would use NOT EXISTS)
  • 36. 38 ANY and ALL operators Find sailors whose rating is better than some sailor named Horatio SELECT S.sid FROM Sailors S WHERE S.rating > ANY (SELECT S2.rating FROM Sailors S2 WHERE S2.sname=ʻHoratioʼ); (Can you find the probable bug in this SQL query??) Hint: what if there are several sailors named Horatio?
  • 37. 39 Using ALL operator Find sailors whose rating is better than every sailor named Horatio SELECT S.sid FROM Sailors S WHERE S.rating > ALL(SELECT S2.rating FROM Sailors S2 WHERE S2.sname=ʻHoratioʼ);
  • 38. 40 Aggregate operators • What is aggregation? – Computing arithmetic expressions, such as Minimum or Maximum • The aggregate operators supported by SQL are: COUNT, SUM, AVG, MIN, MAX
  • 39. 41 Aggregate Operators • COUNT(A): The number of values in the column A • SUM(A): The sum of all values in column A • AVG(A): The average of all values in column A • MAX(A): The maximum value in column A • MIN(A): The minimum value in column A (We can use DISTINCT with COUNT, SUM and AVG to compute only over non-duplicated columns)
  • 40. 42 Using the COUNT operator Count the number of sailors SELECT COUNT (*) FROM Sailors S;
  • 41. 43 Example of SUM operator Find the sum of ages of all sailors with a rating of 10 SELECT SUM (S.age) FROM Sailors S WHERE S.rating=10;
  • 42. 44 Example of AVG operator Find the average age of all sailors with rating 10 SELECT AVG (S.age) FROM Sailors S WHERE S.rating=10;
  • 43. 45 Example of MAX operator Find the name and age of the oldest sailor SELECT S.sname, MAX(S.age) FROM Sailors S; But this is illegal in SQL!!
  • 44. 46 Correct SQL Query for MAX SELECT S.sname, S.age FROM Sailors S WHERE S.age = ( SELECT MAX(S2.age) FROM Sailors S2 );
  • 45. 47 Another Aggregate Query Count the number of different sailors SELECT COUNT (DISTINCT S.sname) FROM Sailors S
  • 46. 48 More to come… • BETWEEN…AND Advanced SQL concepts : • GROUP BY • ORDER BY • HAVING