Solving tips
- Chain joins one table at a time, always joining the new table on a key already present in the growing result.
- Each ON clause connects exactly two tables; the orders table is the hub linking customers to products.
- Compute derived values like line totals in the SELECT after the joins have paired the rows.
An order links a customer to a product. Produce a readable line item for each order.
Schema
CREATE TABLE customers (
id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL
);
CREATE TABLE products (
id INT PRIMARY KEY,
product_name VARCHAR(50) NOT NULL,
price NUMERIC(10,2) NOT NULL
);
CREATE TABLE orders (
id INT PRIMARY KEY,
customer_id INT REFERENCES customers(id),
product_id INT REFERENCES products(id),
quantity INT NOT NULL
);
customers
| id | name |
|---|---|
| 1 | Alice |
| 2 | Bob |
| 3 | Carol |
products
| id | product_name | price |
|---|---|---|
| 100 | Keyboard | 25.00 |
| 200 | Mouse | 15.00 |
| 300 | Monitor | 150.00 |
orders
| id | customer_id | product_id | quantity |
|---|---|---|---|
| 1 | 1 | 100 | 2 |
| 2 | 1 | 200 | 1 |
| 3 | 2 | 300 | 1 |
| 4 | 3 | 100 | 3 |
Task
Return one row per order with columns customer_name, product_name, quantity, and line_total (equal to quantity * price). Order by customer_name ascending, then product_name ascending.
Expected output
| customer_name | product_name | quantity | line_total |
|---|---|---|---|
| Alice | Keyboard | 2 | 50.00 |
| Alice | Mouse | 1 | 15.00 |
| Bob | Monitor | 1 | 150.00 |
| Carol | Keyboard | 3 | 75.00 |