# Subqueries and CTEs

> Structuring multi-step logic with subqueries and common table expressions so complex queries stay readable and testable. Free notes, key concepts, resources...

Canonical: https://www.internhack.in/roadmaps/tracks/data-analyst/sql-subqueries-ctes
Last updated: 2026-11-28

Structuring multi-step logic with subqueries and common table expressions so complex queries stay readable and testable.

Intermediate · about 5 hours · difficulty 3/5

Learn first: [Joins and Combining Tables](https://www.internhack.in/roadmaps/tracks/data-analyst/sql-joins)

Most real analyses need several steps: find each user's first order, then group users by that month, then compute retention. Subqueries and CTEs let you express those steps.

### Subqueries

- **Scalar subquery**: returns one value, e.g. `WHERE amount > (SELECT AVG(amount) FROM orders)`.
- **IN / EXISTS subquery**: filters by membership.
- **Derived table**: a subquery in FROM that you treat like a table.
- **Correlated subquery**: references the outer row; powerful but can be slow.

### Common table expressions

```
WITH first_orders AS (
  SELECT customer_id, MIN(order_date) AS first_order_date
  FROM orders
  GROUP BY customer_id
),
monthly AS (
  SELECT DATE_TRUNC('month', first_order_date) AS cohort_month,
         COUNT(*) AS new_customers
  FROM first_orders
  GROUP BY 1
)
SELECT * FROM monthly ORDER BY cohort_month;
```

CTEs read top to bottom like a recipe. Name each one for what it contains, keep each step small, and run them individually while debugging.

### Recursive CTEs

`WITH RECURSIVE` walks hierarchies (org charts, category trees) or generates series. Occasionally useful; not daily work.

**Pitfalls:** deeply nested subqueries no one can read, and huge CTE chains that repeat the same scan. Move on when you can refactor a nested query into named CTE steps and validate each step's row count.

## Key concepts

- **Scalar and IN subqueries**
- **EXISTS and correlated subqueries**
- **Derived tables**
- **WITH clauses (CTEs)**
- **Structuring multi-step logic**
- **Recursive CTEs**

## Mini project

Using the Olist dataset, write a CTE-based query that finds each customer's first purchase month and counts how many of them bought again within 90 days.

## Check yourself

When would you choose EXISTS over IN, and what NULL-related trap does NOT IN have?

## Free resources

- [Mode SQL Tutorial](https://mode.com/sql-tutorial/) (Mode)
- [PostgreSQL: WITH queries](https://www.postgresql.org/docs/current/queries-with.html) (PostgreSQL)
- [Advanced SQL](https://www.kaggle.com/learn/advanced-sql) (Kaggle)

Previous: [Joins and Combining Tables](https://www.internhack.in/roadmaps/tracks/data-analyst/sql-joins) · Next: [Window Functions](https://www.internhack.in/roadmaps/tracks/data-analyst/sql-window-functions)

## More in Querying Data with SQL

- [SQL Basics: SELECT, WHERE, ORDER BY](https://www.internhack.in/roadmaps/tracks/data-analyst/sql-select-filter)
- [Aggregation with GROUP BY and HAVING](https://www.internhack.in/roadmaps/tracks/data-analyst/sql-aggregation)
- [Joins and Combining Tables](https://www.internhack.in/roadmaps/tracks/data-analyst/sql-joins)
- [Subqueries and CTEs](https://www.internhack.in/roadmaps/tracks/data-analyst/sql-subqueries-ctes)
- [Window Functions](https://www.internhack.in/roadmaps/tracks/data-analyst/sql-window-functions)
- [Dates, Times and Text in SQL](https://www.internhack.in/roadmaps/tracks/data-analyst/sql-dates-strings)
- [Writing Efficient and Readable SQL](https://www.internhack.in/roadmaps/tracks/data-analyst/sql-performance)

## Related

- [Roadmaps](https://www.internhack.in/roadmaps)
- [Data Analyst Roadmap](https://www.internhack.in/roadmaps/tracks/data-analyst)
