Here's a preview from my zine, Become a SELECT Star!! If you want to see more comics like this, sign up for my saturday comics newsletter or browse more comics!
read the transcript!
person: every user has a different email right?
1 query later… person, now sad: oh no
This query uses HAVING
to find all emails that are shared by more than one user:
SELECT email, COUNT(*)
FROM users
GROUP BY email
HAVING COUNT(*) > 1
users:
id 1, email asdf@fake.com
id 2, email bob@builder.com
id 3, email asdf@fake.com
query output:
email asdf@fake.com, COUNT
(*) 2
HAVING
is like WHERE
, but with 1 difference: HAVING
filters rows AFTER grouping and WHERE
filters rows BEFORE grouping.
Because of this, you can use aggregates (like COUNT
(*)) in a HAVING
clause but not with WHERE
.
Here’s another HAVING
example that finds months with more than $6.00 in income:
SELECT month
FROM sales
GROUP BY month
HAVING SUM(price) > 6
sales:
month: Jan. item: catnip price: 5
month: Feb item: laser price: 8
month: March item: food price: 4
month: March item: food price: 3
query output:
month: Feb
month: March
Saturday Morning Comics!
Want another comic like this in your email every Saturday? Sign up here!