Professional Documents
Culture Documents
advanced SELECT
Table of Contents
6 advanced SELECT
236 Chapter 6
advanced SELECT
How would you reorganize the current columns into new categories? Are
there any films that might fit into more than one of the new categories?
advanced SELECT
movie_table
title rating drama comedy action gore scifi for_kids cartoon category
Big Adventure G F F F F F T F
Mad Clowns R F F F T F F F
Paraskavedekatriaphobia R T T T F T F F
Take it Back R F T F F F F F
Shark Bait G F F F F F T F
Angry Pirate PG F T F F F F T
Does the order in which we evaluate each of the T/F columns matter?
sharpen solution
movie_table
title rating drama comedy action gore scifi for_kids cartoon category
240 Chapter 6
advanced SELECT
7KDWVHHPVILQHIRUDVPDOOWDEOHEXW
ZKDWLI\RXKDGKXQGUHGVRIFROXPQV",VWKHUH
VRPHZD\ZHFRXOGFRPELQHDOOWKRVH83'$7(
VWDWHPHQWVLQWRRQHELJRQH"
Paraskavedekatriaphobia R T T T F T F F drama
242 Chapter 6
advanced SELECT
As each movie title’s T/F values are run through the CASE statement,
the RDBMS is looking for the first 'T' to set the category for each film.
Here’s what happens when 'Big Adventure' runs through the code:
UPDATE movie_table
SET category = FALSE: no category yet
CASE
WHEN drama = 'T' THEN 'drama' FALSE: no category yet
WHEN comedy = 'T' THEN 'comedy' FALSE: no category yet
WHEN action = 'T' THEN 'action' FALSE: no category yet
WHEN gore = 'T' THEN 'horror' FALSE: no category yet
WHEN scifi = 'T' THEN 'scifi'
FALSE: no category yet
WHEN for_kids = 'T' THEN 'family'
WHEN cartoon = 'T' THEN 'family'
ELSE 'misc' TRUE: category set to ‘family’,
and we skip to the END and
END; exit the code.
Let’s do one with multiple matches. Again, we’re looking for the first 'T' value
here to set the category.
Here’s what happens when 'Paraskavedekatriaphobia' runs through the code:
UPDATE movie_table
SET category =
CASE TRUE: category set to drama;
we skip to the END and exit
WHEN drama = 'T' THEN 'drama' the code. All our other T
WHEN comedy = 'T' THEN 'comedy' values are ignored.
WHEN action = 'T' THEN 'action'
WHEN gore = 'T' THEN 'horror'
WHEN scifi = 'T' THEN 'scifi'
WHEN for_kids = 'T' THEN 'family'
WHEN cartoon = 'T' THEN 'family'
ELSE 'misc'
END;
in CASE of problems
MESSAGE
Today Time 13.41
Date
To The Boss
Please call
Telephoned
Will call again
Called to see you
Returned your call
Wants to see you
that
MESSAGE Some lady called to complain
her little kid Nathan ended up
of profanity,
watching a cartoon with a lot
ound his sister
and now he keeps chasing ar
and calling her a %#!@
Me URGENT
Taken By
244 Chapter 6
advanced SELECT
Change the CASE expression so that cartoons get put in the 'misc'
category, not 'family'.
Change the CASE expression to test for the conditions that set a
cartoon to 'misc' instead of 'family'.
UPDATE movie_table
SET category =
CASE
WHEN drama = ‘T' THEN ‘drama'
WHEN comedy = ‘T' THEN ‘comedy'
WHEN action = ‘T' THEN ‘action'
WHEN gore = ‘T' THEN ‘horror'
WHEN scifi = ‘T' THEN ‘scifi'
WHEN for_kids = ‘T' THEN ‘family'
WHEN cartoon = ‘T' AND rating = 'G' THEN ‘family'
ELSE 'misc'
END; Your condition can have multiple parts: add an
WHEN to test for whether the film is a cartoAND to your
rated ‘G’. If it is, then it gets a category of on AND it’s
‘family’.
Q: Do I have to use the ELSE? Q: What if I want to only use the CASE expression on some
A:
columns but not others? For example, if I wanted to do a
It’s optional. You can simply leave that line out if you don’t CASE where my category = 'misc'. Can I use a WHERE?
need it, but it’s nice to have to update the value of your column
when nothing else fits. It’s better to have some sort of value than
NULL, for example.
A: Yes, you can add a WHERE clause after the END keyword.
The CASE will only apply to those columns that match the WHERE.
Q: What happens if I leave off the ELSE but none of the Q: Can I use a CASE expression with anything other than
WHEN conditions match? UPDATE statements?
A: No values will be changed in the column you are updating. A: Yes. You can use a CASE expression with SELECT, INSERT,
DELETE, and, as you’ve seen, UPDATE.
246 Chapter 6
advanced SELECT
Staff
To: Dataville Video
CASE Construction From : Th e Bo ss
w categories!
ctions mean ne
Subject: New se
Your boss, always a bit wishy-washy, has decided to change
things up a bit. Read his email and write a single SQL
family,
statement that will accomplish what he wants. My happy video
ctions. I’m
ate some new se
I’ve decided to cre s sh ou ld be shelved
ed movie
thinking that R-rat d PG . Let’s just
on than G an
in a different secti :
teg ori es
create 5 new ca
horror-r
action-r
drama-r
comedy-r
scifi-r
vies in the misc
any G-rated mo
And if there are
to Family.
section, move ’em
gre at,
Thanks. That’ll be
Yo ur bo ss
Staff
To: Dataville Video
CASE Construction SOLUTION e Bo ss
Fr om : Th w categories!
ctions mean ne
Subject: New se
Your boss, always a bit wishy-washy, has decided to change
things up a bit. Read his email and write a single SQL family,
statement that will accomplish what he wants. My happy video
ctions. I’m
ate some new se
I’ve decided to cre vie s sh ou ld be shelved
ed mo
UPDATE movietable thinking that R-rat G an d PG . Let’s just
on than
SET category = in a different secti
tegories:
create 5 new ca
CASE horror-r
WHEN drama = ‘T’ AND rating = ‘R’ THEN ‘drama-r’ action-r
WHEN comedy = ‘T’ AND rating = ‘R’ THEN ‘comedy-r’ drama-r
WHEN action = ‘T’ AND rating = ‘R’ THEN ‘action-r’ comedy-r
scifi-r
WHEN gore = ‘T’ AND rating = ‘R’ THEN ‘horror-r’
vies in the misc
WHEN scifi = ‘T’ AND rating = ‘R’ THEN ‘scifi-r’ any rated mo
G-
And if there are mi ly.
to Fa
WHEN category = ‘misc’ AND rating = ‘G’ THEN ‘family’ section, move ’em
END; ll be gre at,
Thanks. That’
Your boss
UPDATE movietable
SET category =
CASE
WHEN category = ‘drama-r’ THEN ‘drama’
WHEN category = ‘comedy-r’ THEN ‘comedy’
WHEN category = ‘action-r’ THEN ‘action’
WHEN category = ‘horror-r’ THEN ‘horror’
WHEN category = ‘scifi-r’ THEN ‘scifi’
END;
Finally, delete all those T/F columns we don’t need anymore.
248 Chapter 6
advanced SELECT
movie_table
SELECT overload
SELECT title, category FROM movie_table WHERE title LIKE 'A%' AND category = 'family';
SELECT title, category FROM movie_table WHERE title LIKE 'B%' AND category = 'family';
SELECT title, category FROM movie_table WHERE title LIKE 'C%' AND category = 'family';
SELECT title, category FROM movie_table WHERE title LIKE 'D%' AND category = 'family';
SELECT title, category FROM movie_table WHERE title LIKE 'E%' AND category = 'family';
SELECT title, category FROM movie_table WHERE title LIKE 'F%' AND category = 'family';
SELECT title, category FROM movie_table WHERE title LIKE 'G%' AND category = 'family';
250 Chapter 6
advanced SELECT
SELECT title, category FROM movie_table WHERE title LIKE 'A%’ AND category = 'family';
title category
Airplanes and Helicopters family
Are You Paying Attention? family
Acting Up family
Are You My Mother? family
Andy Sighs family
After the Clowns Leave family
Art for Kids family
Animal Adventure family
Animal Crackerz family
Another March of the Penguins family
Anyone Can Grow Up family
Aaargh! family
Aardvarks Gone Wild family
Alaska: Land of Salmon family
Angels family
Ann Eats Worms family
Awesome Adventure family
Annoying Adults family
Alex Needs a Bath family
Aaargh! 2 family
sharpen solution
SELECT title, category FROM movie_table WHERE title LIKE 'A%' AND category = 'family';
title category
Aaargh! family
Aaargh! 2 family
Anyone Can Grow Up family The titles starting ‘Are You…’ come
Are You My Mother? family towards the end of the order since the
family
letter following the initial ‘A’ is an ‘r’,
Are You Paying Attention? but then we had to look at the seventh
Art for Kids family letter into the title before we could work
Awesome Adventure family out where each movie should be shelved.
252 Chapter 6
advanced SELECT
6HULRXVO\$UH\RXWHOOLQJPHWKLV
LVWKHRQO\ZD\ZHFDQDOSKDEHWL]HRXU
UHVXOWV"7KHUH·V12:$<,·PGRLQJWKDW
IRUHYHU\OHWWHURIWKHDOSKDEHW
ORDER BY keyword
FROM movie_table
Airplanes and Helicopters family
Alaska: Land of Salmon family
advanced SELECT
0123ABCDabcd!@ #$%^&*()-_
+ = []{} ;: '"\|`~,.<>/?
Rules of Order
SQL’s Rules of Order SQL’s’ve run your ORDER BY
you
When you’ve run your ORDER BY query, Wheny, put these characters in the
q u e r
fill in the blanks using the order the charac ey appear in the results.
ters order th
appear in your results to help you.
exercise solution
Rules of Order
SQL’s Rules of Order SQL’s’ve run your ORDER BY
you
When you’ve run your ORDER BY query, Wheny, put these characters in the
quer they appear in the results.
fill in the blanks using the order the charac order
appear in your results to help you. ters
!"&'(*+=?@~
characters.
256 Chapter 6
advanced SELECT
Hey,
of the movies
to get rid of some
I think we need st tim e. Can you come
lon ge
we’ve had for the of movies in
and give me a list
in this weekend of pu rch ase date?
order
each category by
at,
That would be gre
Your boss
Titles
4-19-2003 starting with
Z Purchased dates
oldest first
11-20-1999
258 Chapter 6
advanced SELECT
,GRQ·WOLNHROGPRYLHV:KDWLI,ZDQWWR
VHHWKHPRYLHVQHZHVWILUVW"'R,MXVW
KDYHWRUHDGWKHOLVWIURPWKHERWWRP"
Q: I thought that DESC was used to get the DESCRIPTION of Q: Can I use the whole words DESCRIBE and DESCENDING
a table. Are you sure this works to change the ORDER? in my query to avoid confusion?
A: — Yes. It’s all about context. When you use it in front of a table
name for example, DESC movie_table;—you’ll get a
A: You can use DESCRIBE, but DESCENDING won’t work.
260 Chapter 6
advanced SELECT
ideo Staff
To: Dataville V
oss
From: The B
ies all round!
Subject: Freeb
Hey,
kin g g re a t! Y o u ’ve got all those
The store is loo ri g h t p la c e s, and, thanks
in th e
movies stacked B Y clauses in your
c y O R D E R
to those fan d e x a c tly what they’re
y c a n fin
SQL, everybod
looking for.
, I’m
y o u fo r a ll o f your hard work
To rewa rd
a p a rt y a t m y h ouse tonight.
pizz
throwing a little
.
Show up at 6ish
!
n’t fo rg e t to b ri ng those reports
Do
Your boss
r a n y th in g to o nice, I’ve got
P.S. Don’t we a
o k sh e lv e s I’ v e been itching to
these b o
reorganize…
262 Chapter 6
advanced SELECT
The Girl Sprout with the largest total amount sold will win free horseback
riding lessons. All of the Girl Sprouts want to win, so it’s crucial that Edwina
figure out the correct winner before things get ugly.
Use your new ORDER BY skills to write a query that will help Edwina find
the name of the winner.
sharpen solution
The Girl Sprout with the largest total amount sold will win free horseback
riding lessons. All of the Girl Sprouts want to win, so it’s crucial that Edwina
figure out the correct winner before things get ugly.
Use your new ORDER BY skills to write a query that will help Edwina find
the name of the winner.
264 Chapter 6
advanced SELECT
266 Chapter 6
advanced SELECT
ÚjklWfYe] sales
ÚjklWfYe] sales
Britney 3.40
Nicole 19.22 ÚjklWfYe] sales
ÚjklWfYe] sales Britney 2.58
Nicole 0.00 Lindsay 17.62
Paris 26.53 Britney 4.50
Nicole 8.05 Lindsay 9.16
Paris 0.00 Britney 11.25
Nicole 26.82 Lindsay 0.00
Paris 0.56 Britney 8.78
Nicole 7.77 Lindsay 32.02
Paris 1.52 Britney 43.21
Nicole 15.21 Lindsay 2.34
Paris 13.44 Britney 34.19
Nicole 18.96 Lindsay 3.71
Paris 24.19 Lindsay 16.23
Paris 31.99
first_name sales
Nicole 26.82
Surprise, Britney Britney 43.21
had the highest Lindsay 32.02
single day sales. Paris 31.99
first_name sales
Nicole 0.00
And while it looks like the Britney 2.58
other girls slacked off at Lindsay 0.00
least one day each, even Paris 0.00
on Britney’s worst day
she made money.
7KLVLVJHWWLQJVHULRXV0D\EH,FDQJLYH
WKHSUL]HWRWKHJLUOZKRVROGFRRNLHVRQ
PRUHGD\VWKDQDQ\RIWKHRWKHUV
268 Chapter 6
advanced SELECT
cookie_sales
ID ÚjklWfYe] sales sale_date Here’s the original table. What do you think will be
returned by the query?
1 Lindsay 32.02 3-6-2007
2 Paris 26.53 3-6-2007
3 Britney 11.25 3-6-2007
4 Nicole 18.96 3-6-2007
5 Lindsay 9.16 3-7-2007
6 Paris 1.52 3-7-2007
7 Britney 43.21 3-7-2007
8 Nicole 8.05 3-7-2007
9 Lindsay 17.62 3-8-2007 Does this number represent the actual number of
10 Paris 24.19 3-8-2007 days cookies were sold?
11 Britney 3.40 3-8-2007
12 Nicole 15.21 3-8-2007
13 Lindsay 0 3-9-2007
14 Paris 31.99 3-9-2007
15 Britney 2.58 3-9-2007
16 Nicole 0 3-9-2007
17 Lindsay 2.34 3-10-2007 Write a query that will give us the number of days
18 Paris 13.44 3-10-2007 that each girl sold cookies.
19 Britney 8.78 3-10-2007
20 Nicole 26.82 3-10-2007
21 Lindsay 3.71 3-11-2007
22 Paris .56 3-11-2007
23 Britney 34.19 3-11-2007
24 Nicole 7.77 3-11-2007
25 Lindsay 16.23 3-12-2007
26 Paris 0 3-12-2007
27 Britney 4.50 3-12-2007
28 Nicole 19.22 3-12-2007
sharpen solution
28 sales dates
<RXFRXOGMXVWGRDQ25'(5%<RQ
WKHVDOHBGDWHDQGORRNDWWKHILUVW
DQGODVWGDWHVWRILJXUHRXWKRZPDQ\
GD\VFRRNLHVZHUHVROG5LJKW"
270 Chapter 6
advanced SELECT
;-4-+<,1;<16+<^IT]M [
First let’s look at that keyword DISTINCT Since DISTINCT is a keyword and
without the COUNT function. not a function, you don’t need
parentheses around sale_date.
SELECT DISTINCT sale_date
FROM cookie_sales
Here’s our ORDER BY so we can
ORDER BY sale_date; see the first and last sales dates.
File Edit Window Help NoDupes
Now let’s try it with the COUNT function: Notice that the DISTINCT goes inside
the parentheses with sale_date.
SELECT COUNT(DISTINCT sale_date)
FROM cookie_sales;
We don’t need an ORDER BY because
COUNT will be returning a single
number. Nothing to ORDER here. Try out this query, and then use it to
figure out which girl sold cookies on
the most days?
Answer: Britney
who am i?
Who a
A bunch of SQL functions and keywords, in full costume, are
m I?
playing a party game, “Who am I?” They’ll give you a clue—you
try to guess who they are based on what they say. Assume they
always tell the truth about themselves. Fill in the blanks to the
right to identify the attendees. Also, for each attendee, write
down whether it’s a function or keyword.
Tonight’s attendees:
COUNT, DISTINCT, AVG, MIN, GROUP BY, SUM, MAX
function or
Name keyword
The result you get from using me might not be worth much.
272 Chapter 6
advanced SELECT
Q: Since you were looking for the highest values Q: Doing the query for MIN() didn’t really have
with AVG, MAX, and MIN, couldn’t you have added an anything to do with Edwina finding a winner, did it?
A:
ORDER BY clause?
Q:
up the queries and make it easier for you to learn the
new functions. Take a look back over those functions and Speaking of MIN, what happens if there’s a NULL
visualize the ORDER BY there. See how it would change in the column?
the results?
+PP$9*0$;DQG&2817UHDOO\
GLGQ·WZRUNRXWDVDZD\WRGHWHUPLQHWKH
VHFRQGSODFHZLQQHU,ZRQGHULI,FDQ
XVH680WRZRUNRXWZKLFKJLUOFDPHLQ
VHFRQGSODFHDQGJLYHKHUDSUL]H
6(/(&7¿UVWBQDPH680VDOHV
FROM cookie_sales
*5283%<¿UVWBQDPH
ORDER BY SUM(sales)DESC
LIMIT 2; a long query and gets you It’s
This is saying that you want these two little results.
to LIMIT your results to
the first two.
first_name sales
Britney 107.91
Paris 98.23
While there are only four Girl Sprouts in the table and limiting it to two doesn’t
help a huge amount here, imagine that you were working with a much larger table.
Suppose you had a list of the top 1,000 current songs playing at radio stations, but
you wanted the top 100 in order of popularity. LIMIT would allow you to see only
those and not the other 900 songs.
274 Chapter 6
advanced SELECT
Write the query that will get us the second result and only the
second result using the LIMIT clause with two parameters.
sharpen solution
Write the query that will get us the second result and only the
second result using the LIMIT clause with two parameters.
0\64/VWDWHPHQWVDUHJHWWLQJVRORQJDQG
FRPSOLFDWHGQRZZLWKDOOWKRVHQHZNH\ZRUGV
,OLNHWKHPWKH\·UHJUHDWEXWLVQ·WWKHUHD
ZD\,FDQVLPSOLI\WKLQJV"
276 Chapter 6
advanced SELECT
SELECTcross
It’s time to give your right brain a break and
put that left brain to work: all the words are
SQL-related and from this chapter.
2 3
5 6
8 9
10
11
Across Down
2. You can find the smallest value in a column with this function. 1. Lets you specify exactly how many rows to return, and which
5. This function returns each unique value only once, with no row to start with.
duplicates. 3. If you ORDER BY a column using this keyword, the value 9 in
7. The _____ keyword in the CASE allows you to tell your that column will come before 8.
2$//* *%")4-!*- . *)5/(!!//$!*) %/%*). 4. Use these two words to alphabetically order your results
8. You can find the largest value in a column with this function. based on a column you specify.
11. Use these two words to consolidate rows based on a 6. This function adds up a column of numeric values.
common column. 9. If you ORDER BY a column using this keyword, the value 8 in
that column will come before 9.
10. Use this in a SELECT to return the number of results rather
than the results themselves.
sql in review
Y
ORDER B lts
be tic al ly or ders your resu
Alpha lumn you spec
ify. COUNT
ba se d on a co
Can tell you how many ro
Y ws match
GROUP B a a SELECT query wit
on ho ut
Consolidates n.
row s ba se d having to see the rows. you
common colum returns a single integer COUNT
value.
DISTINCT
AVG
Returns each unique value only
once, with no duplicates Returns the
numeric columaverage value in a
n.
MAX and
MIN
SUM
Return the la
Adds up a column of numeric column with M rgest value in a
values. with MIN. AX, and the smallest
LIMIT
Lets you specify exactly
many rows to return, an how
row to start with. d which
278 Chapter 6
advanced SELECT
Who a
A bunch of SQL functions and keywords, in full costume, are
m I?
playing a party game, “Who am I?” They’ll give you a clue—you
try to guess who they are based on what they say. Assume they
always tell the truth about themselves. Fill in the blanks to the
right to identify the attendees. Also, for each attendee, write
down whether it’s a function or keyword. from p
. 272
Tonight’s attendees:
COUNT, DISTINCT, AVG, MIN, GROUP BY, SUM, MAX
function or
Name keyword
The result you get from using me might not be worth much. MIN function
What I spit out is larger than anything I take in. SUM function
crossword solution
SELECTcross Solution
1
L
2 3
M I N D
4
O M E
R I S
5 6
D I S T I N C T
7
E L S E U
8 9
R M A X
10
S B S
11
G R O U P B Y C
M
280 Chapter 6