INNER JOIN with ON
SELECT *FROM customersINNER JOIN orders ON customers.id = orders.customer_id;- Problem: SELECT * returns both id columns and every column you do not need
You have customers and orders.
Table: customers
| id | name |
|---|---|
| 1 | Ana |
| 2 | Raj |
| 3 | Mei |
Table: orders
| id | customer_id | total |
|---|---|---|
| 101 | 1 | 50 |
| 102 | 1 | 30 |
| 103 | 2 | 70 |
Task
Write a query that returns only the rows where a customer has a matching order: the customer name, the order id and the total.
Expected output
| name | order_id | total |
|---|---|---|
| Ana | 101 | 50 |
| Ana | 102 | 30 |
| Raj | 103 | 70 |
Work out your query on your own, then open Answers & Optimization to compare.
Found a mistake in this question?
Report a problemA basic answer first, then the optimized one.
INNER JOIN keeps only rows with a match on the join condition. Mei has no orders, so she is dropped.ON handles any condition. USING (col) is a shorthand when both columns share a name.SELECT *FROM customersINNER JOIN orders ON customers.id = orders.customer_id;CREATE INDEX idx_orders_customer_id ON orders (customer_id); SELECT c.name, o.id AS order_id, o.totalFROM customers cJOIN orders o ON o.customer_id = c.id; -- Only customer columns needed? A semi-join returns each customer once, no duplicatesSELECT c.id, c.nameFROM customers cWHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);Log in to mark questions completed and keep your streak.
Log inSpotted a mistake in these answers?
Report a problem