SQL 7 : Subqueries & Views
D
Qubits of DPK
April 11, 2026
Core DBMS
Quick Recap (SQL 6)
You learned JOINs + GROUP BY + HAVING.
sql
QUBITS OF DPK
Problem: What if the filter condition itself needs to be computed first? That's where subqueries come in.
1. What Is a Subquery?
Layman: A subquery is a question inside a question.
sql
QUBITS OF DPK
Execution order:
- #Inner query runs → returns 60000
- #Outer query uses that: WHERE salary > 60000
2. Types of Subqueries — The Full Map
3. Subquery in WHERE (Scalar Subquery)
Use when: you need one computed value to filter against.
Real-world: Spotify filters songs with above-average stream counts for a featured playlist.
sql
QUBITS OF DPK
Build-up:
sql
QUBITS OF DPK
4. Subquery with IN (Multi-Value)
Use when: the inner query returns a list of values.
Real-world: Amazon shows orders only from warehouses located in a specific region.
sql
QUBITS OF DPK
Interview tip: IN is clean and readable. But if the subquery returns thousands of rows, EXISTS is faster. Know the trade-off.
5. Subquery in FROM (Derived Table)
Use when: you need to aggregate first, then filter on that aggregation.
Why can't you just use HAVING?
HAVING filters groups. But what if you want to treat the grouped result as a table and do more operations on it? That's when you move the aggregation into a FROM subquery.
Real-world: A BI dashboard at Swiggy computes per-restaurant average order value, then surfaces only the top performers.
sql
QUBITS OF DPK
Build-up visual:
Outer query filters on this virtual table.
6. Correlated Subquery
The most interview-heavy subquery type.
Layman: A correlated subquery is like an employee review process where each employee is compared specifically to their own team — not the whole company.
Real-world: Flipkart highlights sellers whose product prices are below the average for their own category.
sql
QUBITS OF DPK
Execution trace (for 3 employees):
sql
QUBITS OF DPK
️ Performance Warning: Correlated subqueries run N times (once per outer row). At scale, this becomes expensive. For MAANG interviews — always mention this and suggest replacing with a window function when possible.
Optimized alternative using window function:
sql
QUBITS OF DPK
7. EXISTS and NOT EXISTS
EXISTS = "Does at least one matching row exist?"
Layman: Think of it like a bouncer checking a guest list. The bouncer doesn't need to read the whole list — they just need to find your name once and wave you in.
SQL stops scanning the moment it finds the first matching row. That's why EXISTS is fast.
Real-world: Netflix checks if a user has watched anything before showing a "Continue Watching" section.
sql
QUBITS OF DPK
Why SELECT 1? EXISTS only cares whether rows exist — not what they contain. SELECT 1 is a convention that signals "I'm only checking existence, not fetching data."
NOT EXISTS = opposite — find rows with no matching record.
Real-world: Zomato identifies users who signed up but never placed an order (for a re-engagement campaign).
sql
QUBITS OF DPK
EXISTS vs IN — Know the Difference
8. ANY and ALL
Both compare a value against a set returned by a subquery.
ANY = "Is my value greater than at least one value in the set?"
sql
QUBITS OF DPK
ALL = "Is my value greater than every value in the set?"
sql
QUBITS OF DPK
Memory trick: ANY = pass the easiest bar. ALL = pass the hardest bar.
9. Views — Virtual Tables
Layman: A view is like a saved search on your phone. You don't store the results — you store the query. Every time you open it, it re-runs and gives you fresh results.
sql
QUBITS OF DPK
Why views exist in production:
Real-world: At Paytm, the analytics team queries a active_users_monthly view. The underlying join across 4 tables is hidden inside the view — analysts just write SELECT * FROM active_users_monthly WHERE region = 'South'.
30-Second Interview Explanation — Subqueries
"A subquery is a query nested inside another query. The inner query runs first, and its result is used by the outer query. There are several types: scalar subqueries return a single value used in WHERE, IN subqueries return a list, FROM subqueries create a derived temporary table, and correlated subqueries reference the outer query's current row and re-execute for each row. EXISTS is a boolean check — it stops at the first match, making it faster than IN for large result sets. When a correlated subquery gets expensive, I replace it with a window function, which processes all rows in a single pass."
Mental Model Summary
sql
QUBITS OF DPK