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): preserve trino order by alias parameter identity (#96231)

Bill Guowei Yangcb565f072321
diff --git a/docs/internal/hogql-trino-compiler.md b/docs/internal/hogql-trino-compiler.md
index fa7d13e08ebf..ab3e960630d9 100644
--- a/docs/internal/hogql-trino-compiler.md
+++ b/docs/internal/hogql-trino-compiler.md
@@ -48,6 +48,8 @@ For supported string, array, and map arguments, `empty(x)` returns true when the
For ordinary `GROUP BY`, an expression that matches a selected expression uses that output's ordinal. This keeps property paths, date conversions, and other bound expressions identical for Trino's grouping checks. An alias for an integer constant uses the selected expression's position; the constant's value does not become an ordinal. Explicit source ordinals remain unchanged. Alias references inside larger expressions expand to their expressions, not ordinals. Complex grouping modes retain their expressions. These rewrites apply to both pure and Django-expanded compilation.
+A top-level `ORDER BY` reference to a selected alias also uses that output's ordinal. This avoids repeating bound parameters from the selected expression and keeps grouped queries valid. Ordering direction and explicit source ordinals remain unchanged; aliases inside larger sort expressions still expand normally.
+
## Why some shared integration is necessary
The backend owns its function mappings, structural rewrites, validation, and table rendering. These shared extension points let it reuse the existing compiler without duplicating its semantic pipeline:
diff --git a/posthog/hogql/printer/test/test_trino_printer.py b/posthog/hogql/printer/test/test_trino_printer.py
index dd4b20859e03..4e90437bd6c1 100644
--- a/posthog/hogql/printer/test/test_trino_printer.py
+++ b/posthog/hogql/printer/test/test_trino_printer.py
@@ -314,13 +314,38 @@ def test_lowers_event_element_materializations_to_the_physical_chain() -> None:
assert 'array_distinct(regexp_extract_all("tenant"."posthog"."events"."elements_chain"' in sql
-def test_lowers_clickhouse_select_alias_references_to_expressions() -> None:
+ "expression, group_by, order_by, expected_order, expected_values",
+ [
+ ("user_id", "account_id", "total", "2 ASC", []),
+ (
+ "concat(user_id, 'suffix')",
+ "concat(user_id, 'suffix')",
+ "account_id DESC",
+ "1 DESC",
+ ["suffix"],
+ ),
+ ("properties.color", "account_id", "account_id", "1 ASC", ['$["color"]']),
+ ("0", "account_id", "account_id", "1 ASC", []),
+ ("user_id", "account_id", "2", "2 ASC", []),
+ (
+ "user_id",
+ "account_id",
+ "concat(account_id, 'suffix')",
+ 'concat(CAST("users"."user_id" AS VARCHAR), CAST(? AS VARCHAR)) ASC',
+ ["suffix"],
+ ),
+ ],
+)
+def test_lowers_clickhouse_select_alias_references_to_expressions(
+ expression: str, group_by: str, order_by: str, expected_order: str, expected_values: list[str]
+) -> None:
context = _context_with_trino_table()
sql, _ = prepare_and_print_ast(
parse_select(
- "SELECT user_id AS account_id, count() AS total FROM users "
- "GROUP BY account_id HAVING total > 0 ORDER BY total"
+ f"SELECT {expression} AS account_id, count() AS total FROM users "
+ f"GROUP BY {group_by} HAVING total > 0 ORDER BY {order_by}"
),
context,
"trino",
@@ -328,7 +353,9 @@ def test_lowers_clickhouse_select_alias_references_to_expressions() -> None:
assert "GROUP BY 1" in sql
assert "HAVING (count(*) > 0)" in sql
- assert "ORDER BY count(*) ASC" in sql
+ sql, values = convert_pyformat_placeholders(sql, context.values)
+ assert sql.endswith(f"ORDER BY {expected_order}")
+ assert values == expected_values
@pytest.mark.parametrize(
diff --git a/posthog/hogql/transforms/trino/normalize.py b/posthog/hogql/transforms/trino/normalize.py
index ffe3f603af14..0d8e1b4ae67c 100644
--- a/posthog/hogql/transforms/trino/normalize.py
+++ b/posthog/hogql/transforms/trino/normalize.py
@@ -121,6 +121,22 @@ class TrinoSelectAliasLowerer(CloningVisitor):
key = expression_key(expr)
if key in projections:
lowered.group_by[index] = ast.PositionalRef(index=projections.index(key) + 1)
+ if node.order_by is not None and lowered.order_by is not None:
+ alias_positions = {
+ expr.alias: index + 1 for index, expr in enumerate(node.select) if isinstance(expr, ast.Alias)
+ }
+ for original, order in zip(node.order_by, lowered.order_by, strict=True):
+ expr = original.expr
+ while isinstance(expr, ast.Alias) and expr.hidden:
+ expr = expr.expr
+ if (
+ isinstance(expr, ast.Field)
+ and isinstance(expr.type, ast.FieldAliasType)
+ and len(expr.chain) == 1
+ and isinstance(expr.chain[0], str)
+ and (position := alias_positions.get(expr.chain[0])) is not None
+ ):
+ order.expr = ast.PositionalRef(index=position)
self.aliases = outer_aliases
return lowered