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

Finding What's Missing with NOT EXISTS

This lesson covers finding "missing" data with NOT EXISTS, so you can efficiently locate rows with no related records. It's for anyone searching "SQL NOT EXISTS tutorial."

NOT EXISTS(subquery) evaluates to true when the subquery returns zero rows — useful for something like "books that have never been checked out," where you're looking for the complete absence of related data.

The example uses WHERE NOT EXISTS (SELECT 1 FROM loans l WHERE l.book_id = b.id) to find books with zero loan records — the exact mirror image of the EXISTS pattern from an earlier lesson.

A common early mistake is not knowing when NOT IN and NOT EXISTS diverge — they can look interchangeable, but they behave differently when NULL shows up among the compared values, and NOT EXISTS is generally the safer default in practice. This is the mirror image of EXISTS, purpose-built for efficiently finding "records with absolutely no related data" — a routine data-maintenance task, like flagging inventory items that have never been ordered.

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)