Subqueries and CTEs
Build a query from smaller, named results instead of one tangled statement.
- Filter with a subquery
- Name results with WITH
- Compare groups against an average
A subquery is a query inside another query. A common table expression (CTE) names that intermediate result with WITH, which makes complex logic readable.
SELECT course_slug, COUNT(*) AS lessons
FROM lessons
GROUP BY course_slug
HAVING COUNT(*) > (
SELECT AVG(lesson_count)
FROM (
SELECT COUNT(*) AS lesson_count
FROM lessons
GROUP BY course_slug
)
);
WITH totals AS (
SELECT course_slug, SUM(minutes) AS minutes
FROM lessons
GROUP BY course_slug
)
SELECT course_slug, minutes
FROM totals
WHERE minutes > 30
ORDER BY minutes DESC;- 01Find the inner result
Write the query that produces the numbers you need to compare.
- 02Name it
Move it into a WITH clause with a short, descriptive name.
- 03Use it
Select from the CTE as if it were a table.
- 04Keep it readable
Chain a second CTE when the next step has its own meaning.
Above-average course totals
Use a CTE to total minutes per course, then return only courses above the average total.
WITH totals AS (
SELECT course_slug, SUM(minutes) AS minutes
FROM lessons
GROUP BY course_slug
)Which clause names a reusable temporary result set?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.