After this lesson, you will be able to: Use INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN, CROSS JOIN and reason about them visually.
JOINs are how relational databases earn their name. The biggest divider between 'wrote a few queries' and 'productive SQL engineer.'
Returns rows where BOTH tables have a match.
-- Users with their postsSELECT u.id, u.name, p.titleFROM users uINNER JOIN posts p ON p.user_id = u.id;-- 'INNER' is optional; just `JOIN` means INNER JOINSELECT u.id, u.name, p.titleFROM users uJOIN posts p ON p.user_id = u.id;-- Users with no posts are excluded (no matching post row)
Returns all rows from the left table, NULL for right when no match.
-- All users, including those with no postsSELECT u.id, u.name, p.titleFROM users uLEFT JOIN posts p ON p.user_id = u.id;-- Users with no posts have NULL in title column-- Common pattern: 'find left rows with NO match on right'SELECT u.id, u.nameFROM users uLEFT JOIN posts p ON p.user_id = u.idWHERE p.id IS NULL;-- Users who have never posted
Less common; useful for reconciling two lists.
-- Compare two product lists (e.g., new catalog vs old)SELECT n.sku, n.name AS new_name, o.name AS old_nameFROM new_catalog nFULL OUTER JOIN old_catalog o ON n.sku = o.skuWHERE n.sku IS NULL OR o.sku IS NULL;-- Returns: products only in new, or only in old
Chain JOINs as needed.
-- Users + posts + commentsCREATE TABLE comments (id SERIAL PRIMARY KEY,post_id INT REFERENCES posts(id),author_id INT REFERENCES users(id),body TEXT,created_at TIMESTAMPTZ DEFAULT NOW());SELECT u.name AS post_author, p.title, c.body AS comment, cu.name AS commenterFROM users uJOIN posts p ON p.user_id = u.idLEFT JOIN comments c ON c.post_id = p.idLEFT JOIN users cu ON cu.id = c.author_idWHERE p.published = TRUE;
INNER JOIN when you needed LEFT JOIN → quietly drops rows. Putting LEFT JOIN's right-side condition in WHERE (cancels the LEFT-ness, becomes INNER). Cartesian product from missing ON clause (10M rows from 1k × 10k). Ambiguous column names without table alias (`SELECT id FROM users JOIN posts`, which id?).
Sign in and purchase access to unlock this lesson.