INNER JOIN and LEFT JOIN in SQL
Combine rows from two tables. Press Run to try it, then change the code and run it again.
CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER, amount INTEGER);
INSERT INTO customers VALUES (1, 'Asha'), (2, 'Rohan'), (3, 'Mei');
INSERT INTO orders VALUES (1, 1, 500), (2, 1, 1200), (3, 2, 300);
-- Only customers with orders
SELECT c.name, o.amount
FROM customers c
INNER JOIN orders o ON o.customer_id = c.id;
-- Every customer, with their total (0 if none)
SELECT c.name, COALESCE(SUM(o.amount), 0) AS total
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id;
Output
Press Run to see the output.
More SQL examples
- Create a table and select rows · Make a table, add rows and read them back.
- GROUP BY and HAVING · Summarise rows per group and filter the groups.
- Second highest salary · A classic interview question, solved two ways.
- Window functions · Rank rows within each group without collapsing them.
- Common table expressions (WITH) · Name a subquery and build on it step by step.