SQL EXISTS

Test whether a subquery returns rows.

✍️ 3 exercises + code challenge in this lesson

EXISTS returns true if a subquery returns at least one row. It is often faster than IN for large tables because it stops at the first match.

NOT EXISTS finds rows with no related records.

Key Takeaways: SQL EXISTS

Mastering SQL EXISTS helps you write clean and reliable SQL code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

SQL EXISTS Code Example

SQL
-- Products that have been ordered at least once
SELECT ProductName FROM Products p
WHERE EXISTS (SELECT 1 FROM OrderItems i WHERE i.ProductID = p.ProductID);

-- Products never ordered
SELECT ProductName FROM Products p
WHERE NOT EXISTS (SELECT 1 FROM OrderItems i WHERE i.ProductID = p.ProductID);
Free sign-in required · Google login available

SQL EXISTS Practice Exercises

Check what you learned in “SQL EXISTS”.

/ 3 solved
Fill in the blank

Find customers that have at least one order.

WHERE  (SELECT 1 FROM Orders o WHERE o.CustomerID = c.CustomerID)
✓ Correct! Not quite. Try again.
Multiple choice

EXISTS returns true when the subquery…

✓ Correct! Not quite. Try again.
Code challenge

Select CustomerName of customers who have never placed an order, using NOT EXISTS, sorted by name.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services