SQL EXISTS and NOT EXISTS: check whether matching rows exist

Sometimes you don't need columns from a second table, only the answer to "is there a match?": customers with at least one delivery, employees who never handled an order. That is what EXISTS and NOT EXISTS are for, and along the way you'll meet the best-known subquery trap: NOT IN with NULL.

In short: WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id) keeps every customer who has at least one order. NOT EXISTS keeps the ones who have none. The subquery refers to the outer row through o.customer_id = c.customer_id, which makes it a correlated subquery.

Before you start: subqueries and JOIN. For the NOT IN trap, the lesson on NULL helps.

Try it now

Orders live in their own table. For each customer you ask: is there a delivered order from them in there?

Task Sales is planning a thank-you email to every customer who has already received at least one delivery. Show the name and city of every customer with at least one order whose status is 'delivered'. Use EXISTS.

customers 12 rows, 7 columns
customer_idnamecitycountrycustomer_sincesegmentphone
1Harbor Fremont PartnersBostonUSA2021-03-15Business617-555-0142
2Emily CarterChicagoUSA2022-07-01ConsumerNULL
3Riverside County OfficeRiversideUSA2020-11-20Government951-555-0110
4Raj PatelLeedsUK2023-01-09Consumer0113 496 0123
5Lakeview Hotel LtdManchesterUK2022-04-18Business0161 496 0456
6Olivia BrooksAustinUSA2024-02-27ConsumerNULL
7Greene & Shaw LLPLondonUK2021-09-05Business020 7946 0321
8Maple Grove High SchoolAustinUSA2023-08-14School512-555-0187
9Chloe EvansBostonUSA2025-05-30Consumer617-555-0199
10Northline Printing CoTorontoCanada2020-06-12Business416-555-0133
11Daniel KimSeattleUSA2024-10-03ConsumerNULL
12Westbrook Dental ClinicChicagoUSA2022-12-01Business312-555-0164
orders 18 rows, 5 columns
order_idcustomer_idorder_datestatusemployee_id
100112026-01-08delivered3
100242026-01-12delivered4
100332026-01-20delivered3
100472026-02-03delivered4
100522026-02-11cancelled8
100612026-02-25delivered3
1007102026-03-04delivered2
100852026-03-17delivered4
100982026-03-30delivered3
101062026-04-07delivered8
1011122026-04-22delivered4
101232026-05-06delivered3
101392026-05-19cancelled8
101472026-06-02shipped4
101512026-06-10shipped3
1016112026-06-12openNULL
101742026-06-13openNULL
1018102026-06-14openNULL

How EXISTS works

EXISTS goes in WHERE, followed by a subquery in parentheses. The condition is true as soon as the subquery returns at least one row and false when it returns none. What the subquery selects makes no difference, which is why people usually write SELECT 1.

Here's an example. Customer service wants every customer who still has an open order.

SELECT c.name, c.city
FROM customers c
WHERE EXISTS (
  SELECT 1
  FROM orders o
  WHERE o.customer_id = c.customer_id
    AND o.status = 'open'
);
namecity
Raj PatelLeeds
Northline Printing CoToronto
Daniel KimSeattle

Read it one customer at a time. For Raj Patel, customer_id 4, the subquery looks for open orders with customer_id 4, finds order 1017, so EXISTS is true and he stays. For Harbor Fremont Partners it finds no open order, so they drop out.

The key line is o.customer_id = c.customer_id. From inside the subquery it reaches out to the table of the outer query. A subquery like that is called correlated. Without the link, the subquery asks the same thing for every customer: is there an open order anywhere? The answer is always yes, and every customer ends up on the list.

NOT EXISTS and the NOT IN trap

NOT EXISTS flips the question: the row stays when the subquery finds nothing. Say you want everyone on the team who has nobody reporting to them. NOT IN looks like the natural choice:

SELECT first_name, last_name
FROM employees
WHERE employee_id NOT IN (SELECT manager_id FROM employees);

The result is empty, and there's no error. Here's why: Karen Mitchell runs the company, so her manager_id is NULL. That puts a NULL in the list NOT IN checks against. For Julia Reyes the question becomes: is 3 different from 1, from 2, from 5, from 7 and from NULL? Comparing with NULL is unknown, so the whole condition is unknown, and WHERE drops the row. The same happens to everyone. NOT EXISTS doesn't have this problem:

SELECT e.first_name, e.last_name
FROM employees e
WHERE NOT EXISTS (
  SELECT 1
  FROM employees r
  WHERE r.manager_id = e.employee_id
);
first_namelast_name
JuliaReyes
MarcusAllen
FelixTurner
DavidRoss
LauraHughes
PaulWard

Karen Mitchell's NULL is harmless here: r.manager_id = e.employee_id is never true for her row, so it simply doesn't count as a match. The takeaway: for "there is no such row", NOT EXISTS is the safe choice. If you'd rather keep NOT IN, filter the NULLs out inside the subquery with WHERE manager_id IS NOT NULL.

One more exercise: walk into the NOT IN trap yourself

Open orders haven't been assigned to anyone yet, so their employee_id is NULL. Go ahead and try NOT IN first, then run it and look at the result.

Task The team lead wants to know who has never handled an order. Show the first_name, last_name and department of every employee whose employee_id does not appear in any order. Use NOT EXISTS.

employees 10 rows, 7 columns
employee_idfirst_namelast_namedepartmentsalaryhire_datemanager_id
1KarenMitchellManagement936002018-01-02NULL
2TomBradleySales624002019-04-011
3JuliaReyesSales468002021-06-152
4MarcusAllenSales492002020-09-012
5SarahLongWarehouse396002022-02-011
6FelixTurnerWarehouse354002024-03-185
7NinaCooperAccounting528002019-10-011
8DavidRossCustomer service384002023-05-022
9LauraHughesCustomer serviceNULL2025-09-012
10PaulWardAccounting432002022-11-147
orders 18 rows, 5 columns
order_idcustomer_idorder_datestatusemployee_id
100112026-01-08delivered3
100242026-01-12delivered4
100332026-01-20delivered3
100472026-02-03delivered4
100522026-02-11cancelled8
100612026-02-25delivered3
1007102026-03-04delivered2
100852026-03-17delivered4
100982026-03-30delivered3
101062026-04-07delivered8
1011122026-04-22delivered4
101232026-05-06delivered3
101392026-05-19cancelled8
101472026-06-02shipped4
101512026-06-10shipped3
1016112026-06-12openNULL
101742026-06-13openNULL
1018102026-06-14openNULL

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

EXISTS, IN or JOIN?

Often all three work. WHERE customer_id IN (SELECT customer_id FROM orders WHERE status = 'open') returns the same customers as the example above. The differences show up with duplicates, NULL and the columns you need.

EXISTSINJOIN
QuestionIs there a matching row?Is the value in this list?Combine the rows of both tables
Duplicatesno, each row at most oncenoyes, one row per match
Columns from the second tablenot in the resultnot in the resultyes
NegationNOT EXISTS, safe with NULLNOT IN, empty if the list holds NULLLEFT JOIN with IS NULL

Rule of thumb: if you need columns from the second table, use JOIN. If you only want to filter, use EXISTS. IN works well for short fixed lists and for subqueries whose column can't contain NULL.

In the next exercise a JOIN would return a customer once per matching order line. EXISTS doesn't.

Task The furniture team is inviting customers to a showroom event. Show the name and country of every customer who has ever ordered a product in the 'Furniture' category, whatever the order status. Each customer should appear only once.

customers 12 rows, 7 columns
customer_idnamecitycountrycustomer_sincesegmentphone
1Harbor Fremont PartnersBostonUSA2021-03-15Business617-555-0142
2Emily CarterChicagoUSA2022-07-01ConsumerNULL
3Riverside County OfficeRiversideUSA2020-11-20Government951-555-0110
4Raj PatelLeedsUK2023-01-09Consumer0113 496 0123
5Lakeview Hotel LtdManchesterUK2022-04-18Business0161 496 0456
6Olivia BrooksAustinUSA2024-02-27ConsumerNULL
7Greene & Shaw LLPLondonUK2021-09-05Business020 7946 0321
8Maple Grove High SchoolAustinUSA2023-08-14School512-555-0187
9Chloe EvansBostonUSA2025-05-30Consumer617-555-0199
10Northline Printing CoTorontoCanada2020-06-12Business416-555-0133
11Daniel KimSeattleUSA2024-10-03ConsumerNULL
12Westbrook Dental ClinicChicagoUSA2022-12-01Business312-555-0164
orders 18 rows, 5 columns
order_idcustomer_idorder_datestatusemployee_id
100112026-01-08delivered3
100242026-01-12delivered4
100332026-01-20delivered3
100472026-02-03delivered4
100522026-02-11cancelled8
100612026-02-25delivered3
1007102026-03-04delivered2
100852026-03-17delivered4
100982026-03-30delivered3
101062026-04-07delivered8
1011122026-04-22delivered4
101232026-05-06delivered3
101392026-05-19cancelled8
101472026-06-02shipped4
101512026-06-10shipped3
1016112026-06-12openNULL
101742026-06-13openNULL
1018102026-06-14openNULL
order_items 38 rows, 4 columns
order_idproduct_idquantityunit_price
10011404.79
10013252.79
10016424.9
1002223.49
10021035.49
10031604.69
100311684.9
10033502.59
100443179
100493269
100551449
10061304.79
10067106.99
100782219
100711489.9
10071204.99
100846175
1008253.49
1009101204.99
10092403.19
100992279
1010726.99
1010213.49
1011121129
10111104.99
10113122.79
10126823.9
10121404.69
101391279
101452439
101442179
10151504.79
101511289.9
10161045.49
1017233.49
1017726.99
10181804.79
101861024.9
products 12 rows, 5 columns
product_idnamecategorypricestock
1Copy paper, 500 sheetsPaper4.99420
2Blue ballpoint pens, 10-packWriting3.49310
3Lever arch file, grayFiling2.79185
4Comfort office chairFurniture18912
5Standing deskFurniture4495
6Black ink cartridgePrinter supplies24.964
7Yellow sticky notes, 12 padsWriting6.990
8Mono laser printer L30Electronics2198
927-inch monitorElectronics27915
10Notebook A5, ruledPaper5.49140
11Black toner XLPrinter supplies89.922
12Cross-cut shredderElectronics1290

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

Common mistakes

The subquery isn't tied to the outer row

Without o.customer_id = c.customer_id, the subquery finds the same rows for every customer, and EXISTS is always true. The exercise then reports too many rows, for example "Your query returns 12 rows. Wanted: 9 rows." Comparing o.customer_id = o.customer_id by mistake has the same effect.

NOT IN with NULL in the subquery

If the subquery's column contains even one NULL, NOT IN returns no rows. The exercise says "Your query returns no rows". Switch to NOT EXISTS, or remove the NULLs with IS NOT NULL.

JOIN instead of EXISTS gives duplicates

A JOIN produces one result row for every matching row in the second table. A customer with two matching orders shows up twice. The exercise reports "Your query returns 5 rows. Wanted: 3 rows." EXISTS returns each customer at most once.

EXISTS after a column name

WHERE customer_id EXISTS (…) isn't valid. EXISTS stands on its own in front of the parentheses, and the link to the column goes inside the subquery. Otherwise the exercise reports a syntax error near EXISTS.

EXISTS in MySQL, PostgreSQL, SQL Server and SQLite

EXISTS and NOT EXISTS behave the same in all four databases, correlated or not. The differences are in the details the documentation spells out:

DatabaseColumns in the subqueryNOT IN with NULL
MySQLignored, according to the manual; SELECT *, SELECT 1 and SELECT 5 are all the sameIN returns NULL when no match is found and the list contains NULL; NOT IN is defined as NOT (… IN …)
PostgreSQLnormally unimportant, the usual convention is EXISTS (SELECT 1 …); the subquery generally runs only until one row is foundthe result is NULL, not true, when no value is equal and at least one is NULL
SQL Serverirrelevant, even EXISTS (SELECT NULL) is true as long as there is a rowcomparisons with NULL return UNKNOWN, and the docs warn about unexpected results
SQLite (these exercises)the number of columns and their values have no effect; EXISTS returns 1 or 0NULL when no match is found and the right-hand side contains NULL

Sources: MySQL Reference Manual (Subqueries with EXISTS or NOT EXISTS, Comparison Functions and Operators), PostgreSQL documentation (Subquery Expressions), Microsoft Learn (EXISTS, IN), sqlite.org (SQL Language Expressions).

FAQ

Why SELECT 1 and not SELECT *?

Both are correct and give the same result, because EXISTS only cares whether rows come back. SELECT 1 tells the reader right away that no column is needed.

Is EXISTS faster than IN or JOIN?

It depends on the database and the execution plan; there's no general rule. Pick the form that matches your question. When speed matters, compare the plans in your own database.

Can I do NOT EXISTS with a LEFT JOIN instead?

Yes. LEFT JOIN orders o ON … WHERE o.order_id IS NULL also finds rows without a partner and is just as safe with NULL. Many people find NOT EXISTS easier to read because it states the question directly.

Up next: level 3 project

Now everything from level 3 comes together: an order overview across four tables with LEFT JOIN, GROUP BY and HAVING, and a list of slow-moving products you can solve with LEFT JOIN or NOT EXISTS.

Go to the order overview project

Write to us

Choose language

Select your preferred language