diff --git a/sqlglot/optimizer/simplify.py b/sqlglot/optimizer/simplify.py index 6dfd9ff6eb..06ea423bb9 100644 --- a/sqlglot/optimizer/simplify.py +++ b/sqlglot/optimizer/simplify.py @@ -495,6 +495,17 @@ def simplify_coalesce(expression): ) +# CROSS joins result in an empty table if the right table is empty. +# So we can only simplify certain types of joins to CROSS. +# Or in other words, LEFT JOIN x ON TRUE != CROSS JOIN x +JOINS = { + ("", ""), + ("", "INNER"), + ("RIGHT", ""), + ("RIGHT", "OUTER"), +} + + def remove_where_true(expression): for where in expression.find_all(exp.Where): if always_true(where.this): @@ -504,6 +515,7 @@ def remove_where_true(expression): always_true(join.args.get("on")) and not join.args.get("using") and not join.args.get("method") + and (join.side, join.kind) in JOINS ): join.set("on", None) join.set("side", None) diff --git a/tests/fixtures/optimizer/simplify.sql b/tests/fixtures/optimizer/simplify.sql index ff42baca1b..629262dcf4 100644 --- a/tests/fixtures/optimizer/simplify.sql +++ b/tests/fixtures/optimizer/simplify.sql @@ -240,9 +240,18 @@ A AND B AND C; SELECT x WHERE TRUE; SELECT x; -SELECT x FROM y LEFT JOIN z ON TRUE; +SELECT x FROM y JOIN z ON TRUE; +SELECT x FROM y CROSS JOIN z; + +SELECT x FROM y RIGHT JOIN z ON TRUE; SELECT x FROM y CROSS JOIN z; +SELECT x FROM y LEFT JOIN z ON TRUE; +SELECT x FROM y LEFT JOIN z ON TRUE; + +SELECT x FROM y FULL OUTER JOIN z ON TRUE; +SELECT x FROM y FULL OUTER JOIN z ON TRUE; + SELECT x FROM y JOIN z USING (x); SELECT x FROM y JOIN z USING (x);