To test the existence of any record in subquery EXISTS operator is used.
It returns a boolean value (True/False).
It returns True when the record is found in the subquery.
Syntax:
SELECT * FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);
DEMO STUDENTS TABLE:
Roll_No | Name | Marks |
1 | Dev | 35 |
2 | Ayush | 45 |
3 | Ram | 55 |
4 | Pyush | 65 |
5 | Nazim | 75 |
Example: This SQL subquery will return True as Roll no. 2 is present in the table.
SELECT * FROM students
WHERE EXISTS
(SELECT Roll_No FROM students WHERE Roll_No = 5);
This will select the full table as the condition is True:
Roll_No | Name | Marks |
1 | Dev | 35 |
2 | Ayush | 45 |
3 | Ram | 55 |
4 | Pyush | 65 |
5 | Nazim | 75 |