JOINs combine rows from related tables.
Types
INNER JOIN� matching rows onlyLEFT JOIN� all left rows + matchesRIGHT JOIN� all right rows + matches
ON Clause
Specifies the relationship between tables.
JOINs combine rows from related tables.
INNER JOIN � matching rows onlyLEFT JOIN � all left rows + matchesRIGHT JOIN � all right rows + matchesSpecifies the relationship between tables.
SELECT u.name, o.total FROM users u INNER JOIN orders o ON u.id = o.user_id; SELECT u.name, COALESCE(SUM(o.total), 0) AS spent FROM users u LEFT JOIN orders o ON u.id = o.user_id GROUP BY u.id;
-- INNER JOIN (only matches) SELECT u.name, o.amount FROM users u INNER JOIN orders o ON o.user_id = u.id; -- LEFT JOIN (all users, even without orders) SELECT u.name, COALESCE(o.amount, 0) AS amount FROM users u LEFT JOIN orders o ON o.user_id = u.id; -- RIGHT JOIN SELECT o.id, u.name FROM orders o RIGHT JOIN users u ON o.user_id = u.id; -- JOIN with 3 tables SELECT u.name, p.title FROM users u JOIN enrollments e ON e.user_id = u.id JOIN courses p ON p.id = e.course_id;
Find users who never ordered.
SELECT u.name FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE o.id IS NULL;
Which JOIN returns all rows from both tables?
FULL OUTER JOIN returns all rows from both tables.
INNER returns only matching rows. LEFT returns all left rows, with NULLs for non-matching right rows.