Ad space (banner)
🗄️SQL Lessons
Lesson 21 / 50

Checking Existence with EXISTS

This lesson covers checking whether related data exists using EXISTS, so you can filter efficiently based on presence alone. It's for anyone searching "SQL EXISTS tutorial."

EXISTS(subquery) evaluates to true as soon as the subquery returns at least one row — perfect for "only books that have at least one loan record," where you care about presence, not the actual value.

The example uses WHERE EXISTS (SELECT 1 FROM loans l WHERE l.book_id = b.id) to find books with at least one loan. The 1 inside SELECT 1 has no special meaning — it's just a conventional way to say "I only care whether this returns anything."

A common early mistake is not knowing when to reach for EXISTS over IN — they can produce similar results, but EXISTS only checks "does at least one row exist," rather than evaluating the subquery's actual values, which often makes it faster on large datasets. Deciding behavior based on "does a related record exist" comes up constantly in inventory and lending systems, so mastering EXISTS makes these existence checks much more efficient.

SQL
OUTPUT

💡 The SQL engine may take a few seconds to load the first time you run code.

Ad space (banner)
Ad space (in-article)