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

Correlated Subqueries & EXISTS

A non-correlated subquery runs once and stands alone, but a correlated subquery is different: it references a column from the outer query, so it must be re-evaluated for each outer row. This lets you ask per-row questions, such as whether each player scored above their own team's average, where the comparison value changes from row to row depending on that row's context.

EXISTS is the natural partner of correlated subqueries. Rather than returning values, EXISTS simply tests whether the inner query produces any rows at all for the current outer row, returning true or false. This makes it perfect for presence and absence questions, like "players who have at least one century" or "teams with no away matches", expressed efficiently without pulling any inner data.

Correlated subqueries and EXISTS unlock genuinely relational questions that depend on a relationship between the outer row and a set of related rows. They are more powerful than simple subqueries but require care, because the per-row evaluation has performance implications and the handling of NULLs in NOT IN versus NOT EXISTS is a notorious source of silent bugs that this lesson will make clear.

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 20 of 35
0% complete