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): honor DISTINCT for count() in the Snowflake printer (#70609)

posthog[bot]f2d03c7f5e97
diff --git a/posthog/hogql/printer/postgres.py b/posthog/hogql/printer/postgres.py
index 9eb42abcea37..6b1a6e0e2c49 100644
--- a/posthog/hogql/printer/postgres.py
+++ b/posthog/hogql/printer/postgres.py
@@ -172,11 +172,16 @@ class PostgresPrinter(BasePrinter):
f"Function '{node.name}' does not support ORDER BY in the {self.DIALECT_LABEL} dialect."
)
if node.distinct:
- # Handlers compose custom SQL from pre-rendered args; injecting DISTINCT into
- # that blindly risks silently changing what the aggregate counts.
- raise QueryError(
- f"Function '{node.name}' does not support DISTINCT in the {self.DIALECT_LABEL} dialect."
- )
+ if func_name in self._get_distinct_capable_handlers():
+ # Fold DISTINCT into the rendered args so the handler emits e.g.
+ # COUNT(DISTINCT expr) — valid SQL these aggregates support.
+ args = [f"DISTINCT {', '.join(args)}"]
+ else:
+ # Other handlers compose custom SQL from pre-rendered args; injecting
+ # DISTINCT blindly risks silently changing what the aggregate counts.
+ raise QueryError(
+ f"Function '{node.name}' does not support DISTINCT in the {self.DIALECT_LABEL} dialect."
+ )
return handler(args)
args_str = ", ".join(args)
@@ -211,6 +216,10 @@ class PostgresPrinter(BasePrinter):
"""Lowercased function names that are emitted verbatim without renaming."""
return POSTGRES_PASSTHROUGH_FUNCTIONS
+ def _get_distinct_capable_handlers(self) -> frozenset[str]:
+ """Lowercased handler names whose SQL accepts a leading DISTINCT (e.g. COUNT(DISTINCT x))."""
+ return frozenset()
+
def visit_array_slice(self, node: ast.ArraySlice):
start = self.visit(node.start_expr) if node.start_expr is not None else ""
end = self.visit(node.end_expr) if node.end_expr is not None else ""
diff --git a/posthog/hogql/printer/snowflake.py b/posthog/hogql/printer/snowflake.py
index 85d9f684d7dc..b657d5f5a148 100644
--- a/posthog/hogql/printer/snowflake.py
+++ b/posthog/hogql/printer/snowflake.py
@@ -150,6 +150,11 @@ class SnowflakePrinter(PostgresPrinter):
def _get_passthrough_functions(self) -> frozenset[str]:
return SNOWFLAKE_PASSTHROUGH_FUNCTIONS
+ def _get_distinct_capable_handlers(self) -> frozenset[str]:
+ # count() is handler-backed here (for the count(*) special case) but Snowflake
+ # fully supports COUNT(DISTINCT expr), so let the distinct flag through.
+ return frozenset({"count"})
+
# --- ClickHouse-only SELECT clauses
#
# The inherited (base) visit_select_query emits these verbatim; Snowflake has no
diff --git a/posthog/hogql/printer/snowflake_functions.py b/posthog/hogql/printer/snowflake_functions.py
index 396ab6ec3ccf..7ab401e0b800 100644
--- a/posthog/hogql/printer/snowflake_functions.py
+++ b/posthog/hogql/printer/snowflake_functions.py
@@ -156,7 +156,8 @@ def _make_agg_if_handler(snowflake_fn: str) -> Callable[[list[str]], str]:
def _handle_count(args: list[str]) -> str:
# HogQL's argless count() means "count all rows", but Snowflake rejects a bare COUNT() —
- # it must be COUNT(*). count(expr) passes through unchanged.
+ # it must be COUNT(*). count(expr) passes through unchanged, as does count(DISTINCT expr)
+ # (visit_call folds the DISTINCT flag into the rendered arg).
return "count(*)" if not args else f"count({', '.join(args)})"
diff --git a/posthog/hogql/printer/test/test_printer.py b/posthog/hogql/printer/test/test_printer.py
index acb26bdf3d1d..f8f6580ee642 100644
--- a/posthog/hogql/printer/test/test_printer.py
+++ b/posthog/hogql/printer/test/test_printer.py
@@ -8075,6 +8075,8 @@ SNOWFLAKE_EMIT_CASES: list[tuple[str, str, str]] = [
# count() means "count all rows"; Snowflake rejects a bare COUNT(), so emit COUNT(*).
("count_star", "count()", "count(*)"),
("count_expr", "count(event)", 'count(events."event")'),
+ # Snowflake supports COUNT(DISTINCT expr) — the count handler must honor the distinct flag.
+ ("count_distinct", "count(distinct event)", 'count(DISTINCT events."event")'),
# Passthrough (valid Snowflake verbatim)
("avg", "avg(1)", "avg(1)"),
("coalesce", "coalesce(1, 2)", "coalesce(1, 2)"),