Building up with WITH
Name intermediate results with WITH so a long query reads top to bottom, and use a subquery where a single number will do.
What runs in CodeSplash
- Linear mixed model (random intercepts and slopes) Verified in Python and R
You will be able to
- Break a query into named steps with WITH
- Use a scalar subquery in a WHERE clause
- Compare each row with its group's summary
Read first
Name your steps
ReadA long query is easier to read as a series of named steps. A WITH clause, or common table expression (CTECommon table expressionA named subquery written at the start of a query with WITH, so a long query can be read in steps.), names a result so the next step can use it.
WITH species_mean AS (
SELECT species, avg(body_mass) AS mean_mass
FROM palmer_penguins_sample
GROUP BY species
)
SELECT *
FROM species_mean
ORDER BY mean_mass DESC;
Read from the top: first compute each species' mean, then show it. A CTE exists only for this query and changes nothing in the warehouse.
Heavy compared with what?
PredictPredict first
Which comparison puts more Chinstrap penguins above average: the overall mean, or their own species' mean?
Reveal
Their own species' mean: 31 Chinstraps beat it. Against the overall mean of about 4,200 grams, far fewer do, since Gentoos pull that mean up. "Above average" means nothing until you say which average.
Compare a row with its group
In the appRun this. It joins each penguin to its species' mean and counts those above it.
WITH species_mean AS (
SELECT species, avg(body_mass) AS mean_mass
FROM palmer_penguins_sample
GROUP BY species
)
SELECT p.species, count(*) AS above_own_mean
FROM palmer_penguins_sample AS p
JOIN species_mean AS s ON p.species = s.species
WHERE p.body_mass > s.mean_mass
GROUP BY p.species
ORDER BY p.species;
Add a step: another WITH entry after a comma can read the one before it. Try computing, per species, the share above its own mean.
A subquery for one number
ExploreWhen you need a single value, a subquery in parentheses is shorter than a CTE.
SELECT count(*) AS above_overall_mean
FROM palmer_penguins_sample
WHERE body_mass > (SELECT avg(body_mass) FROM palmer_penguins_sample);
Run it. The inner query runs first, and its one number becomes part of the condition.
If you find yourself nesting subqueries inside subqueries, switch to WITH. It runs the same way and reads from top to bottom.
Write your own comparison
In the appNow write one from a task. The starter already has the WITH part. It opens in a new SQL tab, and Check compares your result with the answer's.
SQL exercise · penguins
Join a row to its group's summary
For Adelie penguins, show each penguin's body mass and how far it is above its island's Adelie mean. Leave out unknown masses. Call the columns island, body_mass and above_mean.
WITH island_mean AS (
SELECT island, avg(body_mass) AS mean_mass
FROM {{table}}
WHERE species = 'Adelie'
GROUP BY island
)
SELECT *
FROM island_mean;Hints
- Join the table to the WITH clause on island.
- The join alone keeps every species on those islands, so filter to Adelie in the outer query too.
Show a solution
WITH island_mean AS (
SELECT island, avg(body_mass) AS mean_mass
FROM {{table}}
WHERE species = 'Adelie'
GROUP BY island
)
SELECT p.island, p.body_mass, p.body_mass - m.mean_mass AS above_mean
FROM {{table}} AS p
JOIN island_mean AS m ON p.island = m.island
WHERE p.species = 'Adelie' AND p.body_mass IS NOT NULL;In the app this opens in a real SQL tab on the sample table and checks your result.
Check your understanding
CheckpointCheck yourself
Using the per-species query, how many penguins in total are above their own species' mean?
Show the answer
Answer: 159
.
Check yourself
How many penguins are above the overall mean?
Show the answer
Answer: 149
Most of them are Gentoos, which is why 149 and 159 tell such different stories.
Check yourself
You define a CTE named species_mean. What's in your warehouse afterwards?
Show the answer
Answer: a
To keep a result, use Save as dataset, or save the query as a SQL model.
Groups within groups
ReflectYou've compared each bird with its species. That idea has a formal version: models that separate variation within groups from variation between them. Where in your data do rows belong to groups (customers, sites, patients) that you're ignoring?
Recap
RecapWITHnames intermediate results, so a query reads as steps.- Use a subquery in parentheses when you need one value.
- Compare a row with its group by joining the group's summary back on.
Concepts in this lesson