RUN

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.

main.sql

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

Open the full SQL online compiler →