Subqueries#
A subquery is a query inside another query, written in brackets. It lets you use the result of one question to answer another.
Subquery = एक query के अंदर दूसरी query। अंदर वाली query पहले चलती है, और उसका जवाब बाहर वाली query इस्तेमाल करती है।
उदाहरण: "औसत से महंगे products" - पहले औसत निकालो (अंदर की query), फिर उससे तुलना करो (बाहर की query)।
1. Scalar subquery - returns one value#
2. IN subquery - returns a list#
3. EXISTS / NOT EXISTS#
EXISTS checks whether the subquery returns any row - often clearer and safer than NOT IN:
NOT IN (subquery) returns no rows at all if the subquery contains a single NULL. Use NOT EXISTS or LEFT JOIN ... IS NULL when NULLs are possible.
4. Subquery in FROM (derived table)#
Use a query's result as a temporary table:
5. Correlated subquery#
A subquery that refers to the outer row - runs once per row:
CTEs - Common Table Expressions#
As questions get more complex, nested subqueries become hard to read. A CTE names each step with WITH:
WITH step1 AS (
...query...
),
step2 AS (
...query that can use step1...
)
SELECT ... FROM step2;
CTE (WITH) को recipe के कदमों की तरह समझें। हर कदम को एक नाम देते हैं (item_revenue, customer_revenue), और अगला कदम पिछले कदम का इस्तेमाल करता है। इससे लंबी query ऊपर से नीचे पढ़ने में आसान हो जाती है - जैसे Python में एक-एक variable बनाते हैं।
CTE सिर्फ उसी एक query तक रहता है; database में permanently save नहीं होता।
Why analysts love CTEs#
- Readable: each step has a meaningful name.
- Debuggable: run
SELECT * FROM step1to check an intermediate result. - Reusable within the query: refer to a CTE several times.
- Supported by SQLite, MySQL 8+, PostgreSQL, SQL Server, Oracle, BigQuery, Snowflake...
CTE vs subquery vs view#
| Lives for | Use when | |
|---|---|---|
| Subquery | inside one query | small, one-off lookups (e.g. average price) |
| CTE | one query | multi-step logic, readability |
VIEW (CREATE VIEW ... AS) |
permanently in the database | the same logic is reused by many reports |
Summary#
- Subqueries can return one value (scalar), a list (IN), a check (EXISTS), or a table (FROM).
- Correlated subqueries refer to the outer row.
- Prefer NOT EXISTS over NOT IN when NULLs are possible.
- CTEs (
WITH name AS (...)) make multi-step analysis readable and debuggable.