Advertisement
Google Ad Slot: content-top
MySQL EXISTS
MySQL EXISTS Clause
The EXISTS operator in MySQL is used to check if a subquery returns any results.
- It returns TRUE if the subquery finds at least one row.
- It returns FALSE if the subquery returns no rows.
It is commonly used in WHERE clauses to perform conditional checks.
EXISTS Syntax
SELECT column_name(s) FROM table_name WHERE EXISTS ( SELECT 1 FROM another_table WHERE condition );
EXISTS→ Checks if the subquery has any rows.SELECT 1→ It is a convention to useSELECT 1instead of selecting actual data, as it improves performance.WHERE condition→ Condition for the subquery.
MySQL EXISTS Examples
We have two tables:
students Table
student_id |
name |
gender |
city |
age |
score |
course_id |
phone_number |
|
|---|---|---|---|---|---|---|---|---|
1 |
Alice |
Female |
Delhi |
20 |
85 |
101 |
NULL |
1234567890 |
2 |
Bob |
Male |
Mumbai |
22 |
75 |
NULL |
bob@email.com |
NULL |
3 |
Charlie |
Male |
Delhi |
21 |
95 |
102 |
NULL |
NULL |
4 |
David |
Male |
Bangalore |
23 |
65 |
101 |
david@email.com |
NULL |
5 |
Eve |
Female |
Mumbai |
20 |
80 |
103 |
NULL |
NULL |
6 |
Frank |
Male |
Delhi |
22 |
90 |
103 |
NULL |
NULL |
7 |
Alice |
Female |
Mumbai |
19 |
60 |
102 |
NULL |
NULL |
courses Table
course_name |
course_name |
|---|---|
101 |
Math |
102 |
Science |
103 |
History |
104 |
English |
The following SQL statement find students enrolled in courses.
Output:
name |
|---|
Alice |
Bob |
Charlie |
David |
Eve |
Frank |
Explanation:
EXISTSchecks if the student’scourse_idexists in thecoursestable.- Since all course IDs in
studentsexist incourses, all students are returned.