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

Scalar & Inline Subqueries

A subquery is a query nested inside another query, and it lets you answer questions that depend on the result of a prior calculation. To find batsmen who scored above the tournament average, you first need that average, then you compare each player against it. A subquery computes the inner result and feeds it to the outer query, all in one statement.

Subqueries appear in different positions, each with its own role. A scalar subquery returns a single value and can sit almost anywhere an expression is allowed, while an inline subquery in the FROM clause returns a whole result set treated as a temporary table. Recognising what shape a subquery returns is the key to placing it correctly and predicting how it behaves.

This nesting is what makes SQL compositional rather than flat. Instead of running one query, copying a number, and pasting it into a second query by hand, you let the engine compute the inner result and apply it automatically. Mastering scalar and inline subqueries unlocks a large class of two-step questions and lays the groundwork for the more advanced correlated subqueries and CTEs ahead.

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