SQL Intermediate Lesson 1: Common Table Expressions (WITH)

SQL Intermediate Lesson 1: Common Table Expressions (WITH) 1

📎 This article includes 2 downloadable practice files ↓

⏱ 2 min read

📘 SQL Intermediate Course · Lesson 1 of 10

Advertisement
In this article
  1. Chain several CTEs
  2. Common mistakes
  3. Practice

Long queries with subqueries inside subqueries are hard to read and harder to fix. A Common Table Expression gives a subquery a name at the top, and the main query reads like a story.

WITH sales AS (
  SELECT c.region, o.qty * p.price AS amount
  FROM orders o
  JOIN customers c USING (customer_id)
  JOIN products  p USING (product_id)
  WHERE o.status <> 'Cancelled'
)
SELECT region, ROUND(SUM(amount), 2) AS total
FROM sales
GROUP BY region
ORDER BY total DESC;

Chain several CTEs

Separate them with commas; each can use the ones before it:

WITH sales AS (...),
     per   AS (SELECT customer, SUM(amount) AS total FROM sales GROUP BY customer)
SELECT customer, total
FROM per
WHERE total > (SELECT AVG(total) FROM per);

That is “customers above the average customer”, which needs the per-customer totals twice. Without a CTE you’d repeat the whole grouping query.

💡 Build CTEs one step at a time. Run WITH sales AS (...) SELECT * FROM sales LIMIT 10 first, check it, then add the next step.

Common mistakes

  • A comma before the main SELECT after the last CTE gives a syntax error.
  • Expecting a CTE to be stored: it lives only for that one query. For reuse, create a VIEW.
  • Integer division in shares: in SQLite and SQL Server, 5/2 = 2. Multiply by 100.0 first.

Practice

Download shop2.db and this lesson’s exercise file below. Open the database in DB Browser for SQLite (free), paste each task into the Execute SQL tab and compare with the expected result printed under it. Answers are at the bottom of the file.

📎 Practice files for this article

⬇ Download all 2 files (ZIP · 9 KB)

  • 📄
    Practice database (SQLite)shop2.db: customers, products, 300 orders, payments, employees with managers and monthly targets.
    ⬇ DB · 48 KB
  • 🗃️
    Lesson 1 exercisesTasks with the real expected result under each, and answers at the bottom.
    ⬇ SQL · 3 KB

Free to use for learning. Files with macros (.bas) are plain text — import them with Alt+F11 → File → Import File, and always test on a copy.

Advertisement
✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free · AI can be wrong