Lesson 8 of 12
Structured learning draftBreak an analysis into named query stages
Make a paid-sales summary easier to inspect by giving its filtered records a name. Use a common table expression to separate row selection from customer aggregation, then check each stage before extending the query.
Learning objectives
- Name an intermediate query.
- Separate filtering from summarising.
- Inspect a stage without assuming materialisation.
Break an analysis into named query stages: the working sequence
Trace the three stages of break an analysis into named query stages and compare them with the example.
The sales fixture supplies the original records.
The paid CTE exposes only paid rows and the fields required next.
The final SELECT aggregates that stage by customer.
A CTE introduced with WITH names a query for use in the current statement. It is a readability tool, not a promise that a permanent table or a particular execution plan will be created.
WITH sales(id, customer, amount, status) AS (
VALUES (1, 'Amina', 120, 'paid'),
(2, 'Amina', 80, 'pending'),
(3, 'Brian', 50, 'paid'),
(4, 'Chen', NULL, 'paid')
), paid AS (
SELECT customer, amount FROM sales WHERE status = 'paid'
)
SELECT customer, SUM(amount) AS known_paid_total
FROM paid
GROUP BY customer
ORDER BY customer;customer | known_paid_total
Amina | 120
Brian | 50
Chen | NULLTry it, then change it
- Replace the final SELECT with SELECT * FROM paid and inspect its three rows.
- Restore the summary and explain Chen's NULL result.
- Rename the CTE to paid_sales consistently and confirm the result is unchanged.
Common mistakes
- Treating a CTE name as a persistent database table.
- Assuming WITH guarantees faster execution.
- Changing several stages at once without comparing intermediate outputs.
Practice activity
Apply the lesson
Add a named stage for known paid amounts. Compare the population and total with the original paid stage, and explain which record disappears. Keep the changed example, its output and a short explanation of whether the result matched your prediction.
How to check your work
- Write down the expected result before running or submitting your work.
- Try a normal example, an empty or missing input, and a boundary case where the rule changes.
- Compare the actual result with your prediction. Record the smallest example that explains a difference.
- Explain one change you made and why it improved the result. Save your evidence in the lesson notes.
When you get stuck · databases
A join returns more rows than expected.
- Find the cause
- Count matching records for each join key in both tables. A key repeated on both sides creates multiple combinations.
- Try this
- Decide the intended row grain first: one row per customer, order or item. Aggregate at that grain or correct the join condition; do not hide the problem with DISTINCT.
- Check the fix
- Use two customers and three orders as a fixture. Predict every result row and check unmatched records separately.
Use this course-wide example when it fits your task. For a different failure, record the input, expected result, actual result and smallest steps that reproduce it.
Watch, pause, practise
Free video lessons
Choose the chapter that matches your task. Videos open on the original provider’s site; playback uses additional data.
CS50: databases with SQL
Watch Querying or Relating to see selection and joins explained using actual tables. Examples begin with SQLite; check syntax when using PostgreSQL.
Try it yourself: Draw two small tables, predict the joined rows, then compare your prediction with the query result.
Source checked 2026-10-07 · Free learning material; optional certificates may cost extra.Check your understanding
What does the paid CTE name in this example?
Lesson summary
- Named stages can make a query easier to explain.
- A CTE belongs to its statement.
- Inspect intermediate rows before trusting the final summary.
Sources and further reading
- WITH queriesPostgreSQL Global Development Group - accessed 2026-10-07
- PostgreSQL SQL language guidePostgreSQL Global Development Group - accessed 2026-10-07
Personal study note
Your notes
Keep the input, expected result, actual result and what you changed. Save before leaving this lesson. Download a copy to keep it outside this browser.