JOINs (INNER, LEFT, RIGHT)
JOINs combine rows from two tables using a related column. INNER JOIN returns only rows that match in both tables. LEFT JOIN returns every row from the left table, with NULL where there's no match. RIGHT JOIN is the same idea but keeps every row from the right table.
-- Users who have posts SELECT users.name, posts.title FROM users INNER JOIN posts ON posts.user_id = users.id; -- All users, even ones without posts (title will be NULL) SELECT users.name, posts.title FROM users LEFT JOIN posts ON posts.user_id = users.id; -- Short aliases SELECT u.name, COUNT(p.id) AS post_count FROM users u LEFT JOIN posts p ON p.user_id = u.id GROUP BY u.name;