Back to Chapters
Chapter Progress: 0 %0 / 6 Lessons Read
‹›

4. Data engineering patterns

4.2 CTEs: build a query in named steps

Highlights & notes

Select lesson text to highlight it, or tap Add note.

    Bookmarks

    Bookmark a lesson to see it here.

      A CTE (common table expression) is a named, temporary result that you write at the top of a query with WITH. The main query below can then use it like a table.

      • WITH spend AS ( ... ) → step 1, saved under the name spend
      • SELECT ... FROM spend → step 2 uses it
      • Add more steps with a comma: WITH a AS (...), b AS (...)

      Data pipelines are written this way: one clear step per CTE, read from top to bottom. It is far easier to test and review than queries nested inside queries.

      Think of it like variables in Python

      spend = orders[...].groupby(...).sum()
      result = spend.merge(customers)

      Each CTE is one named intermediate table.

      Must Know:

      A CTE exists only while its query runs. It is not saved in the database. To check a step, run SELECT * FROM step_name as the main query.

      How it fits together

      1. WITH spend AS (...)
      2. spend: a named result
      3. Main SELECT reads spend

      Watch the query run

      SQL

      WITH spend AS (  SELECT customer_id, SUM(amount) AS total  FROM orders  WHERE status = 'delivered'  GROUP BY customer_id)SELECT c.name, s.totalFROM spend AS sJOIN customers AS c ON c.id = s.customer_idORDER BY s.total DESC;

      Rows at this step

      name | total
      -----+------
      Asha | 68000
      Ravi | 52700

      Practice in SQL

      In a CTE called counts, count the orders of each customer_id. Then show the name and orders of customers with 2 or more orders. Sort by name.

      Tables you can query: customers, orders
      customers
      id | name  | city
      ---+-------+------
      1  | Asha  | Noida
      2  | Ravi  | Delhi
      3  | Meera | Pune
      4  | Kabir | Noida
      5  | Zoya  | NULL
      
      orders
      id  | customer_id | product  | amount | status    | order_date
      ----+-------------+----------+--------+-----------+-----------
      101 | 1           | Laptop   | 55000  | delivered | 2026-01-05
      102 | 2           | Mouse    | 700    | delivered | 2026-01-06
      103 | 1           | Keyboard | 1500   | delivered | 2026-01-09
      104 | 3           | Monitor  | 12000  | cancelled | 2026-01-12
      105 | 2           | Laptop   | 52000  | delivered | 2026-01-15
      106 | 4           | Mouse    | 650    | pending   | 2026-01-18
      107 | 1           | Monitor  | 11500  | delivered | 2026-01-20
      108 | 3           | Keyboard | NULL   | pending   | 2026-01-22
      Expected output
      name  | orders
      ------+-------
      Asha  | 3
      Meera | 2
      Ravi  | 2

      Reference solution
      WITH counts AS (
        SELECT customer_id, COUNT(*) AS orders
        FROM orders
        GROUP BY customer_id
      )
      SELECT c.name, n.orders
      FROM counts AS n
      JOIN customers AS c ON c.id = n.customer_id
      WHERE n.orders >= 2
      ORDER BY c.name;

      Question 1 · Easy

      Which keyword starts a CTE?

      Question 2 · Medium

      How long does a CTE exist?

      Question 3 · Hard

      Why do data engineers prefer CTEs to queries nested inside queries?

      Key takeaways

      WITH name AS (query) saves a step under a name for the rest of the query. Build pipelines as a chain of small, named steps.

      Lesson 20 of 24

      Save your progress

      Start free and your progress, code and notes stay saved. Free for 1 month, no card needed.

      Start free Log in
      PreviousCTEs: build a query in named steps
      Save your progress free for 1 month. Start free · Log in