AI Hints
Home›PostgreSQL Tutorial›ROLLUP and CTEs
PostgreSQL · Lesson 29 of 120

CTEs

Named steps.

⏱ 2 min read▶ Video at 24:46🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Long queries get hard to read. A common table expression, or CTE, names a step with with, so you can build the answer one piece at a time.

  • Long queries
  • Name each step
  • WITH

Big spenders

The first step, spend, totals each customer's spending. The main query then picks customers who spent over two hundred, using spend like a table. Run it. Our top customers, in a query that reads like a story.

query.sqlsql
WITH spend AS (
  SELECT o.customer_id, sum(i.quantity * b.price) AS total
  FROM orders o
  JOIN order_items i USING (order_id)
  JOIN books b USING (book_id)
  GROUP BY o.customer_id
)
SELECT c.first_name, c.last_name, s.total
FROM spend s JOIN customers c USING (customer_id)
WHERE s.total > 200
ORDER BY s.total DESC
LIMIT 4;
Output
 first_name | last_name | total
------------+-----------+--------
 Yara       | Ali       | 445.27
 Farah      | Novak     | 415.25
 Rosa       | Khan      | 408.79
 Jack       | Lopez     | 390.30
(4 rows)

CTE tips

You can chain many CTEs, each using the ones before. Postgres usually inlines them, so they're as fast as subqueries. Materialized forces a CTE to run once. And CTEs can even insert, update or delete.

keyvalue
ChainWITH a AS, b AS
Speedinlined
MATERIALIZEDrun once
WritesINSERT/UPDATE in CTEs

Summary

CTEs name steps with with, so complex queries read top to bottom. Next, recursive CTEs for trees.

Key takeaways
  • WITH
  • Named steps
  • Readable
Next up: Recursive CTEs — walk a tree