Learn SQL/Advanced/Interview Patterns/SQL Semi-Join Pattern

SQL Semi-Join Pattern

The opposite of anti-join — rows from A that DO have a match in B, without duplicating them.

What & Why

A semi-join returns rows from table A that have at least one match in table B — but each A row appears only once, even if it matches multiple B rows. EXISTS and IN naturally produce this; a regular JOIN does not (it duplicates A rows per match).

See How It Works

BUSINESS QUESTION

List product features that have received feedback.

idnamedescriptionteamreleased_atdeprecated_at
1Activation ChecklistGuides new users through setupgrowth2024-01-20NULL
2CSV ExportExports report dataplatform2024-02-14NULL
3Invite NudgesPrompts workspace collaborationgrowth2024-03-05NULL
4Legacy DashboardOriginal reporting surfaceanalytics2023-08-102024-06-01
iduser_idfeature_idratingnps_scorecommentcreated_at
1101159Clear and useful2024-01-25 12:15:00+00
210224NULLExport worked well2024-02-20 15:40:00+00
3103147Helpful setup flow2024-03-18 09:05:00+00
410433NULLNeeds clearer timing2024-04-08 17:30:00+00
EXAMPLE QUERY
SELECT
  f.id,
  f.name,
  f.team
FROM product.features f
WHERE EXISTS (
  SELECT 1
  FROM product.feedback fb
  WHERE fb.feature_id = f.id
)
ORDER BY f.name;
RESULT — features with feedback
idnameteam
1Activation Checklistgrowth
2CSV Exportplatform
3Invite Nudgesgrowth

EXISTS preserves feature grain even when a feature has multiple feedback rows.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario