Filter Related SQL Server Rows with IN and EXISTS
A subquery can express a relationship without adding the related table's columns to the result. IN tests membership in a set of values. EXISTS tests whether a related query produces at least one row, which avoids multiplying the outer rows when several matches exist.
Create a Reproducible Dataset
Run all sections in the same batch:
DECLARE @Manufacturers TABLE (ManufacturerId int PRIMARY KEY, Name nvarchar(30));
DECLARE @Products TABLE (ProductId int PRIMARY KEY, ManufacturerId int NULL, Model nvarchar(30));
INSERT @Manufacturers VALUES (1, N'North'), (2, N'South');
INSERT @Products VALUES (10, 1, N'Compact'), (11, 1, N'Pro'),
(12, 2, N'Lite'), (13, NULL, N'Unassigned');
Test Membership with IN
SELECT p.ProductId, p.Model
FROM @Products AS p
WHERE p.ManufacturerId IN
(
SELECT m.ManufacturerId
FROM @Manufacturers AS m
WHERE m.Name = N'North'
)
ORDER BY p.ProductId;
This returns products 10 and 11. Qualify column names with aliases. A misspelled inner column can sometimes bind to an outer query's column, creating a valid but unintended correlated query.
Test Related Presence with EXISTS
SELECT m.ManufacturerId, m.Name
FROM @Manufacturers AS m
WHERE EXISTS
(
SELECT 1
FROM @Products AS p
WHERE p.ManufacturerId = m.ManufacturerId
)
ORDER BY m.ManufacturerId;
Each manufacturer appears once even though North has two products. The expression SELECT 1 communicates that only the presence of a row matters.
Find Missing Relationships with NOT EXISTS
SELECT p.ProductId, p.Model
FROM @Products AS p
WHERE NOT EXISTS
(
SELECT 1
FROM @Manufacturers AS m
WHERE m.ManufacturerId = p.ManufacturerId
)
ORDER BY p.ProductId;
This returns product 13 because its null manufacturer has no equal match. Add p.ManufacturerId IS NOT NULL to the outer predicate if unassigned products should be excluded.
NOT IN behaves differently when its subquery returns a null. Comparisons can become UNKNOWN and remove rows you expected to keep. Prefer NOT EXISTS for an absence test, while still defining your desired treatment of null outer values. A scalar subquery used with = must return at most one value, and errors if it returns multiple rows. Choose the construct that matches the data contract rather than replacing all subqueries with joins mechanically.
Microsoft References
Author: Herman Schoenfeld