Choose INNER, LEFT and CROSS JOIN by the Rows You Need
A join combines rows according to a relationship or produces all combinations. The join type controls which unmatched rows remain. It does not guarantee a one-to-one relationship. The keys, matching data and predicate determine how many rows are produced.
Prepare Two Small Rowsets
Run the following sections together in one batch so that the variables remain available:
DECLARE @Customers TABLE (CustomerId int PRIMARY KEY, Name nvarchar(30));
DECLARE @Orders TABLE (OrderId int PRIMARY KEY, CustomerId int);
INSERT @Customers VALUES (1, N'Ada'), (2, N'Ben'), (3, N'Cleo');
INSERT @Orders VALUES (101, 1), (102, 1), (103, 2);
Ada has two orders, Ben has one and Cleo has none.
Return Matches with INNER JOIN
SELECT c.Name, o.OrderId
FROM @Customers AS c
INNER JOIN @Orders AS o ON o.CustomerId = c.CustomerId
ORDER BY c.CustomerId, o.OrderId;
This returns three rows. Ada appears twice because two orders match. An inner join is therefore not inherently one-to-one. If the join key is duplicated on both sides, every matching pair contributes a row.
Preserve Every Customer with LEFT JOIN
SELECT c.Name, o.OrderId
FROM @Customers AS c
LEFT JOIN @Orders AS o ON o.CustomerId = c.CustomerId
ORDER BY c.CustomerId, o.OrderId;
This returns four rows, including Cleo with a null OrderId. To keep all customers while selecting only qualifying orders, place that qualification in ON:
SELECT c.Name, o.OrderId
FROM @Customers AS c
LEFT JOIN @Orders AS o
ON o.CustomerId = c.CustomerId AND o.OrderId >= 102
ORDER BY c.CustomerId, o.OrderId;
The result contains Ada/102, Ben/103 and Cleo/null. Moving o.OrderId >= 102 into WHERE would remove the unmatched Cleo row. A right join preserves the right side and can often be written more readably as a left join by swapping the inputs. A full outer join preserves unmatched rows from both.
Generate Combinations with CROSS JOIN
SELECT c.Name, d.DayName
FROM @Customers AS c
CROSS JOIN (VALUES (N'Monday'), (N'Tuesday')) AS d(DayName)
ORDER BY c.CustomerId, d.DayName;
Three customers and two days produce six rows. Use this deliberately for a small combination set. An accidental cross join on large inputs can expand the result dramatically. Before using DISTINCT to suppress unexpected duplicates, verify the intended keys and missing join predicates.
Microsoft References
Author: Herman Schoenfeld