TECHNOLOGIESTieInn Technologies

CTEs with WITH

SQL · 14 questions

Short notes

Key idea

A CTE (WITH ... AS) names a subquery and puts it at the top, so the query reads in steps, top to bottom. Each step can use the ones before it.

Syntax

WITH step1 AS (
  SELECT ...
),
step2 AS (
  SELECT ... FROM step1
)
SELECT * FROM step2;

One WITH, steps separated by commas, then the final SELECT.

Example

Customers whose spending is above the average customer's:

WITH spend AS (
  SELECT customer_id, SUM(amount) AS total
  FROM orders
  GROUP BY customer_id
)
SELECT customer_id, total
FROM spend
WHERE total > (SELECT AVG(total) FROM spend);

The same CTE is used twice, which a plain subquery couldn't do without repeating itself.

Traps

  • Only one WITH. Write WITH a AS (...), b AS (...), not a second WITH.
  • No comma before the final SELECT.
  • A CTE lives only for its one query. It isn't a saved table.
  • Check each step by running SELECT * FROM step1 on its own while you build.

Want the full lesson with step-by-step examples, a project and a certificate? SQL course, ₹120 →

Questions

Open in Code Lab5 free questions
5 questions

    CTEs with WITH

  1. Question 1easy

    Which is the correct way to define two CTEs?

  2. CTEs with WITH

  3. Question 2medium

    You define a CTE called recent_orders in one query. Can a second, separate query use it?

  4. CTEs with WITH

  5. Question 3medium

    What does this return?

    WITH per_customer AS (
      SELECT customer_id, COUNT(*) AS n
      FROM orders
      GROUP BY customer_id
    ),
    loyal AS (
      SELECT * FROM per_customer WHERE n >= 3
    )
    SELECT COUNT(*) FROM loyal;
  6. CTEs with WITH

  7. Question 4medium

    What does this return?

    WITH per_customer AS (
      SELECT customer_id, COUNT(*) AS n
      FROM orders
      GROUP BY customer_id
    )
    SELECT MAX(n) FROM per_customer;
  8. CTEs with WITH

  9. Question 5hard

    No orders were placed in October 2024. What is orders for October in this result?

    WITH RECURSIVE months AS (
      SELECT DATE '2024-09-01' AS month
      UNION ALL
      SELECT month + INTERVAL 1 MONTH FROM months WHERE month < DATE '2024-11-01'
    ),
    counts AS (
      SELECT date_trunc('month', order_date) AS month, COUNT(*) AS orders
      FROM orders GROUP BY month
    )
    SELECT COALESCE(c.orders, 0) AS orders
    FROM months m LEFT JOIN counts c ON c.month = m.month
    WHERE m.month = DATE '2024-10-01';

9 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.