SQL Joins Explained: INNER, LEFT, RIGHT, and FULL, With Examples
Introduction Most real data lives in more than one table. Users live in one table, orders in another, and the link between them is usually an ID, like user_id . A join combines rows from two tables based on that link, so you can ask questions like "show me each order, with the name of the person who placed it." There are four joins you need first. They differ only in which rows they keep when there is no match. The example tables -- users -- id | name -- 1 | Ali -- 2 | Sara -- 3 | Omar -- orders -- id | user_id | item -- 1 | 1 | Keyboard -- 2 | 1 | Mouse -- 3 | 2 | Monitor Ali has two orders, Sara has one, Omar has none, and every order belongs to a user in this example. INNER JOIN — only matching rows An INNER JOIN keeps only rows that match in both tables. Omar disappears here, because he has no orders. SELECT users.name, orders.item FROM users INNER JOIN orders ON users.id = orders.user_id; Result: name | item Ali | Keyboard Ali | Mouse ...