← Back to all snippets
SQL

Check for Record Existence Efficiently with EXISTS

Determine if any records exist that match specific criteria in a subquery using the SQL EXISTS operator, optimized for performance over COUNT.

SELECT p.product_name, p.price
FROM products p
WHERE EXISTS (
  SELECT 1
  FROM orders o
  WHERE o.product_id = p.product_id
  AND o.order_date > CURRENT_DATE - INTERVAL '30 days'
);
How it works: The `EXISTS` operator is used to test for the existence of any rows in a subquery. It returns `TRUE` if the subquery returns one or more rows, and `FALSE` otherwise. This is often more efficient than `COUNT(*)` for existence checks because the subquery can stop processing as soon as it finds the first matching row. This example retrieves products that have been ordered in the last 30 days.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs