Joins and set operations
Join keys and relationship cardinality
Match orders to customers and reason about one-to-many relationships.
Lesson 32 of 84
Reading: about 2 min
Lesson + practice: about 12 min
Difficulty: Intermediate
On this page4 sections
This lesson uses the unmodified DDI_SQL_Training dataset v1.0.0 on SQL Server 2019 or later. Match orders to customers and reason about one-to-many relationships.
Run the example
SELECT TOP (5) o.OrderID, o.CustomerID, c.FirstName
FROM dbo.Orders AS o
JOIN dbo.Customers AS c ON c.CustomerID = o.CustomerID
ORDER BY o.OrderID;Read it step by step
- Orders.CustomerID is a foreign key to the unique Customers.CustomerID.
- Each order matches one customer; one customer can match many orders.
- The join adds the customer name, and ORDER BY selects a repeatable five-order sample.
Check the result
| OrderID | CustomerID | FirstName |
|---|---|---|
| 1 | 1 | Alex |
| 2 | 2 | Maya |
| 3 | 3 | Leo |
| 4 | 4 | Isla |
| 5 | 5 | Ravi |
The result grain remains one row per selected order because CustomerID is unique on the customer side.
Practice
Show the two order-item lines for OrderID 1, including each line’s ProductID.
Check your answer and expected result
Reveal answer
SELECT o.OrderID, i.LineNumber, i.ProductID
FROM dbo.Orders AS o
JOIN dbo.OrderItems AS i ON i.OrderID = o.OrderID
WHERE o.OrderID = 1
ORDER BY i.LineNumber;| OrderID | LineNumber | ProductID |
|---|---|---|
| 1 | 1 | 1 |
| 1 | 2 | 6 |
Order 1 has two lines: the one-to-many join returns two rows for one order.
Your progress
Reveal the check answer or reach the end to complete this lesson.