Junior — Middle
Can you explain what the EXISTS operator means in SQL and how it is used?
sobes.tech AI
Answer from AI
The EXISTS operator in SQL is used to check for the existence of rows returned by a subquery. It returns TRUE if the subquery returns at least one row, and FALSE if the subquery is empty.
It is often used in WHERE conditions to filter data based on the presence of related records.
Example:
SELECT * FROM employees e
WHERE EXISTS (
SELECT 1 FROM departments d
WHERE d.id = e.department_id AND d.name = 'Sales'
);
This example selects all employees who work in the "Sales" department. The subquery checks for the existence of the corresponding department, and if it exists, EXISTS returns TRUE.