Nested Queries in SQL - Detailed Explanation
[Check] What is a Nested Query?
A nested query (or subquery) is a query inside another query. The inner query runs first and its result is used
by the outer query.
[Bullet] Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name OPERATOR (
SELECT column_name
FROM another_table
WHERE condition
);
[Check] Example: Find Students with Marks Above Average
Table: Students
| ID | Name | Marks |
|----|--------|-------|
| 1 | Aditya | 75 |
| 2 | Rohan | 55 |
| 3 | Sneha | 82 |
| 4 | Priya | 60 |
| 5 | Kavita | 90 |
Query:
SELECT Name, Marks
FROM Students
WHERE Marks > (
SELECT AVG(Marks)
FROM Students
);
Nested Queries in SQL - Detailed Explanation
[Explanation] Explanation:
1. Inner Query:
SELECT AVG(Marks) FROM Students; -> Result = 72.4
2. Outer Query:
SELECT Name, Marks FROM Students WHERE Marks > 72.4;
[Check] Output:
| Name | Marks |
|--------|-------|
| Aditya | 75 |
| Sneha | 82 |
| Kavita | 90 |
[Types] Types of Nested Queries:
1. Single-row subquery (e.g., =, >)
2. Multi-row subquery (e.g., IN, ANY, ALL)
[Multi-row Example] Example (Multi-row):
SELECT Name, Marks
FROM ClassA
WHERE Marks IN (
SELECT Marks
FROM ClassB
);
[Summary] Summary:
- Nested queries are useful for filtering or calculations based on another query.
- They are evaluated from inner to outer.