SQL & Databases·Composing queries

Subqueries and CTEs

Build a query from smaller, named results instead of one tangled statement.

Beginner 14 min read Lesson 11 of 480 Challenge included
What you will be able to do
  • 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.

cte.sqlSQL
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;
  1. 01
    Find the inner result

    Write the query that produces the numbers you need to compare.

  2. 02
    Name it

    Move it into a WITH clause with a short, descriptive name.

  3. 03
    Use it

    Select from the CTE as if it were a table.

  4. 04
    Keep it readable

    Chain a second CTE when the next step has its own meaning.

Your turn

Above-average course totals

Hard

Use a CTE to total minutes per course, then return only courses above the average total.

SQL · starter
WITH totals AS (
  SELECT course_slug, SUM(minutes) AS minutes
  FROM lessons
  GROUP BY course_slug
)
Check your understanding before moving on.
Knowledge checkQuestion 1

Which clause names a reusable temporary result set?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Window functions
Lesson 11 of 480 · 0% of course