SQL / MySQL Intermediate Queries · 6 min read

SQL EXISTS for a Membership Test

Lesson 24 of 33 in the SQL / MySQL learning path.

How do I find lessons that have at least one confirmed seat?

EXISTS is true when the subquery returns any row. It does not care how many.

A join would repeat the lesson once per student. EXISTS answers the yes-or-no question and keeps one lesson row.

Syntax & Parameters

Syntax
WHERE EXISTS (SELECT 1 FROM enrollments e WHERE e.lesson_id = l.id)

Example

queries.sql
-- Published lessons that already have a confirmed seat.
SELECT l.id, l.title
FROM lessons AS l
WHERE l.published_at IS NOT NULL
  AND EXISTS (
    SELECT 1
    FROM enrollments AS e
    WHERE e.lesson_id = l.id
      AND e.status = 'confirmed'
  )
ORDER BY l.title;
-- One lesson row, even when many students confirmed.

Expected Output

One row per published lesson that has at least one confirmed enrollment, ordered by title.

Line-by-Line Walkthrough

  1. The outer query lists published lessons.
  2. EXISTS runs a correlated subquery per candidate lesson.
  3. SELECT 1 shows we only care that a row exists.
  4. The subquery matches enrollment.lesson_id to the outer lesson.
  5. status confirmed ignores pending seats.
  6. The lesson appears once even if 30 students confirmed.
  7. ORDER BY title is applied to the lessons, not the seats.
  8. An index on enrollments(lesson_id, status) keeps this cheap.

Common Pitfalls & Security

Watch the failure mode, not only the happy path.

  • A join plus DISTINCT hides the duplication instead of asking the real question.
  • Forgetting the correlation returns lessons whenever any enrollment exists.
  • NOT EXISTS is the way to find lessons with no confirmed seats. A left join with IS NULL is the other spelling.
  • SELECT * in the subquery wastes work. SELECT 1 is enough.

Best Practices & Modern Standards

Use EXISTS for a membership test and a join when you need columns from both tables.

Index the columns in the subquery predicate.

Real-World Use

The public catalog lists only published lessons that already have a confirmed student, without repeating the lesson title once per student.

Frequently Asked Questions

Does EXISTS return the inner columns?

No. It returns true or false to the outer WHERE.

Why SELECT 1?

The inner select list is ignored. 1 documents that you are not reading those columns.

How do I find lessons with nobody?

Use NOT EXISTS with the same correlation.

Is this slower than a join?

Often it stops at the first matching child. A join builds the full pair list.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…