Joins and set operations
INNER JOIN
Return rows whose keys match in both related tables.
Lesson 33 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. Return rows whose keys match in both related tables.
Run the example
sql
SELECT TOP (5) p.ProductID, p.ProductName, c.CategoryName
FROM dbo.Products AS p
INNER JOIN dbo.Categories AS c ON c.CategoryID = p.CategoryID
ORDER BY p.ProductID;Read it step by step
- Products.CategoryID references the Categories primary key.
- INNER JOIN retains product rows with a matching category.
- ORDER BY ProductID selects five predictable products from the joined set.
Check the result
| ProductID | ProductName | CategoryName |
|---|---|---|
| 1 | Laptop Stand | Computing |
| 2 | USB-C Dock | Computing |
| 3 | Webcam | Computing |
| 4 | Notebook | Office |
| 5 | Pen Set | Office |
All canonical products have a category because the foreign key requires it.
Practice
Show OrderID, CustomerID, and FirstName for Orders 1 through 3.
Check your answer and expected result
Reveal answer
sql
SELECT o.OrderID, o.CustomerID, c.FirstName
FROM dbo.Orders AS o
INNER JOIN dbo.Customers AS c ON c.CustomerID = o.CustomerID
WHERE o.OrderID BETWEEN 1 AND 3
ORDER BY o.OrderID;| OrderID | CustomerID | FirstName |
|---|---|---|
| 1 | 1 | Alex |
| 2 | 2 | Maya |
| 3 | 3 | Leo |
Each of the three orders matches one customer.
Your progress
Reveal the check answer or reach the end to complete this lesson.