diff --git a/sqlglot-integration-tests b/sqlglot-integration-tests index f0c1c9b057..21043c686d 160000 --- a/sqlglot-integration-tests +++ b/sqlglot-integration-tests @@ -1 +1 @@ -Subproject commit f0c1c9b0578e83d7005e21f4862eafde4d6fb282 +Subproject commit 21043c686d54bfc8eee51280c8118f22f5cf1923 diff --git a/sqlglot/optimizer/canonicalize_internal_names.py b/sqlglot/optimizer/canonicalize_internal_names.py index 7004e29712..15865f55d9 100644 --- a/sqlglot/optimizer/canonicalize_internal_names.py +++ b/sqlglot/optimizer/canonicalize_internal_names.py @@ -255,10 +255,11 @@ def _canon(ident: exp.Identifier, name: str) -> None: scope_outputs[id(scope_expr)] = output_map - # Unqualified alias references (ORDER BY a, HAVING a > 5, ...) + # Unqualified alias references (ORDER BY a, HAVING a > 5, ...). for col in find_all_in_scope(scope_expr, exp.Column): - if not col.table and col.name in output_map: - _canon(col.this, output_map[col.name]) + # Only rewrite when the alias is actually being renamed + if not col.table and (canon := output_map.get(col.name)) and canon != col.name: + _canon(col.this, canon) # UBN matches branches by original alias. When both branches are internal # and aliased to distinct _cN, matching originals land on different slots