Joining tables with INNER JOIN
SQL · 15 questions
Short notes
Key idea
An inner join puts rows from two tables side by side where a key matches. Rows with no match on the other side disappear.
Syntax
SELECT o.order_id, c.name, o.amount
FROM orders AS o
JOIN customers AS c ON c.customer_id = o.customer_id;
JOIN and INNER JOIN are the same. Table aliases (o, c) keep it short.
Example
Revenue per customer name:
SELECT c.name, SUM(o.amount) AS revenue
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
GROUP BY c.name;
Traps
- Duplicate keys multiply rows. If a customer appears twice in
customers, each of their orders appears twice, and sums double. - Ambiguous columns: when both tables have
id, writeo.idorc.id. - Forgetting the
ON(or using a comma join withoutWHERE) gives every pair of rows: a cross join. - Rows silently vanish when a key is missing or NULL. Count rows before and after joining.
Want the full lesson with step-by-step examples, a project and a certificate? SQL course, ₹120 →
- Question 1easy
Which rows does an
INNER JOINreturn? - Question 2medium
SELECT customer_id FROM orders o JOIN customers c ON o.customer_id = c.customer_idfails. Why? - Question 3medium
There are 40 customers. 9 of them never placed an order. What does this return?
SELECT COUNT(DISTINCT c.customer_id) FROM customers c JOIN orders o ON o.customer_id = c.customer_id;
- Question 4hard
There are 80 orders and 166 order lines. What does this return?
SELECT COUNT(*) FROM orders o JOIN order_items oi ON oi.order_id = o.order_id;
- Question 5easy
What's the difference between
JOINandINNER JOIN?
Joining tables with INNER JOIN
Joining tables with INNER JOIN
Joining tables with INNER JOIN
Joining tables with INNER JOIN
Joining tables with INNER JOIN
10 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.