Exists
checks whether or not the result of a subquery is empty.
SELECT *
FROM customers
WHERE NOT EXISTS (SELECT *
FROM customers.id = orders.customer_id
)
The example returns all customers that have not place an order yet—for whom there exists no order. Not exists
is also said to be an anti join while exists
is a semi join.
The columns selected in the subquery are irrelevant. The asterisk (*
) is commonly used and does not mean “all columns” in this context. Exists
can be used wherever conditions are allowed: where
, having
, case when
, ….
Standard Features
F671, “Subqueries in CHECK constraints”
Product specific functions: exception join
.
The Exists
is defined in ISO/IEC 9075-2:2023 as the mandatory feature E061-08.
You can’t catch up on 20 years of SQL evolution in one day. Subscribe the newsletter via E-Mail, Bluesky or RSS to gradually catch up and to keep modern-sql.com on your radar.
The essence of SQL tuning in 200 pages
Buy now!
(paperback and/or PDF)
Paperback also available at Amazon.com.
Markus offers SQL training and consulting for developers working at companies of all sizes.
Learn more »