sqlglot icon indicating copy to clipboard operation
sqlglot copied to clipboard

optimize_joins: comma join rewritten to CROSS JOIN changes join grouping, wrong rows with RIGHT/FULL JOIN

Open chaitanyachaudhary30 opened this issue 3 weeks ago • 2 comments

Read dialect: duckdb Write dialect: duckdb Version: 30.31.0 (PyPI) and main at 539d7b9

optimize changes the result of a query that mixes a comma join with a RIGHT JOIN or FULL JOIN. optimize_joins rewrites the comma as CROSS JOIN, and that changes how the joins are grouped.

In FROM a, b RIGHT JOIN c ON ..., JOIN binds more tightly than the comma, so the query means a, (b RIGHT JOIN c ON ...). After the rewrite it is a CROSS JOIN b RIGHT JOIN c ON ..., which groups left to right as (a CROSS JOIN b) RIGHT JOIN c ON .... For an inner or left join the two groupings give the same rows, but not for RIGHT and FULL.

Fully reproducible code snippet

import duckdb
from sqlglot.optimizer import optimize

con = duckdb.connect()
con.execute("CREATE TABLE a AS SELECT * FROM (VALUES (1), (2)) t(x)")
con.execute("CREATE TABLE b AS SELECT * FROM (VALUES (10)) t(y)")
con.execute("CREATE TABLE c AS SELECT * FROM (VALUES (10), (20)) t(z)")

sql = "SELECT * FROM a, b RIGHT JOIN c ON b.y = c.z"
schema = {"a": {"x": "INT"}, "b": {"y": "INT"}, "c": {"z": "INT"}}
optimized = optimize(sql, schema=schema, dialect="duckdb").sql("duckdb")

print(optimized)
print(sorted(con.execute(sql).fetchall(), key=str))
print(sorted(con.execute(optimized).fetchall(), key=str))

Output:

SELECT "a"."x" AS "x", "b"."y" AS "y", "c"."z" AS "z" FROM "a" AS "a" CROSS JOIN "b" AS "b" RIGHT JOIN "c" AS "c" ON "b"."y" = "c"."z"
[(1, 10, 10), (1, None, 20), (2, 10, 10), (2, None, 20)]
[(1, 10, 10), (2, 10, 10), (None, None, 20)]

The original query returns 4 rows: the unmatched c row (z = 20) is paired with every row of a. The optimized query returns 3 rows, and the unmatched row has x = NULL.

The same happens with FULL JOIN. DuckDB (2.0.0) agrees with the grouping described above: SELECT * FROM a, (b RIGHT JOIN c ON b.y = c.z) returns the 4 rows, and SELECT * FROM (a CROSS JOIN b) RIGHT JOIN c ON b.y = c.z returns the 3 rows.

The rule alone is enough to reproduce it, without a schema:

from sqlglot import parse_one
from sqlglot.optimizer.optimize_joins import optimize_joins

optimize_joins(parse_one("SELECT * FROM a, b RIGHT JOIN c ON b.y = c.z", dialect="duckdb")).sql("duckdb")
# 'SELECT * FROM a CROSS JOIN b RIGHT JOIN c ON b.y = c.z'

The change comes from normalize() in sqlglot/optimizer/optimize_joins.py, which sets kind = "CROSS" on every join that has no on, side, kind, using or method, i.e. on comma joins. It reproduces with read="postgres" too.

Official Documentation

  • Postgres, FROM clause: "In the absence of parentheses, JOINs nest left-to-right. In any case JOIN binds more tightly than the commas separating FROM-list items."
  • Postgres, Joined tables: "This latter equivalence does not hold exactly when more than two tables appear, because JOIN binds more tightly than comma. For example FROM T1 CROSS JOIN T2 INNER JOIN T3 ON condition is not the same as FROM T1, T2 INNER JOIN T3 ON condition because the condition can reference T1 in the first case but not the second."

chaitanyachaudhary30 avatar Nov 11 '26 22:11 chaitanyachaudhary30

Reproduced on 539d7b9 with the exact snippet. normalize() converts the comma join to CROSS JOIN even when the comma group contains a RIGHT/FULL join, so a, (b RIGHT JOIN c) becomes (a CROSS JOIN b) RIGHT JOIN c and returns fewer rows.

I have a fix that preserves the comma join when its group contains a RIGHT/FULL (or PASTE/NEAREST/method) join, while keeping the existing CROSS normalization for INNER/LEFT. Tests cover the issue, the a, b JOIN c RIGHT JOIN d counterexample, multiple comma groups, USING, parenthesized joins, NEAREST, ASOF, and DuckDB row equivalence.

Note: #9001 also touches optimize_joins.py, but it fixes parenthesized-join reordering in _is_reorderable; the comma normalization case still reproduces on its head. This change is in normalize() and the tests are in tests/test_optimizer.py to avoid the fixture conflict. PR coming.

agustin18 avatar Nov 12 '26 01:11 agustin18

Not a priority at the moment.

georgesittas avatar Nov 16 '26 11:11 georgesittas