Imagine we need to create a report that shows all orders placed by customers, along with detailed information about the products in each order, including the product names and the quantities ordered. We will also calculate the total cost for each item in the order.
Here’s how you can write this SQL query using INNER JOIN
:
SELECT
c.FirstName,
c.LastName,
o.OrderID,
o.OrderDate,
p.ProductName,
od.Quantity,
p.Price,
(od.Quantity * p.Price) AS ItemTotal
FROM Customers c
INNER JOIN Orders o ON c.CustomerID = o.CustomerID
INNER JOIN OrderDetails od ON o.OrderID = od.OrderID
INNER JOIN Products p ON od.ProductID = p.ProductID
ORDER BY o.OrderDate DESC, o.OrderID, p.ProductName;
c.FirstName, c.LastName
: Customer’s first and last names from the Customers
table.o.OrderID, o.OrderDate
: Order ID and the date the order was placed from the Orders
table.p.ProductName, p.Price
: Product name and price per unit from the Products
table.od.Quantity
: Quantity of each product ordered from the OrderDetails
table.(od.Quantity * p.Price) AS ItemTotal
: Calculates the total cost for each product in the order.INNER JOIN Orders o ON c.CustomerID = o.CustomerID
: Links the Customers
table to the Orders
table by CustomerID
, ensuring we only get orders that have a corresponding customer.INNER JOIN OrderDetails od ON o.OrderID = od.OrderID
: Connects the Orders
table to the OrderDetails
table by OrderID
, allowing us to retrieve details about what was ordered.INNER JOIN Products p ON od.ProductID = p.ProductID
: Links the OrderDetails
table to the Products
table by ProductID
, enabling access to product details for each order item.OrderDate
in descending order to show the most recent orders first.OrderID
and ProductName
to group items in the same order together and sort products alphabetically within each order.Assuming you have populated the tables with relevant data, the output might look something like this:
FirstName | LastName | OrderID | OrderDate | ProductName | Quantity | Price | ItemTotal |
---|---|---|---|---|---|---|---|
John | Doe | 1001 | 2023-04-21 | Luxury Watch | 1 | 500.00 | 500.00 |
John | Doe | 1001 | 2023-04-21 | Designer Bag | 2 | 450.00 | 900.00 |
Jane | Smith | 1002 | 2023-04-20 | Gourmet Chocolate | 5 | 120.00 | 600.00 |
Jane | Smith | 1002 | 2023-04-20 | Organic Tea | 10 | 15.00 | 150.00 |