Joins, subqueries and relational composition
Join semantics, intermediate cardinalities, EXISTS and derived tables.
Cardinality and join semantics
INNER, LEFT, RIGHT, FULL and CROSS define different row-preservation rules. Cardinality depends on key multiplicity: multiple dimension matches multiply fact measures. In an outer join, a predicate in ON restricts matches; in WHERE on the nullable side it can remove preserved rows. Resolve this distinction before physical optimization.
Explicit joins and multiplicity
INNER, LEFT, RIGHT, FULL and CROSS JOIN are recognized. Comma joins with equality predicates are also analyzed. Alias each source and qualify ambiguous columns. Repeated keys on both sides multiply rows; COUNT(*) after a join counts matches, not just left-side rows.
Outer joins produce NULL for missing sides. Moving a predicate from ON to WHERE may remove these rows and change the answer. Two tables do not imply two processes: algorithm, sizes, budgets and plan shape determine parallelism.
SELECT v.Id, c.Nom, v.Montant
FROM dbo.Ventes v LEFT JOIN dbo.Clients c ON v.ClientId = c.ClientId
ORDER BY v.Id;Derived tables and subqueries
Derived tables require an explicit alias after the closing parenthesis. IN, EXISTS and scalar subqueries support correlations to the immediate outer scope. More distant outer scopes are unsupported. A scalar subquery returns one column and at most one row; multiple rows are an error.
SELECT c.ClientId, c.Nom FROM dbo.Clients c
WHERE EXISTS (SELECT 1 FROM dbo.Ventes v WHERE v.ClientId = c.ClientId)
ORDER BY c.ClientId;
SELECT T.Pays, T.total FROM
(SELECT Pays, SUM(Montant) AS total FROM dbo.Ventes GROUP BY Pays) T
ORDER BY T.Pays;UNION, UNION ALL, INTERSECT and EXCEPT
UNION removes duplicates; UNION ALL preserves them. INTERSECT computes a distinct intersection and EXCEPT a distinct difference. INTERSECT ALL and EXCEPT ALL are unsupported. Branches need equal column counts and compatible types; use CAST to disambiguate. Branch order is not an ordering guarantee without final ORDER BY.
COUNT above UNION ALL must count the entire result without an artificial TOP. Equivalent per-branch reductions may optimize the work; other intermediate forms retain explicit limits.
SELECT COUNT(*) AS total FROM (
SELECT Id FROM dbo.Ventes
UNION ALL
SELECT Id FROM dbo.Ventes WHERE ClientId = 1
) T;Control grain before joining
A derived table aggregates measures before attaching them to the dimension. This makes ClientId grain explicit and preserves dimension members without measures through LEFT JOIN. NbValeurs distinguishes groups consisting only of NULL values from groups containing measures.
SELECT c.ClientId, c.Nom, a.NbLignes, a.NbValeurs, a.Total
FROM dbo.Clients AS c
LEFT JOIN (
SELECT ClientId, COUNT(*) AS NbLignes,
COUNT(Montant) AS NbValeurs, SUM(Montant) AS Total
FROM dbo.Ventes
GROUP BY ClientId
) AS a ON a.ClientId = c.ClientId
ORDER BY c.ClientId;