SQL JOINs, explained

Real databases split data across tables. An orders table stores a customer_id rather than the customer's name. A JOIN matches rows from two tables using a condition, usually an id.

An INNER JOIN (or just JOIN) keeps only rows that have a match on both sides. A LEFT JOIN keeps every row from the left table and fills in NULL when nothing matches.

Examples

1. Orders with customer names

SELECT o.id, c.name, o.total
FROM orders o
JOIN customers c ON c.id = o.customer_id;

o and c are short aliases for the two tables.

2. Customers who never ordered

SELECT c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL;

LEFT JOIN keeps every customer. Rows with no order have NULL on the orders side.

Practice JOINs

5 questions, easiest first. Your progress is saved on this device.

  • โ—‹Orders with namesmedium
  • ๐Ÿ”’Join, then filtermedium
  • ๐Ÿ”’Include everyonehard
  • ๐Ÿ”’Never orderedhard
  • ๐Ÿ”’Follow the chainhard
Practice JOINs