SQL / MySQL Advanced Queries · 6 min read

SQL INTERSECT

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

How do I find users who both teach and enroll?

INTERSECT returns rows that are in both SELECT results. Duplicates are collapsed.

A join can do this too. INTERSECT states that you want the overlap of two sets.

Syntax & Parameters

Syntax
SELECT user_id FROM lessons INTERSECT SELECT user_id FROM enrollments

Example

queries.sql
SELECT user_id
FROM lessons
WHERE published_at IS NOT NULL
INTERSECT
SELECT user_id
FROM enrollments
WHERE status = 'confirmed'
ORDER BY user_id;
-- MySQL 8.0.31 and later support INTERSECT.
-- Both selects must have the same column count and compatible types.
-- The result is the overlap, not the union.
-- An inner join on user_id is the older spelling.
-- INTERSECT removes duplicate ids.

Expected Output

User ids who published a lesson and also have a confirmed enrollment, once each.

Line-by-Line Walkthrough

  1. The first query lists owners of published lessons.
  2. INTERSECT keeps only ids that also appear in the second query.
  3. The second query lists users with a confirmed enrollment.
  4. ORDER BY applies to the combined result.
  5. Column counts must match.
  6. Types must be compatible.
  7. Duplicate ids collapse.
  8. Older MySQL versions need an inner join instead.

Common Pitfalls & Security

Know the failure before you copy it.

  • INTERSECT is not available on old MySQL. Check the version.
  • Different column counts are a syntax error.
  • NULL equals NULL inside INTERSECT in a way people do not expect. Know your engine.
  • A huge overlap without indexes on both sides is a large temporary table.

Best Practices & Modern Standards

Use INTERSECT when you mean set overlap and the engine supports it.

Fall back to an inner join of two derived tables on older MySQL.

Real-World Use

A report lists people who both teach a published course and sit in someone else’s confirmed enrollment.

Frequently Asked Questions

How is this different from UNION?

UNION stacks sets. INTERSECT keeps only the overlap.

Does it keep duplicates?

No. Each matching row appears once.

What MySQL version?

8.0.31 added INTERSECT.

Can I intersect three queries?

Yes. Chain another INTERSECT. All three selects must share a shape.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…