SQL
Checking for Existence with EXISTS in Subqueries
Optimize your SQL queries by using the `EXISTS` operator to efficiently check for the presence of related records in a subquery, improving performance over `IN` for certain scenarios.
SELECT
c.customer_id,
c.customer_name
FROM
Customers c
WHERE EXISTS (
SELECT 1
FROM Orders o
WHERE o.customer_id = c.customer_id
AND o.total_amount > 100
);
How it works: This query uses the `EXISTS` operator to find customers who have placed at least one order with a `total_amount` greater than 100. Instead of retrieving actual data from the subquery, `EXISTS` simply checks for the presence of any rows that satisfy the subquery's condition. This is often more efficient than `IN` when dealing with large datasets, as it can stop processing as soon as a matching row is found.