Module · 6 lessons

Subqueries, CTEs, and Views

Build queries inside queries — scalar, multi-row, nested, and correlated subqueries, plus CTEs and reusable views.

At a glance

Level
Intermediate
Lessons
6 lessons
Time to complete
2 weeks
Cost
Free forever · no sign-up

Welcome to Subqueries, CTEs, and Views — the module where your SQL grows from single, flat queries into layered logic that can answer almost any question a business throws at you. So far you have selected, filtered, sorted, joined, and aggregated data. Now you will learn to put one query inside another, so the result of one calculation becomes the input to the next.

Data for this module

Database: chinook.db — a digital music store (SQLite). The guided project (Lesson 6) uses stores.db — a scale-model car retailer.

Open it in any SQLite client — DB Browser for SQLite, the sqlite3 CLI, or Python’s sqlite3. Each lesson lists the specific tables it uses.

Throughout this module you work with the Chinook database, a realistic model of a digital music store with customers, invoices, tracks, albums, genres, and employees. You will compute each country’s share of total sales, filter customers against a list generated by another query, traverse a company’s management hierarchy, and package complex logic into named, reusable building blocks. These are the exact patterns analysts and engineers reach for every day.

You will start with scalar subqueries — a query that returns a single value you can drop into any comparison or calculation. From there you move to multi-row and multi-column subqueries that feed IN, ANY, and ALL, then to nested and correlated subqueries that depend on the row being processed. Finally you will organize tangled logic with common table expressions (the WITH clause), traverse tree structures with recursive CTEs, and persist your best queries as views that behave like virtual tables.

Every concept is hands-on, with runnable queries and real output you can reproduce. The module closes with a guided project where you analyze a scale-model-car sales database end to end — recommending what to restock, ranking your most valuable customers, and estimating how much you can spend to acquire new ones. Start with Lesson 1, where you will write your first subquery and see exactly why subqueries matter.

Lessons in this module

Achievement

Complete all 6 lessons to finish the Subqueries, CTEs, and Views module.

Start module