🎓 A1Learner
🔍
0 of 51 lessons completed

SQL CTEs

A CTE names a subquery result once at the start of a query. The main query then reads that named result as if it were a table.

The average price, named once

One number comes back: 20.1575, the average price of all eight products.

WITH avg_price AS (SELECT AVG(price) AS average_price FROM products)
SELECT average_price FROM avg_price;

Products above the average

Three products pass the filter: Headphones, Backpack and Desk Lamp.

WITH avg_price AS (SELECT AVG(price) AS average_price FROM products)
SELECT name, price FROM products
WHERE price > (SELECT average_price FROM avg_price)
ORDER BY price DESC;

Big orders, named once

Three orders come back, all with a quantity of three or more. Ana Silva holds two of them, orders 6 and 2.

WITH big_orders AS (SELECT order_id, customer_id, quantity FROM orders WHERE quantity >= 3)
SELECT c.name, b.order_id, b.quantity FROM big_orders b
JOIN customers c ON b.customer_id = c.customer_id
ORDER BY b.quantity DESC;

Same answer, subquery form

The same three rows come back. The CTE version gives the average a name, so the question reads more plainly.

SELECT name, price FROM products
WHERE price > (SELECT AVG(price) FROM products)
ORDER BY price DESC;

Example

WITH avg_price AS (SELECT AVG(price) AS average_price FROM products)
SELECT name, price, (SELECT average_price FROM avg_price) AS average_price FROM products
WHERE price > (SELECT average_price FROM avg_price)
ORDER BY price DESC;

Key points

  • CTE: a named result written once after WITH
  • WITH: the word that opens the named result
  • AS: the word that links the name to its query
  • The named result lives for one query only.
  • A CTE can hold one value, filtered rows, or a joined result.
  • A CTE and a subquery can answer the same question; the CTE names the middle step.

In this example, the CTE holds the average price of all eight products. The main query returns each product priced above that average, with 20.1575 shown beside each one. Three products pass: Headphones, Backpack and Desk Lamp.

Try it Yourself

Edit the code, then press Run.

Running is simulated · DB Fiddle

Exercise

What does WITH do at the start of a query?