Interview question
Filter orders by line item without duplicate orders
Uses EXISTS instead of a row-multiplying join when the related table is only a filter.
TL;DR
Uses EXISTS instead of a row-multiplying join when the related table is only a filter.
One-to-many cardinality, existence filters, duplicate avoidance, stable ordering, and pagination-ready query shape.
Practice the problem like a real interview: restate, reason, implement, and test.
Tables: Orders(OrderId, CustomerId, CreatedAt, Status) and OrderLines(OrderLineId, OrderId, ProductId, Quantity). Return each non-cancelled order containing @ProductId, newest first. Use OrderId as the tie-breaker.
Order 10 contains the requested product on two separate lines. It still appears once. Order 11 has no matching line and does not appear.
DISTINCT as a patch for an unnecessary row-multiplying join.Because no line columns are needed in the result, I model the related table as an existence condition. The correlated subquery answers yes or no for each order and cannot multiply the order row. A composite index on OrderLines(ProductId, OrderId) supports starting from the selective product filter; the reverse order can be better when the query normally starts from a small page of orders.
SELECT o.OrderId, o.CustomerId, o.CreatedAt, o.Status
FROM dbo.Orders AS o
WHERE o.Status <> 'Cancelled'
AND EXISTS
(
SELECT 1
FROM dbo.OrderLines AS ol
WHERE ol.OrderId = o.OrderId
AND ol.ProductId = @ProductId
)
ORDER BY o.CreatedAt DESC, o.OrderId DESC;
The best index order depends on whether product selectivity or the outer order page drives the plan. The important shape is a semi-join: one qualifying match is enough, and no deduplication step is required.
CreatedAt.DISTINCT without understanding why duplicates appeared.Move to the linked follow-up, next path step, prerequisite, or deeper variant.
Practice the next layer of the same subject.