MySQL Tutorial
The EXISTS operator is used to test for the existence of any record in a sub query.
The EXISTS operator returns true if the sub query returns one or more records.
EXISTS is commonly used with correlated sub queries.
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);
Let's put these statements into real use.
We've a table named Students and Teachers in our database that contains the following records:
ROLL_NO | NAME | SUBJECT |
---|---|---|
1 | Will | C++ |
2 | SAM | Python |
3 | Rani | Node.js | 4 | Rim | Java |
5 | Micheal | JAVA |
6 | Lara | PHP |
TECH_NO | NAME | SUBJECT | ROLL_NO |
---|---|---|---|
20 | Kayla | PHP | 6 |
21 | Albert | Java | 2 |
21 | Albert | Java | 5 |
22 | Helen | Node.js | 3 | 23 | Anne | Python | 2 |
24 | Jaime | C++ | 1 |
The following MySQL statement returns TRUE and lists the Teacher name with a Student ROLL_NO less than 4:
SELECT TECH_NO
FROM Teachers
WHERE EXISTS
(SELECT ROLL_NO FROM Students
WHERE Students.ROLL_NO = Teachers.ROLL_NO AND ROLL_NO < 4);
Now, after executing the above MySQL statement,
TECH_NO |
---|
21 |
22 | 23 |
24 |