SQL SUBQUERIES - Beginner Friendly Examples
What is a Subquery?
A subquery is a query inside another query.
Used in: SELECT, FROM, WHERE, HAVING
Example Table: Students
| student_id | name | marks |
|------------|--------|-------|
|1 | Riya | 75 |
|2 | Aryan | 82 |
|3 | Diya | 90 |
|4 | Kabir | 60 |
|5 | Meera | 85 |
1. Subquery in WHERE
"Students who scored above average":
SELECT name, marks
FROM Students
WHERE marks > (
SELECT AVG(marks) FROM Students
);
2. Subquery in SELECT
"Each student's marks with class average":
SELECT name, marks,
(SELECT AVG(marks) FROM Students) AS avg_class_marks
FROM Students;
3. Subquery in FROM
"Use a derived table to filter":
SELECT name, marks
FROM (
SELECT * FROM Students
) AS temp
WHERE marks > (
SELECT AVG(marks) FROM Students
);
4. Subquery with IN
"Students who got same marks as those scoring > 80":
SELECT name, marks
FROM Students
WHERE marks IN (
SELECT marks FROM Students WHERE marks > 80
);
Correlated Subquery Example
"Students scoring above average of everyone else":
SELECT name, marks
FROM Students s1
WHERE marks > (
SELECT AVG(marks)
FROM Students s2
WHERE s2.student_id <> s1.student_id
);
Subqueries let you break down complex logic step-by-step!