On this page
  1. Joins & Set Operations
  2. Contents
  3. Join Types & Anti-Joins
  4. LEFT JOIN Filter Placement Gotcha
  5. Set Operations (UNION, INTERSECT, EXCEPT)

Joins & Set Operations

Prev: DML & Querying | Up: sql | Next: Aggregations, CTEs & Window Functions
Rel: SQL Query Execution Lifecycle, Indexing & Storage Engines
Ref: PostgreSQL — Table Expressions
Tags: #public #databases #sql #joins


Contents


Join Types & Anti-Joins

Join Rows Returned
INNER JOIN Only matching pairs from both tables
LEFT JOIN All left rows + matching right rows (or NULLs)
FULL OUTER JOIN All rows from both sides, padded with NULLs
CROSS JOIN Cartesian product ($M \times N$)

Find rows with no match using NOT EXISTS (cleanest and NULL-safe) or a LEFT JOIN ... WHERE right.id IS NULL anti-join:

SELECT u.id, u.email
FROM users u
WHERE NOT EXISTS (
  SELECT 1 FROM orders o WHERE o.user_id = u.id
);

LEFT JOIN Filter Placement Gotcha

Filtering a right-table column in WHERE turns a LEFT JOIN into an INNER JOIN (dropping unmatched NULL rows). Place right-table filters in the ON clause instead:

SELECT u.email, o.total_cents
FROM users u
LEFT JOIN orders o
  ON o.user_id = u.id AND o.total_cents > 5000;

Set Operations (UNION, INTERSECT, EXCEPT)

Linked from

Related notes