⚡0 XP🔥0

Subqueries and CTEs (WITH)

Lesson 5 of 8 ⏱ 4 min read ✎ 3 exercises ❓ 5-question quiz ▶ Runs SQL

Break complex questions into steps - scalar subqueries, IN / NOT IN and EXISTS subqueries, subqueries in FROM (derived tables), and Common Table Expressions with WITH for readable multi-step analysis.

Subqueries#

A subquery is a query inside another query, written in brackets. It lets you use the result of one question to answer another.

हिंदी में समझें

Subquery = एक query के अंदर दूसरी query। अंदर वाली query पहले चलती है, और उसका जवाब बाहर वाली query इस्तेमाल करती है।

उदाहरण: "औसत से महंगे products" - पहले औसत निकालो (अंदर की query), फिर उससे तुलना करो (बाहर की query)।

1. Scalar subquery - returns one value#

▶ Try it Yourselfdatabase: shopSQL
Ctrl + Enter to run

2. IN subquery - returns a list#

▶ Try it Yourselfdatabase: shopSQL
Ctrl + Enter to run

3. EXISTS / NOT EXISTS#

EXISTS checks whether the subquery returns any row - often clearer and safer than NOT IN:

▶ Try it Yourselfdatabase: shopSQL
Ctrl + Enter to run
Common Mistake

NOT IN (subquery) returns no rows at all if the subquery contains a single NULL. Use NOT EXISTS or LEFT JOIN ... IS NULL when NULLs are possible.

4. Subquery in FROM (derived table)#

Use a query's result as a temporary table:

▶ Try it Yourselfdatabase: shopSQL
Ctrl + Enter to run

5. Correlated subquery#

A subquery that refers to the outer row - runs once per row:

▶ Try it Yourselfdatabase: shopSQL
Ctrl + Enter to run

CTEs - Common Table Expressions#

As questions get more complex, nested subqueries become hard to read. A CTE names each step with WITH:

WITH step1 AS (
    ...query...
),
step2 AS (
    ...query that can use step1...
)
SELECT ... FROM step2;
▶ Try it Yourselfdatabase: shopSQL
Ctrl + Enter to run
हिंदी में समझें

CTE (WITH) को recipe के कदमों की तरह समझें। हर कदम को एक नाम देते हैं (item_revenue, customer_revenue), और अगला कदम पिछले कदम का इस्तेमाल करता है। इससे लंबी query ऊपर से नीचे पढ़ने में आसान हो जाती है - जैसे Python में एक-एक variable बनाते हैं।

CTE सिर्फ उसी एक query तक रहता है; database में permanently save नहीं होता।

Why analysts love CTEs#

  • Readable: each step has a meaningful name.
  • Debuggable: run SELECT * FROM step1 to check an intermediate result.
  • Reusable within the query: refer to a CTE several times.
  • Supported by SQLite, MySQL 8+, PostgreSQL, SQL Server, Oracle, BigQuery, Snowflake...

CTE vs subquery vs view#

Lives for Use when
Subquery inside one query small, one-off lookups (e.g. average price)
CTE one query multi-step logic, readability
VIEW (CREATE VIEW ... AS) permanently in the database the same logic is reused by many reports

Summary#

  • Subqueries can return one value (scalar), a list (IN), a check (EXISTS), or a table (FROM).
  • Correlated subqueries refer to the outer row.
  • Prefer NOT EXISTS over NOT IN when NULLs are possible.
  • CTEs (WITH name AS (...)) make multi-step analysis readable and debuggable.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Above-average products

Show name and price of products whose price is above the average product price, highest first.

Database: shop (see the tables in this lesson)
2

Customers who bought furniture

Show the name of customers who have bought at least one Furniture product, using IN with a subquery (each name once), sorted by name.

Database: shop (see the tables in this lesson)
3

Monthly revenue with a CTE

Using a CTE named item_revenue (order_date and revenue per item for Delivered orders), show revenue per month in 2025 as month (format YYYY-MM) and revenue (rounded to 2 decimals), sorted by month.

Database: shop (see the tables in this lesson)

Quick Quiz

Q1.

What is a subquery?

Q2.

Which query lists products priced above the average price?

Q3.

What is the main benefit of a CTE (WITH ... AS)?

Q4.

How long does a CTE exist?

Q5.

Why can NOT IN (subquery) return no rows unexpectedly?