MySQL Subqueries
A subquery is a SELECT inside another query, written in brackets. The inner query runs first, and its result is used by the outer query.
Subquery with a comparison
Find the students whose marks are above the average.
SELECT name, marks
FROM students
WHERE marks > (SELECT AVG(marks) FROM students)
ORDER BY marks DESC;
Result
| name | marks |
|---|---|
| Maria | 92 |
| Asha | 88 |
| Robin | 85 |
| John | 78 |
The inner query returns the average, 75.5. The outer query then returns the students above it.
Subquery with IN
SELECT name
FROM students
WHERE course_id IN (SELECT id FROM courses WHERE course_name = 'Python')
ORDER BY id;
Result
| name |
|---|
| Robin |
| John |
Subquery with EXISTS
EXISTS is true if the inner query returns at least one row.
SELECT c.course_name
FROM courses c
WHERE EXISTS (SELECT 1 FROM students s WHERE s.course_id = c.id)
ORDER BY c.id;
Courses that have students
| course_name |
|---|
| Python |
| Java |
| Web Design |
Second highest marks
SELECT MAX(marks) AS second_highest
FROM students
WHERE marks < (SELECT MAX(marks) FROM students);
Result
| second_highest |
|---|
| 88 |
Note:
Many subqueries can also be written as a JOIN, which is often faster. Use the one that is easier to read.
Summary
- A subquery is a query in brackets inside another query.
- Use it with comparison operators,
INandEXISTS. - Next: UNION.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |