100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
SQL Mastery
35 minbeginner

Common Table Expressions (WITH clause)

As queries grow, deeply nested subqueries become hard to read and harder to debug. A Common Table Expression, or CTE, solves this by letting you define a named, temporary result set at the top of a query using the WITH keyword, then reference it by name below. It turns an unreadable pyramid of nesting into a clean, top-to-bottom sequence of named steps.

A CTE is essentially a derived table with a name and better ergonomics. Instead of embedding a subquery inside FROM and aliasing it inline, you declare it once with WITH and use its name like a real table. This separation of definition from use makes complex logic readable, because each stage is named, defined in isolation, and composed in the order a human actually thinks about the problem.

CTEs are among the most loved features in modern SQL because they make sophisticated queries maintainable. You can chain several CTEs so each builds on the last, reuse a CTE's result multiple times in the main query, and read the whole thing as a logical pipeline. Mastering CTEs is the difference between writing clever queries and writing queries other people, including future you, can understand.

Analogy🏏Cricket
🏏 Think of it like cricket: Imagine the end of an IPL innings when the scorer announces the team's final total. Just as the scorer does not read out all one hundred and twenty individual deliveries but instead sums them into a single team score, SUM folds many row values into one number. Just as the commentator reports the highest individual score, the average partnership, and the number of wickets, MAX, AVG, and COUNT each summarise the innings differently. Just as a not-out batsman with no deliveries faced does not lower the team average, aggregates skip NULLs when computing. Just as the announcement is one figure no matter whether the innings had fifty deliveries or two hundred and fifty, an aggregate collapses any number of rows into a single result. This reveals why summaries answer the questions about the whole that individual deliveries cannot.
Lesson 21 of 35
0% complete