Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(hogql): lower BY NAME set operators for the ClickHouse dialect (#73524)

Jovan Sakovice0be04e9c449
diff --git a/posthog/hogql/printer/base.py b/posthog/hogql/printer/base.py
index cf62b489b38c..6a8883de7b1e 100644
--- a/posthog/hogql/printer/base.py
+++ b/posthog/hogql/printer/base.py
@@ -107,6 +107,10 @@ class BasePrinter(Visitor[str]):
raise QueryError(f"Invalid set operator: {set_operator!r}")
if set_operator in ("INTERSECT ALL", "EXCEPT ALL"):
raise ImpossibleASTError(f"{set_operator} is not supported in the '{self.DIALECT_NAME}' dialect")
+ if set_operator.endswith(" BY NAME"):
+ # The resolver lowers BY NAME for ClickHouse; reaching the printer means this dialect has
+ # neither native support nor a lowering, so refuse rather than emit SQL the engine rejects.
+ raise QueryError(f"{set_operator} is not supported in the '{self.DIALECT_NAME}' dialect")
def _assert_recursive_cte_supported(self) -> None:
"""Raise if this dialect does not support recursive CTEs. Postgres overrides to permit."""
diff --git a/posthog/hogql/printer/hogql.py b/posthog/hogql/printer/hogql.py
index 664aa5bcdaae..b17aa8ead413 100644
--- a/posthog/hogql/printer/hogql.py
+++ b/posthog/hogql/printer/hogql.py
@@ -1,7 +1,8 @@
-from typing import ClassVar, cast
+from typing import ClassVar, cast, get_args
from posthog.hogql import ast
from posthog.hogql.constants import HogQLDialect
+from posthog.hogql.errors import ImpossibleASTError, QueryError
from posthog.hogql.printer.base import BasePrinter
@@ -22,6 +23,14 @@ class HogQLPrinter(BasePrinter):
# the target dialect ever runs.
return
+ def _assert_set_operator_supported(self, set_operator: str) -> None:
+ # BY NAME is valid HogQL (the SQL dialects lower or reject it), so the round-trip
+ # prints it back verbatim. Keep the base allowlist and INTERSECT ALL/EXCEPT ALL gates.
+ if set_operator not in get_args(ast.SetOperator):
+ raise QueryError(f"Invalid set operator: {set_operator!r}")
+ if set_operator in ("INTERSECT ALL", "EXCEPT ALL"):
+ raise ImpossibleASTError(f"{set_operator} is not supported in the '{self.DIALECT_NAME}' dialect")
+
def visit_cte(self, node: ast.CTE) -> str:
materialization_hint = (
"" if node.materialized is None else ("MATERIALIZED " if node.materialized else "NOT MATERIALIZED ")
diff --git a/posthog/hogql/printer/mysql.py b/posthog/hogql/printer/mysql.py
index acf8f75dded1..3658a4fd54eb 100644
--- a/posthog/hogql/printer/mysql.py
+++ b/posthog/hogql/printer/mysql.py
@@ -76,6 +76,11 @@ class MySQLPrinter(PostgresPrinter):
DIALECT_NAME: ClassVar[HogQLDialect] = "mysql"
DIALECT_LABEL: ClassVar[str] = "MySQL"
+ def _assert_set_operator_supported(self, set_operator: str) -> None:
+ if set_operator.endswith(" BY NAME"):
+ raise QueryError(f"{set_operator} is not supported in the '{self.DIALECT_NAME}' dialect")
+ super()._assert_set_operator_supported(set_operator)
+
def __init__(
self,
context: HogQLContext,
diff --git a/posthog/hogql/printer/postgres.py b/posthog/hogql/printer/postgres.py
index 6b1a6e0e2c49..24f0dfc64143 100644
--- a/posthog/hogql/printer/postgres.py
+++ b/posthog/hogql/printer/postgres.py
@@ -51,7 +51,10 @@ class PostgresPrinter(BasePrinter):
return f"in {self.DIALECT_LABEL} mode"
def _assert_set_operator_supported(self, set_operator: str) -> None:
- return
+ # DuckDB permits everything the base gate rejects (INTERSECT/EXCEPT ALL, recursive CTEs) and
+ # supports UNION BY NAME natively — except INTERSECT/EXCEPT BY NAME, which it also rejects.
+ if set_operator.endswith(" BY NAME") and not set_operator.startswith("UNION "):
+ raise QueryError(f"{set_operator} is not supported in the '{self.DIALECT_NAME}' dialect")
def _assert_recursive_cte_supported(self) -> None:
return
diff --git a/posthog/hogql/printer/redshift.py b/posthog/hogql/printer/redshift.py
index 025a06669402..e2cf58f955f0 100644
--- a/posthog/hogql/printer/redshift.py
+++ b/posthog/hogql/printer/redshift.py
@@ -4,6 +4,7 @@ from typing import ClassVar
from posthog.hogql import ast
from posthog.hogql.constants import HogQLDialect
from posthog.hogql.errors import QueryError
+from posthog.hogql.printer.base import BasePrinter
from posthog.hogql.printer.postgres import PostgresPrinter
from posthog.hogql.printer.redshift_functions import (
REDSHIFT_FUNCTION_HANDLERS_LOWER,
@@ -31,6 +32,11 @@ class RedshiftPrinter(PostgresPrinter):
DIALECT_NAME: ClassVar[HogQLDialect] = "redshift"
DIALECT_LABEL: ClassVar[str] = "Redshift"
+ def _assert_set_operator_supported(self, set_operator: str) -> None:
+ # Redshift supports UNION [ALL] but not INTERSECT ALL/EXCEPT ALL or BY NAME. The Postgres
+ # parent permits everything for DuckDB, so validate against the base gate directly instead.
+ BasePrinter._assert_set_operator_supported(self, set_operator)
+
def _dialect_error_suffix(self) -> str:
return "in the Redshift dialect"
diff --git a/posthog/hogql/printer/snowflake.py b/posthog/hogql/printer/snowflake.py
index b657d5f5a148..2e8bba1289b7 100644
--- a/posthog/hogql/printer/snowflake.py
+++ b/posthog/hogql/printer/snowflake.py
@@ -7,6 +7,7 @@ from posthog.hogql.database.direct_snowflake_table import DirectSnowflakeTable
from posthog.hogql.database.models import DatabaseField
from posthog.hogql.errors import QueryError
from posthog.hogql.escape_sql import escape_snowflake_identifier
+from posthog.hogql.printer.base import BasePrinter
from posthog.hogql.printer.postgres import PostgresPrinter
from posthog.hogql.printer.snowflake_functions import (
SNOWFLAKE_FUNCTION_HANDLERS_LOWER,
@@ -78,6 +79,11 @@ class SnowflakePrinter(PostgresPrinter):
DIALECT_NAME: ClassVar[HogQLDialect] = "snowflake"
DIALECT_LABEL: ClassVar[str] = "Snowflake"
+ def _assert_set_operator_supported(self, set_operator: str) -> None:
+ # Snowflake has no INTERSECT ALL/EXCEPT ALL or BY NAME. The Postgres parent permits
+ # everything for DuckDB, so validate against the base gate directly instead.
+ BasePrinter._assert_set_operator_supported(self, set_operator)
+
def _print_table_sql(self, table) -> str:
return self._print_table(table)
diff --git a/posthog/hogql/printer/test/test_printer.py b/posthog/hogql/printer/test/test_printer.py
index 03660d121eb3..eb2053f4b2c6 100644
--- a/posthog/hogql/printer/test/test_printer.py
+++ b/posthog/hogql/printer/test/test_printer.py
@@ -447,6 +447,134 @@ class TestPrinter(BaseTest):
),
)
+ @parameterized.expand(
+ [
+ ("union all by name", "UNION ALL"),
+ ("union by name", "UNION DISTINCT"),
+ ]
+ )
+ def test_union_by_name_lowered_for_clickhouse(self, operator: str, lowered: str):
+ response = self._select(f"select 1 as a, 2 as b {operator} select 3 as b, 4 as a")
+ self.assertNotIn("BY NAME", response)
+ self.assertIn(f" {lowered} ", response)
+ self.assertIn("SELECT 4 AS a, 3 AS b", response)
+
+ @parameterized.expand([("intersect by name",), ("except by name",)])
+ def test_intersect_except_by_name_rejected_for_clickhouse(self, operator: str):
+ # INTERSECT/EXCEPT bind tighter than UNION, so aligning their operand to the first branch
+ # rather than the true set partner would silently mispair columns. No engine supports them,
+ # so they are refused rather than lowered.
+ with self.assertRaises(QueryError) as context:
+ self._select(f"select 1 as a, 2 as b {operator} select 3 as b, 4 as a")
+ self.assertIn("is not supported", str(context.exception))
+
+ def test_union_by_name_executes_on_clickhouse(self):
+ sql = self._select("select 1 as a, 2 as b union all by name select 3 as b, 4 as a")
+ self.assertEqual(sync_execute(sql), [(1, 2), (4, 3)])
+
+ def test_union_by_name_nested_set_operand_reorders_every_leaf(self):
+ response = self._select(
+ "select 1 as a, 2 as b union all by name (select 30 as b, 40 as a union all select 50 as b, 60 as a)"
+ )
+ self.assertNotIn("BY NAME", response)
+ self.assertIn("SELECT 40 AS a, 30 AS b", response)
+ self.assertIn("SELECT 60 AS a, 50 AS b", response)
+
+ @parameterized.expand(
+ [
+ ("missing_column", "select 1 as a, 2 as b union all by name select 3 as b", "missing: a"),
+ (
+ "extra_column",
+ "select 1 as a union all by name select 3 as a, 4 as b",
+ "unexpected: b",
+ ),
+ (
+ "same_arity_renamed_column",
+ "select 1 as a, 2 as b union all by name select 3 as a, 4 as c",
+ "missing: b",
+ ),
+ (
+ "duplicate_columns",
+ "select uuid, uuid from events union all by name select uuid from events",
+ "uniquely named columns",
+ ),
+ (
+ "nested_leaf_arity_mismatch",
+ "select 1 as a, 2 as b union all by name (select 3 as b, 4 as a union all select 5 as a, 6 as b, 7 as c)",
+ "number of columns",
+ ),
+ ]
+ )
+ def test_by_name_invalid_column_sets_raise(self, _name: str, query: str, expected_error: str):
+ with self.assertRaises(QueryError) as context:
+ self._select(query)
+ self.assertIn(expected_error, str(context.exception))
+
+ def test_union_by_name_remaps_positional_order_by(self):
+ # `order by 2` on the reordered branch must still sort by the column the user meant. ClickHouse
+ # binds a trailing ORDER BY to the last operand, so this needs multiple rows to be observable —
+ # a string check alone passes even when the ordinal points at the wrong column. The sentinel
+ # first-branch row floats freely across the UNION ALL boundary, so assert only the sorted
+ # branch: a correct remap sorts by x (8, 9, 10); a broken one sorts by y (10, 9, 8).
+ sql = self._select(
+ "select 0 as x, 0 as y union all by name select number as y, (10 - number) as x from numbers(3) order by 2"
+ )
+ sorted_branch = [row for row in sync_execute(sql) if row[0] != 0]
+ self.assertEqual(sorted_branch, [(8, 2), (9, 1), (10, 0)])
+
+ def test_union_by_name_kept_for_postgres_dialect(self):
+ response, _ = prepare_and_print_ast(
+ parse_select("select 1 as a, 2 as b union all by name select 3 as b, 4 as a"),
+ HogQLContext(team_id=self.team.pk, enable_select_queries=True),
+ "postgres",
+ )
+ self.assertIn("UNION ALL BY NAME", response)
+ self.assertIn("SELECT 3 AS b, 4 AS a", response)
+
+ @parameterized.expand([("intersect by name",), ("except by name",)])
+ def test_intersect_except_by_name_rejected_for_postgres_dialect(self, operator: str):
+ # DuckDB supports UNION BY NAME natively but rejects INTERSECT/EXCEPT BY NAME, so the postgres
+ # printer must refuse them rather than emit SQL DuckDB won't run.
+ with self.assertRaises(QueryError) as context:
+ prepare_and_print_ast(
+ parse_select(f"select 1 as a, 2 as b {operator} select 3 as b, 4 as a"),
+ HogQLContext(team_id=self.team.pk, enable_select_queries=True),
+ "postgres",
+ )
+ self.assertIn("is not supported", str(context.exception))
+
+ @parameterized.expand([("mysql",), ("snowflake",), ("redshift",)])
+ def test_by_name_rejected_in_warehouse_dialects(self, dialect: str):
+ with self.assertRaises(QueryError) as context:
+ prepare_and_print_ast(
+ parse_select("select 1 as a union all by name select 2 as a"),
+ HogQLContext(team_id=self.team.pk, enable_select_queries=True),
+ cast(HogQLDialect, dialect),
+ )
+ self.assertIn("UNION ALL BY NAME is not supported", str(context.exception))
+
+ @parameterized.expand([("intersect all",), ("except all",)])
+ def test_intersect_except_all_rejected_for_redshift_and_snowflake(self, operator: str):
+ # These extend the permit-all Postgres printer, so without a real gate they would ship
+ # INTERSECT ALL/EXCEPT ALL verbatim to engines that don't support them.
+ for dialect in ("redshift", "snowflake"):
+ with self.assertRaises((QueryError, ImpossibleASTError)):
+ prepare_and_print_ast(
+ parse_select(f"select 1 as a {operator} select 1 as a"),
+ HogQLContext(team_id=self.team.pk, enable_select_queries=True),
+ cast(HogQLDialect, dialect),
+ )
+
+ @parameterized.expand([("intersect all",), ("except all",)])
+ def test_intersect_except_all_permitted_for_mysql(self, operator: str):
+ # MySQL 8.0.31+ supports the ALL modifier, so it must not be swept up in the Redshift/Snowflake gate.
+ printed, _ = prepare_and_print_ast(
+ parse_select(f"select 1 as a {operator} select 1 as a"),
+ HogQLContext(team_id=self.team.pk, enable_select_queries=True),
+ "mysql",
+ )
+ self.assertIn(operator.upper(), printed)
+
# these share the same priority, should stay in order
def test_except_and_union(self):
expr = parse_select("""select 1 as id except select 2 as id union all select 3 as id""")
diff --git a/posthog/hogql/resolver.py b/posthog/hogql/resolver.py
index a978496815f9..766ca9f5f416 100644
--- a/posthog/hogql/resolver.py
+++ b/posthog/hogql/resolver.py
@@ -258,6 +258,63 @@ def _unify_select_set_columns(
return columns
+_BY_NAME_SUFFIX = " BY NAME"
+
+
+def _by_name_column_mismatch_error(canonical: list[str], names: list[str]) -> QueryError:
+ canonical_set, names_set = set(canonical), set(names)
+ details: list[str] = []
+ if missing := [name for name in canonical if name not in names_set]:
+ details.append(f"missing: {', '.join(missing)}")
+ if extra := [name for name in names if name not in canonical_set]:
+ details.append(f"unexpected: {', '.join(extra)}")
+ return QueryError(
+ f"BY NAME requires every branch of the set operation to have the same columns ({'; '.join(details)}). "
+ "Add the missing columns to each branch explicitly, e.g. `NULL AS column_name`."
+ )
+
+
+def _remap_positional_ordinals(leaf: ast.SelectQuery, new_index_by_old: dict[int, int]) -> None:
+ # ClickHouse resolves bare integer literals in these clauses positionally (enable_positional_arguments
+ # defaults to on), so a reordered select list must carry the ordinals along or `ORDER BY 2` silently
+ # comes to mean a different column.
+ referencing: list[ast.Expr] = [order.expr for order in leaf.order_by or []]
+ referencing.extend(leaf.group_by or [])
+ if leaf.limit_by:
+ referencing.extend(leaf.limit_by.exprs)
+ for expr in referencing:
+ if isinstance(expr, ast.Constant) and isinstance(expr.value, int) and not isinstance(expr.value, bool):
+ new_index = new_index_by_old.get(expr.value - 1)
+ if new_index is not None:
+ expr.value = new_index + 1
+
+
+def _permute_set_operand(branch: ast.SelectQuery | ast.SelectSetQuery, permutation: list[int]) -> None:
+ """Apply one positional permutation (new position -> old position) to every SELECT leaf of a set
+ operand. Each leaf is validated on the way down, so a nested branch whose select list does not line
+ up with the operand's columns raises instead of being silently truncated."""
+ if isinstance(branch, ast.SelectSetQuery):
+ for sub in branch.select_queries():
+ _permute_set_operand(sub, permutation)
+ branch_type = branch.type
+ if isinstance(branch_type, ast.SelectSetQueryType) and branch_type.columns:
+ names = list(branch_type.columns.keys())
+ branch_type.columns = {names[old]: branch_type.columns[names[old]] for old in permutation}
+ return
+ if len(branch.select) != len(permutation):
+ raise QueryError(
+ "BY NAME requires every branch of the set operation to have the same number of columns "
+ f"(expected {len(permutation)}, got {len(branch.select)})"
+ )
+ leaf_type = branch.type
+ if not isinstance(leaf_type, ast.SelectQueryType) or len(leaf_type.columns) != len(branch.select):
+ raise QueryError("BY NAME requires uniquely named columns in every branch of the set operation")
+ _remap_positional_ordinals(branch, {old: new for new, old in enumerate(permutation)})
+ branch.select = [branch.select[old] for old in permutation]
+ names = list(leaf_type.columns.keys())
+ leaf_type.columns = {names[old]: leaf_type.columns[names[old]] for old in permutation}
+
+
class AliasCollector(TraversingVisitor):
def __init__(self):
super().__init__()
@@ -342,6 +399,8 @@ class Resolver(CloningVisitor):
limit_percent=node.limit_percent,
limit_with_ties=node.limit_with_ties,
)
+ self._lower_by_name_operators(result)
+
select_types = [
result.initial_select_query.type,
*(x.select_query.type for x in result.subsequent_select_queries),
@@ -355,6 +414,48 @@ class Resolver(CloningVisitor):
return result
+ def _lower_by_name_operators(self, node: ast.SelectSetQuery) -> None:
+ """ClickHouse has no `UNION ... BY NAME` syntax, so the operator cannot be printed there. Lower
+ it instead: reorder each BY NAME operand's select lists to the first branch's column order and
+ emit the plain operator. Dialects with native support (DuckDB behind the postgres printer) keep
+ the operator untouched. Differing column sets raise here, where DuckDB's native BY NAME would
+ null-fill — the error tells the user how to close the gap.
+
+ Only UNION variants are lowered. INTERSECT/EXCEPT BY NAME bind tighter than UNION, so their
+ real set partner is the preceding operand rather than the first branch; aligning to the first
+ branch would silently misalign them. No engine we target supports them either, so they are
+ refused rather than lowered."""
+ if self.dialect != "clickhouse":
+ return
+ for sub in node.subsequent_select_queries:
+ if sub.set_operator.endswith(_BY_NAME_SUFFIX) and not sub.set_operator.startswith("UNION "):
+ raise QueryError(f"{sub.set_operator} is not supported in the '{self.dialect}' dialect")
+ if not any(sub.set_operator.endswith(_BY_NAME_SUFFIX) for sub in node.subsequent_select_queries):
+ return
+ initial = node.initial_select_query
+ if initial.type is None:
+ raise ImpossibleASTError("Set operation branch has no resolved type")
+ canonical = [name for name, _ in _select_type_columns(initial.type)]
+ if len(set(canonical)) != len(canonical) or (
+ isinstance(initial, ast.SelectQuery) and len(initial.select) != len(canonical)
+ ):
+ raise QueryError("BY NAME requires uniquely named columns in every branch of the set operation")
+ index_by_name = {name: index for index, name in enumerate(canonical)}
+ for sub in node.subsequent_select_queries:
+ if not sub.set_operator.endswith(_BY_NAME_SUFFIX):
+ continue
+ branch = sub.select_query
+ if branch.type is None:
+ raise ImpossibleASTError("Set operation branch has no resolved type")
+ names = [name for name, _ in _select_type_columns(branch.type)]
+ if len(set(names)) != len(names):
+ raise QueryError("BY NAME requires uniquely named columns in every branch of the set operation")
+ if set(names) != set(index_by_name):
+ raise _by_name_column_mismatch_error(canonical, names)
+ branch_index_by_name = {name: index for index, name in enumerate(names)}
+ _permute_set_operand(branch, [branch_index_by_name[name] for name in canonical])
+ sub.set_operator = cast(ast.SetOperator, sub.set_operator[: -len(_BY_NAME_SUFFIX)])
+
def visit_values_query(self, node: ast.ValuesQuery):
resolved_rows: list[list[ast.Expr]] = []
for row in node.rows: