sql · level 3 · unit 1 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Chain CTEs with commas to build a .
One WITH can hold several steps. Write WITH once, then separate the steps with commas. Each step can read any step above it, so the query becomes a pipeline: every stage takes the last result and changes it a little.
Here, spend adds up each customer's orders. average works out the mean of those totals. The main query keeps the customers who beat it.
Build pipelines one step at a time. Write the first step, run SELECT * FROM it, check the rows, then add the next. Bugs have nowhere to hide.
WITH spend AS (
SELECT customer_id, SUM(total) AS spent
FROM orders
GROUP BY customer_id
),
average AS (
SELECT AVG(spent) AS avg_spent FROM spend
)
SELECT customer_id, spent
FROM spend
WHERE spent > (SELECT avg_spent FROM average)
ORDER BY spent DESC; The average here is 61, so only customers 2 and 3 make the cut.
guess first
A two-step pipeline. What comes out?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
WITH daily AS (
SELECT day, SUM(total) AS takings FROM orders GROUP BY day
),
busy AS (
SELECT day FROM daily WHERE takings > 40
)
SELECT COUNT(*) AS busy_days FROM busy;
your turn
Your turn. Add the middle step.
Make big read from spend and keep the customers who spent at least an amount you choose (try 50). The main query turns their ids into names.
result
Your answer appears here as a table.
fix it
Two WITHs and a syntax error. Fix the pipeline!
result
Your answer appears here as a table.
- The error points at the second
WITH. How many times does a pipeline sayWITH? - Write
WITHonce at the top. Every step after the first is separated by a comma. - Delete the second WITH and put a comma after the bracket on line 5, then press run.
nailed it
your queries read like a recipe now. :D
- Write
WITHonce, then separate steps with commas. - Each step can read any step above it.
- Build a pipeline one step at a time, checking as you go.
new words in your collection
- pipeline
This lesson isn’t saved. A free account remembers every lesson you finish.