EXISTS
PG 7.4+→ booleanReturns true if the subquery returns any rows. Short-circuits on first match — does not evaluate all rows.
Signature
EXISTS ( subquery ) → booleanParameters
| Parameter | Type | Description |
|---|---|---|
| subquery | SELECT statement | Subquery to test |
Examples
SELECT * FROM users u WHERE EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id);Users who have orderedSELECT * FROM products p WHERE NOT EXISTS (SELECT 1 FROM order_items i WHERE i.product_id = p.id);Products never orderedSELECT department_id FROM departments d WHERE EXISTS (SELECT 1 FROM employees e WHERE e.department_id = d.id AND e.salary > 100000);Departments containing at least one high-paid employeeUPDATE inventory SET reorder_flag = true WHERE NOT EXISTS (SELECT 1 FROM purchase_orders po WHERE po.sku = inventory.sku AND po.status = 'open');Flags items with no open purchase order for reorderThe SELECT list inside EXISTS is never evaluated — only row existence matters. Use `SELECT 1` (or `SELECT *`) as a convention. The planner optimizes EXISTS to a semi-join.
-- Good:
WHERE EXISTS (SELECT 1 FROM t WHERE condition)
-- Avoid: WHERE EXISTS (SELECT expensive_func() FROM t WHERE condition)exists() column list is ignored by the planner