IN and EXISTS are SQL operators used to check whether a condition is satisfied, but they work differently.
- IN checks whether a value matches any value in a list or the result of a subquery.
- EXISTS checks whether a subquery returns at least one row. It returns TRUE if the subquery returns one or more rows and FALSE if it returns no rows.
The table below shows the major differences between IN and EXISTS:
| IN | EXISTS |
|---|---|
| Checks whether a value matches any value returned by a subquery or listed explicitly. | Checks whether a subquery returns at least one row. |
| Compares a value with the values returned by the subquery. | Checks only whether matching rows exist. |
| Can be used with a list of values. | Requires a subquery. |
| Can be easier to read when checking against a small list of values. | Often useful when checking related data between tables. |
| May process the values returned by the subquery before making the comparison. | Can stop checking once a matching row is found. |
| Example: SELECT * FROM employee WHERE department_id IN (1, 2); | Example: SELECT name FROM employee WHERE EXISTS (SELECT 1 FROM department); |
Example of IN and EXISTS
The following examples demonstrate how IN and EXISTS work when filtering records based on related data.
Table: employee
| employee_id | name | department_id |
|---|---|---|
| 1 | Alice | 10 |
| 2 | Bob | 20 |
| 3 | Charlie | 30 |
Table: department
| department_id | department_name |
|---|---|
| 10 | HR |
| 20 | Sales |
IN
Query:
SELECT *FROM employeeWHERE department_id IN (SELECT department_idFROM department);
Output:
| employee_id | name | department_id |
|---|---|---|
| 1 | Alice | 10 |
| 2 | Bob | 20 |
Here, IN checks whether each employee's department_id matches any department_id returned by the subquery.
EXISTS
Query:
SELECT *FROM employee AS eWHERE EXISTS (SELECT 1FROM department AS dWHERE d.department_id = e.department_id);
Output:
| employee_id | name | department_id |
|---|---|---|
| 1 | Alice | 10 |
| 2 | Bob | 20 |
Here, EXISTS checks whether at least one matching department exists for each employee.