Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

SQL
SQL
0/12 completed
Beginner
What is a database?SELECT: reading dataFiltering with WHERESorting and limiting results
Intermediate
Aggregates and GROUP BYJOINs: combining tablesINSERT, UPDATE and DELETECreating tables and constraints
Advanced
Subqueries and CTEsWindow functions
Pro
Indexes and transactionsDatabase design and normalization
Tracks / SQL / Advanced

Subqueries and CTEs

Some questions need multiple steps: "Find products priced above the average price." First compute the average, then compare. Subqueries and CTEs let you build queries out of other queries.

Subquery in WHERE

SQL · editable

The inner query runs first and returns a single value.

Subquery with IN

SQL · editable

EXISTS

EXISTS checks whether a subquery returns any row. It's often faster than IN on large tables, and it's the clearest way to say "has at least one…".

SQL · editable

This is a correlated subquery: it refers to c from the outer query, so it's evaluated per customer.

Subquery in FROM (derived table)

SQL · editable

CTEs: WITH for readable queries

A Common Table Expression names a subquery up front, like a variable. Long reports become a series of readable steps.

SQL · editable

Pro tip: when a query grows past ~15 lines, break it into CTEs. Each step can be tested on its own by changing the final SELECT.

Recursive CTEs

A CTE can refer to itself. It's useful for sequences, org charts and category trees.

SQL · editable
SQL · editable

UNION

UNION stacks results from two queries with the same columns (UNION ALL keeps duplicates and is faster).

SQL · editable

Practice

Using a CTE, find the best-selling product (by total quantity) in each category.

SQL · editable
✎ Check your understanding

1.What is a correlated subquery?

2.Why use a CTE instead of nested subqueries?

← Creating tables and constraints