Brightlane's customer service team is assembling a case-management report and needs order records matched to the customers who placed them.
Write a query to return the customer name, order ID, and order total for every order.
Assumptions:
- Every order has a valid
customer_id, so every order will appear in the result.
Output:
- One row per order, with columns
customer_name,order_id, andtotal_amount.
Schema · ecommerce 5 tables
Run previews · Check grades
Write a query, then run it to see results here.
Worked solution Try it yourself first
SELECT
c.name AS customer_name,
o.id AS order_id,
o.total_amount
FROM
orders o
JOIN customers c ON o.customer_id = c.id The shape
The orders table carries a customer_id reference, and the customers table carries the matching id. JOIN ... ON o.customer_id = c.id pairs each order with its customer, so a single row in the result holds the order ID, the total, and the customer's name side by side.
Clause by clause
FROM orders oreads from the orders table and aliases it aso. The aliasing matters here becauseordersandcustomersboth have anidcolumn, and unqualified references toidwould be ambiguous.JOIN customers c ON o.customer_id = c.idis the assembly. For each row inorders, PostgreSQL finds the row incustomerswhoseidequals that order'scustomer_id, and emits a combined row. Because every order has a validcustomer_id, every order appears exactly once in the result.200orders in,200rows out.SELECT c.name AS customer_name, o.id AS order_id, o.total_amountpicks three columns from the combined row: the customer's name from thecustomersside, the order's ID from theordersside, and the total from the order. Every column reference is prefixed by its alias, and the two ID columns get explicit aliases (customer_name,order_id) so the result row reads as a case-management report rather than two unqualifiedidcolumns next to each other.
You practiced an INNER JOIN between two tables on a foreign-key/primary-key match. The recurring shape: when a fact (an order) holds a reference to a parent entity (a customer) and the report needs columns from both, JOIN ... ON foreign_key = primary_key is the assembly mechanism.