3. Modifying Data, Performance & Capstone
Subqueries, CTEs (WITH) & Indexes
Break complex multi-step SQL questions into clean named stages using Common Table Expressions (CTEs) and make slow queries 100x faster with B-tree database indexes.
- Read and write subqueries for dynamic threshold comparisons
- Structure multi-step SQL analytics cleanly using WITH Common Table Expressions (CTEs)
- Speed up slow filters and JOINs with database indexes while weighing write trade-offs
When a business question takes multiple steps—such as "Find every product whose total units sold beat the average product volume"—shoving everything into one giant SELECT quickly becomes unreadable. Subqueries and CTEs (WITH) let you solve complex SQL problems cleanly one step at a time.
Subqueries: Nesting a Helper Query
A subquery embeds one SELECT inside parentheses inside another query. For example, how do you list orders whose total exceeds the average order total without hardcoding a number?
SELECT id, customer_id, total_amount
FROM orders
WHERE total_amount > (
SELECT AVG(total_amount) FROM orders
);SQL runs the inner query first (AVG(total_amount)), plugs that single answer into the comparison, and filters orders cleanly.
Common Table Expressions (WITH): Clean Step-by-Step SQL
Deeply nested subqueries inside subqueries are exhausting to read. A CTE (Common Table Expression) flips the layout inside out: you define named temporary tables at the top with WITH, just like creating clear helper variables in Python:
WITH course_totals AS (
SELECT
c.id,
c.title,
c.category,
COUNT(e.id) AS total_students
FROM courses c
LEFT JOIN enrollments e ON e.course_id = c.id
GROUP BY c.id, c.title, c.category
)
SELECT title, category, total_students
FROM course_totals
WHERE total_students >= 2
ORDER BY total_students DESC;You can even chain multiple stages separated by commas (WITH step_one AS (...), step_two AS (SELECT ... FROM step_one) SELECT ... FROM step_two;), turning tangled analytics into top-to-bottom storytelling.
Every CTE name documents why that intermediate table exists—making code reviews and future bug fixes effortless.
Try It Yourself: Multi-Step CTE Query Live
Run this CTE query against our live SQLite database—first computing each customer's paid order spend in customer_spend, then filtering to customers who spent more than $100:
Click “Run Code” to execute this snippet right in your browser.
Why Queries Get Slow — And How Indexes Speed Them Up
Without an index, running WHERE email = 'maya@example.com' on a 2-million-row students table forces SQL to read all 2,000,000 rows from top to bottom (a Full Table Scan).
A database index acts just like the alphabetical index at the back of a textbook—letting the engine jump straight to the exact page in a couple of milliseconds:
CREATE INDEX idx_students_email ON students(email);
CREATE INDEX idx_enrollments_course_id ON enrollments(course_id);When to Add Indexes (and When NOT To)
Indexes dramatically accelerate reads (SELECT), but every INSERT, UPDATE, and DELETE must also update those index trees on disk, consuming extra storage and slightly slowing heavy write traffic. Add indexes selectively on columns used heavily in:
- High-traffic
WHERElookups (email,slug,status) JOIN ... ONforeign key columns (course_id,customer_id)- Large table
ORDER BYsorts (created_at DESC)
Quick Checkpoints
What is the main benefit of a Common Table Expression (WITH ... AS (...))?
Why shouldn't you create an index on every single column of a table?