SQL Nested Queries PDF
SQL Nested Queries PDF
Nested Queries
Stphane Bressan
Introduction to Database Systems
Nested Queries
Find the first name and last name of the customers who downloaded
a game.
SELECT c.first_name, c.last_name
FROM customer c, downloads d
WHERE c.customerid = d.userid;
Customers are repeated...It is better done with a nested query. outer query
SELECT c.first_name, c.last_name
FROM customer c
WHERE c.customerid = ANY inner query
(SELECT d.customerid
FROM downloads d);
There can be subqueries in the subqueries (some DBMS have a maximum level of
nesting and some stop optimizing after a certain level).
Introduction to Database Systems
ANY
Find the first name and last name of the different customers who
downloaded a game.
SELECT c.first_name, c.last_name
FROM customers c
WHERE c.customerid = ANY (
SELECT d.customerid
FROM downloads d);
The condition in the " WHERE " clause is true if the identifier is
equal to any of the results of the subquery.
" customerid " is a primary key of the "customer " table. The
query now considers the different customers.
Introduction to Database Systems
ANY
Find the first name and last name of the different customers who
downloaded a game.
SELECT c.first_name, c.last_name
FROM customers c
DONT DO THIS
WHERE c.customerid = (
SELECT d.customerid
FROM downloads d);
In most DBMS the query returns an error because there is more than
one result to the subquery.
It is recommended to always use "ANY", even in cases where the
result of the subquery has at most one row.
Introduction to Database Systems
IN
Find the first name and last name of the different customers who
downloaded a game.
EXISTS
Find the first name and last name of the different customers who downloaded a
game. maybe less efficient
but system may be smart enough to recognise this is the same as
the last slides one
The condition in the "WHERE" clause is true if the result of the subquery is not
empty. The outer query and the inner query are correlated. The condition of the
subquery uses "c.customerid" from the outer query. Think of the subquery as
a different query being evaluated for each row of the outer query. Attributes of a
query can be used at any level of nesting in its subqueries.
Not the other way round.
Introduction to Database Systems
SELECT c.customerid
FROM customers c
WHERE c.customerid NOT IN (SELECT d.customerid
FROM downloads d);
SELECT c.customerid
FROM customers c
WHERE NOT EXISTS(SELECT *
FROM downloads d
WHERE c.customerid = d.customerid);
Introduction to Database Systems
Credits
Copyright 2017 by Stphane Bressan
steph@nus.edu.sg