Relationships and JOINs
EXISTS and NOT EXISTS
Test existence without needing the related values.
Understand the concept
EXISTS is TRUE when its subquery produces at least one row. The projected value is not the point; SELECT 1 is a common convention. NOT EXISTS tests the absence of matching rows.
For customers who have ordered, EXISTS states the intention more directly than multiplying rows with a JOIN and removing duplicates. NOT EXISTS avoids the NULL problem of NOT IN. Do not declare one pattern universally faster: inspect the plan, indexes and data distribution.
Use it for existence, absence, unsold products and missing relationships.
Assuming the value projected inside EXISTS determines the match.
One topic. Three levels of depth.
SELECT c.FullName FROM lab.Customer AS c WHERE EXISTS (SELECT 1 FROM lab.SalesOrder AS o WHERE o.CustomerId = c.CustomerId);Finds five customers with orders, without repeating customers.
This page does not execute SQL. Practise in the downloadable SqlStudioLab using SSMS. Before rerunning temporary-table examples, remove only the relevant #table. Views, procedures and functions create persistent lab objects; never use a production connection.
Try it yourself first.
Find customers without orders using NOT EXISTS.
Show the solution and explanation
SELECT c.FullName FROM lab.Customer AS c WHERE NOT EXISTS (SELECT 1 FROM lab.SalesOrder AS o WHERE o.CustomerId = c.CustomerId);Selin. The subquery projection does not change the existence test.