Beruflich Dokumente
Kultur Dokumente
subqueries
Table of Contents
Chapter 9. subqueries.................................................................................. 1
Section 9.1. Greg gets into the job recruiting business................................................................................................................... 2
Section 9.2. Greg's list gets more tables......................................................................................................................................... 3
Section 9.3. Greg uses an inner join............................................................................................................................................... 4
Section 9.4. But he wants to try some other queries...................................................................................................................... 6
Section 9.5. Subqueries................................................................................................................................................................... 8
Section 9.6. We combine the two into a query with a subquery.................................................................................................... 9
Section 9.7. A subquery construction walkthrough...................................................................................................................... 16
Section 9.8. A subquery as a SELECT column.............................................................................................................................. 19
Section 9.9. Another example: Subquery with a natural join...................................................................................................... 20
Section 9.10. A noncorrelated subquery....................................................................................................................................... 21
Section 9.11. A noncorrelated subquery with multiple values: IN, NOT IN................................................................................ 25
Section 9.12. Correlated subqueries............................................................................................................................................. 30
Section 9.13. A (useful) correlated subquery with NOT EXISTS................................................................................................. 31
Section 9.14. EXISTS and NOT EXISTS....................................................................................................................................... 32
Section 9.15. Greg's Recruiting Service is open for business....................................................................................................... 34
Section 9.16. On the way to the party........................................................................................................................................... 35
Section 9.17. Your SQL Toolbox.................................................................................................................................................... 36
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 1 Return to Table of Contents
9 subqueries
Yes, Jack, I’d like a two-part question, please. Joins are great,
but sometimes you need to ask your database more than one question. Or take
the result of one query and use it as the input to another query. That’s where
subqueries come in. They’ll help you avoid duplicate data, make your queries
more dynamic, and even get you in to all those high-end concert afterparties.
(Well, not really, but two out of three ain’t bad!)
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 2 Return to Table of Contents
380 Chapter 9
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 3 Return to Table of Contents
subqueries
available description
years_exp
contact_interest interests
contact_id interest_id
interest
my_contacts
contact_id interest_id
profession
OLD TABLES
last_name
prof_id
first_name
profession
phone
contact_seeking seeking
zip_code email
contact_id seeking_id
gender
zip_code seeking
birthday
city
prof_id seeking_id
state
zip_code
status
status_id
status_id
status Since the two new tables each have a one-to-one
relationship with my_contacts, he’s been able to
use natural joins so far with great success and ease.
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 4 Return to Table of Contents
Wanted: Web
Developer
Looking for
Web Develope
rate HTML & r with firs
CSS chops to t
interaction work with ou
and visual r
This is a tr design team
emendous op s.
for someone portunity
who’s meticu
web standard lous about
s to shine
highly-visib with a
le company.
amazingly in Work with an
fluential co
by smart pe mpany operat
ople who lo ed
ve what they
Salary: $95, do .
000-$105,000
Experience:
5+ years
Once he finds the best few matches, he can call them up and
screen them further. But first, he wants to pull out all the
Web Developers with at least five years of experience and
who don’t require a salary higher than 105,000.
382 Chapter 9
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 5 Return to Table of Contents
subqueries
Write the query to get the qualified candidates from the database.
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 6 Return to Table of Contents
Write the query to get the qualified candidates from the database.
t
We only need to get the contacy’re
information since we know the
SELECT mc.last_name, mc.first_name, mc.phone seeking Web Developer jobs.
FROM my_contacts AS mc
Since both my_contacts and job_desired
NATURAL JOIN share contact_id as a primary key, we can
simply use a natural join to connect them.
job_desired AS jd
WHERE jd.title = 'Web Developer'
AND jd.salary_low < 105000;
We’re only interested in people who will consider the salary.
We look at the salary_low figure to see if the salary
offered is more than the least they’ll accept.
384 Chapter 9
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 7 Return to Table of Contents
subqueries
Remember the IN keyword? It returns a row if Results from the first query
jc.title is in the group of titles in parentheses.
It works!
mc.first_name mc.last_name mc.phone jc.title
Joe Lonnigan (555) 555-3214 Cook
Wendy Hillerman (555) 555-8976 Waiter
Sean Miller (555) 555-4443 Web Designer
Jared Callaway (555) 555-5674 Web Developer
Juan Garza (555) 555-0098 Web Developer
Try combining the two queries into a single query. Write that single query here.
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 8 Return to Table of Contents
Subqueries
To accomplish what those two queries do with just one query, we need to add a
subquery into the query.
We’ll call the second query we used to get the matches from the professions
table the OUTER query because it will wrap up inside of itself the INNER query.
Let’s see how it works:
OUTER query
WHERE
All those professions in parentheses above came from the first query
we did, the one to select all the titles from the job_current table. A subquery is a query
So—and this is the clever bit, so watch carefully—we can replace
that part of the outer query with part of our first query.
that is wrapped
This will still produce all the results in parentheses above, but this
query now gets encapsulated as the subquery:
within another query.
It’s also called an
INNER query INNER query.
386 Chapter 9
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 9 Return to Table of Contents
subqueries
And these are the results we get when we run our query,
precisely the same results as when we spelled out all the
job titles in the WHERE clause, but with a lot less typing.
Same results as before,
but with just one query!
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 10 Return to Table of Contents
Anatomy of a query
within a query
Outer query
Inner query
388 Chapter 9
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 11 Return to Table of Contents
subqueries
A subquery in action
Let’s see a comparable query in action from the my_contacts table.
First your RDBMS takes the scalar value from the zip_code table,
then it compares that value to the columns in the WHERE clause.
value
Q: Why can’t I just do this as a join? You can do the same query above this way:
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 12 Return to Table of Contents
fireside chat
390 Chapter 9
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 13 Return to Table of Contents
subqueries
Subquery rules
There are some rules that all subqueries follow. Fill in the blanks using
the words below (you might need some of them more than once).
SEMICOLON
SELECT END
COLUMN LIST
PARENTHESES
DELETE
UPDATE INSERT
Rules of Order
SQL’s Rules of Order SQL’s
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 14 Return to Table of Contents
exercise solution
Subquery rules
Keep these rules in mind as you look at the subqueries in the rest of the chapter.
Rules of Order
SQL’s Rules of Order SQL’s
Q: So what is the inner query allowed to return? How about Q: I’m still not clear on whether a subquery can return a
the outer query? single value or more than one value. What are the official rules?
A: In most cases, the inner query can only return a single value—
that is, one column with one row. The outer query can then take that
A: In general, a subquery must return a single value. IN is the
exception. Most of the time subqueries need to return a single value
value and use it to compare against all the values in a column. to work.
Q: Why do you say “a single value” when the example on Q: So what happens if your subquery does return more than
page 388 returns the entire column full of values? one value but isn’t using a WHERE clause that contains a set of
392 Chapter 9
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 15 Return to Table of Contents
subqueries
<HDKWKHVHUXOHVDUHFRRORUZKDWHYHUEXWZKDW,ZDQWWR
NQRZLVKRZ,FDQJHWULGRIWKRVHORQJQDPHVLQP\UHVXOW
FROXPQVOLNHPFODVWBQDPH'R\RXKDYHDUXOHIRUWKDW"
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 16 Return to Table of Contents
:KRPDNHVWKHPRVWPRQH\
RXWRIDOOP\FRQWDFWV"
394 Chapter 9
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 17 Return to Table of Contents
subqueries
now our
And here’s the first part whichryis value. The
subquery to find the MAX sala nst the outer ,W·V0LNH",VKRXOGKDYHNQRZQ
value from this is compared agairesults. +HQHYHUSLFNVXSWKHFKHFN
part of the query to get the
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 18 Return to Table of Contents
,WUHDOO\VHHPVOLNHZHFRXOGKDYH
GRQHWKDWZLWKRXWWKHVXETXHU\
Write another query to figure out who makes the most money
out of all Greg’s contacts.
,GRQ·WFDUHLIWKHUHDUH
PXOWLSOHZD\VRIGRLQJWKHVDPH
WKLQJ,ZDQWWRNQRZWKHEHVW
ZD\2UDWOHDVWVRPHUHDVRQWR
FKRRVHRQHZD\RYHUDQRWKHU
Good point.
Why don’t you check out the SQL
Exposed interview on page 400?
396 Chapter 9
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 19 Return to Table of Contents
subqueries
If a subquery is
*RWKURXJKDOOWKHURZVLQWKHP\BFRQWDFWVWDEOH)RUHDFKRQH
SXOORXWWKHILUVWQDPHODVWQDPHDQGVWDWHZKHUHZHILQG used as a column
WKHVWDWHE\WDNLQJWKH]LSFRGHDQGPDWFKLQJLWXSZLWKWKH
FRUUHFWVWDWHLQWKH]LSFRGHWDEOH expression in a
Remember that the subquery may only return one single value,
SELECT statement,
so each time it runs, a row is returned. Here’s what some of the
results of this query might look like:
it can only return one
value from one column.
mc.first_name mc.last_name state
Joe Lonnigan TX
Wendy Hillerman CA
Sean Miller NY
Jared Callaway NJ
Juan Garza CA
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 20 Return to Table of Contents
SELECT jc.salary
FROM my_contacts mc NATURAL JOIN job_current jc This query will return Andy’s
WHERE email = 'andy@weatherorama.com'; salary, a single value.
Greg notices that this query will only return a single result. Instead
of running it and getting that value and plopping it into another
This will be the query, he decides to turn it into a subquery.
inner query. He writes a single query that:
• gets Andy’s salary and This will use the >
• compares it to other salaries comparison operator.
• and returns the first and last names of people with their salaries
FROM
398 Chapter 9
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 21 Return to Table of Contents
subqueries
A noncorrelated subquery
Get the first name, last
When we put the pieces together, here’s the name and salary.
entire query. First the software processes the
inner query once, then it uses that value to
SELECT mc.first_name, mc.last_name, jc.salary
figure out the outer query result.
FROM
The RDBMS processes
this part first. my_contacts AS mc NATURAL JOIN job_current AS jc
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 22 Return to Table of Contents
SQL Exposed
This week’s interview:
Choosing the best way to query when
you have more than one choice
Head First SQL: Welcome, SQL. We appreciate Head First SQL: So it’s about how long you take
the personal interview. We know things have been to respond? That’s how we pick how to ask you?
difficult.
SQL: Well, duh. Of course it is. It’s all about what
SQL: Difficult? That’s what you call it? I’d say you ask me. I’m just here to try to answer your
things have been troubling, disturbing, and really questions, when they’re accurate.
hard to quantify while at the same time being very
Head First SQL: Speed? That’s the secret?
convoluted.
SQL: Look, I’ll clue you in. The thing about
Head First SQL: Uh, right. That’s kind of the
databases is that they GROW. You want your
point here. You’re getting complaints that maybe
questions to be as easy to answer as possible. Because
you’re too flexible. You give us too many choices
if you ask me “Whodunnit” I need you to make
when we ask you questions.
me think about it as little as possible. Give me easy
SQL: I admit that I’m flexible. That you can ask me questions, and I’ll give you quick answers.
the same question in a number of ways and I’ll give
Head First SQL: I get it. But how do we know
you the same answers.
what the easy questions are?
Head First SQL: Some people would say that
SQL: Well, for starters, cross joins are a huge waste
you’re wishy-washy.
of time. And correlated subqueries are on the slow
SQL: I refuse to get defensive about this. I’m not the side too.
bad guy here.
Head First SQL: Anything else?
Head First SQL: No, we know you aren’t, it’s just
SQL: Well…
that you’re so…imprecise.
Head First SQL: Please, go ahead.
SQL: HA! Me imprecise! I’ve had about enough of
this. (standing) SQL: Experiment. Sometimes your best bet is to
create test tables and try different queries. Then you
Head First SQL: No, don’t go. We just want a
can compare how long each one took. Oh, and joins
few answers. Sometimes you let us ask you the same
are more efficient than subqueries.
thing in so many different ways.
Head First SQL: Thanks, SQL. Can’t believe
SQL: And what’s wrong with that?
that’s the big secret…
Head First SQL: Nothing really, we just want
SQL: Yeah. Thanks for wasting my time.
to know WHAT we should be asking you. Does it
matter, if you give us the same answer?
SQL: Of course it matters! Sometimes you ask
me something, and it takes me a very long time to
answer you. Sometimes, BANG, I’m done. The
whole point is that you ask me the right way.
400 Chapter 9
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 23 Return to Table of Contents
subqueries
BUILD-A-SUBQUERY WORKSHOP
Read through each of the scenarios below. Follow the instructions to write the two queries as
requested, then combine them into a subquery.
1. Greg wants to see what the average salary is for a Web Developer in his job_current table.
Then he wants to look at what people are actually making as compared to the average salary
for that job. If he finds people earning less, he can use that to target them because they may be
more interested in getting a new job.
Write a query to get the average salary of a Web Developer from the job_current table.
2. Greg needs to get the first name, last name, and salary of all web developers in his
job_current table.
Write a query to get the first name, last name, and salary of all Web Developers in the
job_current table.
3. Greg uses the average salary (and a little math) as a subquery to show each Web Developer
and how much under or over the average salary they make.
Combine the two queries. Use the subquery as part of the SELECT column list.
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 24 Return to Table of Contents
workshop solution
1. Greg wants to see what the average salary is for a Web Developer in his job_current table.
Then he wants to look at what people are actually making as compared to the average salary
for that job. If he finds people earning less, he can use that to target them because they may be
more interested in getting a new job.
Write a query to get the average salary of a Web Developer from the job_current table.
2. Greg needs to get the first name, last name, and salary of all web developers in his
job_current table.
Write a query to get the first name, last name, and salary of all Web Developers in the
job_current table.
3. Greg uses the average salary (and a little math) as a subquery to show each Web Developer
and how much under or over the average salary they make.
Combine the two queries. Use the subquery as part of the SELECT column list.
Here’s our subquery.
SELECT mc.first_name, mc.last_name, jc.salary,
jc.salary — (SELECT AVG(salary) FROM job_current WHERE title = ‘Web Developer')
FROM my_contacts mc NATURAL JOIN job_current jc
WHERE jc.title = ‘Web Developer';
402 Chapter 9
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 25 Return to Table of Contents
subqueries
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 26 Return to Table of Contents
subquery exercise
Write queries with joins and noncorrelated subqueries when necessary to answer
the questions below. Use the gregs_list database schema to help you.
Several of these need the aggregate functions you
learned with the Girl Sprout cookie sales problem.
List titles for jobs that earn salaries equal to the highest salary in the job_listings table.
List the first and last name of people with a salary greater than the average salary.
Find all web designers who have the same zip code as any job_listings for web designers.
List everyone who lives in the same zip code as the person with the highest current salary.
404 Chapter 9
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 27 Return to Table of Contents
subqueries
contact_interest
contact_id
my_contacts interests
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 28 Return to Table of Contents
exercise solution
Write queries with joins and noncorrelated subqueries when necessary to answer
the questions below. Use the gregs_list database schema to help you.
List titles for jobs that earn salaries equal to the highest salary in the job_listings table.
List the first and last name of people with a salary greater than the average salary.
406 Chapter 9
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 29 Return to Table of Contents
subqueries
Find all web designers who have the same zip code as any job_listings for web designers.
List everyone who lives in the same zip code as the person with the highest current salary.
This is a trick question, because there could be more than one person with the highest salary.
That means we’ll need to use an IN. We also need to use two subqueries.
The outer query takes the zip codes and finds matches
in the my_contacts table. Because the middle subquery
could return more than one zip code, we use an IN. The middle subquery finds
zip codes of people who
earn the maximum salary.
SELECT last_name, first_name FROM my_contacts
WHERE zip_code IN (SELECT mc.zip_code FROM my_contacts mc
NATURAL JOIN job_current jc
WHERE jc.salary = (SELECT MAX(salary) FROM job_current));
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 30 Return to Table of Contents
correlated subqueries
Correlated subqueries
,IDQRQFRUUHODWHGVXETXHU\PHDQV
WKHVXETXHU\VWDQGVDORQHWKHQ,EHWD
FRUUHODWHGVXETXHU\LVVRPHKRZGHSHQGHQWRQ
WKHRXWHUTXHU\
408 Chapter 9
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 31 Return to Table of Contents
subqueries
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 32 Return to Table of Contents
410 Chapter 9
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 33 Return to Table of Contents
subqueries
Write a query that returns the email of people who have at least
one interest but don’t exist in the job_current table.
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 34 Return to Table of Contents
subquery success!
Q: So can you put a subquery inside a subquery? Q: If I don’t like using subqueries, is there a way I can use
A:
joins instead?
Definitely. There’s a limit on how many nested subqueries you
can use, but most RDBMS systems support far more than you’d ever
easily be able to use.
A: Most of the time, yes. You need to learn a few more joins first,
though. Which leads us to...
A: Your best bet is to write little queries for the various parts of the
question. Then look at them and see how you need to combine them.
If you’re trying to find people who earn the same amount of money
as the highest paid web designer, break it apart into:
412 Chapter 9
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 35 Return to Table of Contents
subqueries
THE WEEKLY
INQUERYER
The SHOCKING T
Subqueries REVERUTH about
ALED!
JOINS IN HIDING
Neighbors say subqueries can
’t do “anything more” tha
“the truth needs to com n joins, and
e out at last.”
By Troy Armstrong
INQUERYER STAFF WR
ITER
DATAVILLE – What has
only been speculation for
now been verified by Inq many years has
ueryer sources. Joins and
used to make exactly the subqueries can be
same queries. Much to the
residents, anything you confusion of local
can do with a subquery,
type of join. you can do with some
“It’s terrible,” sobbed sch
oolteacher Heidi Musgro
the children that what the ve. “How can I tell
y thought they knew abo
those hours spent learnin ut subqueries, all
g how to use them, well,
used joins. It’s heartbreak they could have just
ing.”
The fallout from this rev
elation can be expected Local resident Heidi
the next chapter, when out to continue well into Musgrove was
er joins are exposed to pub shocked to learn the
truth about
lic scrutiny. subqueries.
WAS IT ALL A WASTE OF TIME? ARE SUBQUERIES REALLY THE SAME AS JOINS?
TURN TO THE NEXT CHAPTER TO FIND OUT.
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 36 Return to Table of Contents
sql in review
Inner quer
y
A query inside anot
also known as a su her query. It’s
bquery.
Noncorrelated subquery
414 Chapter 9
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 37 Return to Table of Contents
subqueries
Subquerycross
You can tell your inner query from your outer query,
but can you solve this crossword? All of the solution
words are from this chapter.
2 3
Across Down
1. A subquery is always a single _____ statement. 1. A query inside of another query is known as a _____.
4. The _____ query contains the inner query, or subquery. 2. Subqueries are always inside _____.
&%'#'$*%& %! !% +&$$ *& 3. A _____ subquery means that the inner query relies on the
from the outer query, it is a _____ subquery. outer query before it can be resolved.
7. In a _____ subquery, the inner query, or subquery, gets 5. The _____ query is called the subquery.
interpreted by the RDBMS, followed by the outer query.
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.
Chapter 9. subqueries Page 38 Return to Table of Contents
Write a query that returns the email of people who have at least
one interest but don’t exist in the job_current table.
From page 411.
Subquerycross Solution
1
S E L E C T
U
B
2 3
Q P C
4
O U T E R A O
5
I E R R
6
N O N C O R R E L A T E D R
N Y N E
E T L
R H A
7
N O N C O R R E L A T E D
S E
E D
S
416 Chapter 9
Chapter 9. subqueries
Head First SQL By Lynn Beighley ISBN: 9780596526849 Publisher: O'Reilly Prepared for Gareth Morris, Safari ID: northwind001@gmail.com
Print Publication Date: 2007/08/15 User number: 810998 Copyright 2007, Safari Books Online, LLC.
This PDF is exclusively for your use in accordance with the Safari Terms of Service. No part of it may be reproduced or transmitted in any form by any means without the prior
written permission for reprints and excerpts from the publisher. Redistribution or other use that violates the fair use priviledge under U.S. copyright laws (see 17 USC107) or that
otherwise violates the Safari Terms of Service is strictly prohibited.