: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-table): sort by aliased SQL expression columns (#57859)
Steven Shultsaa470f12f277
diff --git a/frontend/src/queries/nodes/DataTable/DataTable.tsx b/frontend/src/queries/nodes/DataTable/DataTable.tsxindex d1f37c1d1cba..08132f8dd9bb 100644--- a/frontend/src/queries/nodes/DataTable/DataTable.tsx+++ b/frontend/src/queries/nodes/DataTable/DataTable.tsx@@ -44,6 +44,8 @@ import { TableViewSelector } from '~/queries/nodes/DataTable/TableView/TableViewimport {extractExpressionComment,getDataNodeDefaultColumns,+ orderByForSelectKey,+ removeAsAlias,removeExpressionComment,} from '~/queries/nodes/DataTable/utils'import { EventName } from '~/queries/nodes/EventsNode/EventName'@@ -244,6 +246,12 @@ export function DataTable({const col = getContextColumn(colName, context?.columns)return !col?.queryContextColumn?.hidden})+ const orderByForKey = (key: string): string => {+ const rawSelect = sourceFeatures.has(QueryFeature.selectAndOrderByColumns)+ ? ((query.source as EventsQuery).select ?? [])+ : []+ return orderByForSelectKey(key, rawSelect)+ }const rowFillFractionIndex = allColumns.findIndex((colName) => {const col = getContextColumn(colName, context?.columns)return col?.queryContextColumn?.isRowFillFraction@@ -355,8 +363,11 @@ export function DataTable({const source = query.source as EventsQueryconst columns = columnsInLemonTable ?? getDataNodeDefaultColumns(source)const isAggregation = isHogQLAggregation(hogQl)- const isOrderBy = source.orderBy?.[0] === key- const isDescOrderBy = source.orderBy?.[0] === `${key} DESC`+ const orderKey = orderByForKey(key)+ const isOrderBy = source.orderBy?.[0] === orderKey+ const isDescOrderBy =+ source.orderBy?.[0] === `${orderKey} DESC` ||+ source.orderBy?.[0] === `${orderKey}\n DESC`setQuery({...query,source: {@@ -370,7 +381,11 @@ export function DataTable({),orderBy:isOrderBy || isDescOrderBy- ? [isDescOrderBy ? `${hogQl} DESC` : hogQl]+ ? [+ isDescOrderBy+ ? `${removeAsAlias(hogQl)}\n DESC`+ : removeAsAlias(hogQl),+ ]: source.orderBy,},})@@ -393,7 +408,7 @@ export function DataTable({query.source.kind === NodeKind.MarketingAnalyticsTableQuery ||query.source.kind === NodeKind.NonIntegratedConversionsTableQuery? createMarketingAnalyticsOrderBy(key, 'ASC')- : [key]+ : [orderByForKey(key)]setQuery?.({...query,source: {@@ -413,7 +428,7 @@ export function DataTable({query.source.kind === NodeKind.MarketingAnalyticsTableQuery ||query.source.kind === NodeKind.NonIntegratedConversionsTableQuery? createMarketingAnalyticsOrderBy(key, 'DESC')- : [`${key}\n DESC`]+ : [`${orderByForKey(key)}\n DESC`]setQuery?.({...query,source: {diff --git a/frontend/src/queries/nodes/DataTable/utils.test.ts b/frontend/src/queries/nodes/DataTable/utils.test.tsindex 3332ff554352..7b3b593969c8 100644--- a/frontend/src/queries/nodes/DataTable/utils.test.ts+++ b/frontend/src/queries/nodes/DataTable/utils.test.ts@@ -6,6 +6,8 @@ import {extractExpressionComment,getColumnsForQuery,getDefaultDataTablePersonColumns,+ orderByForSelectKey,+ removeAsAlias,removeExpressionComment,} from '~/queries/nodes/DataTable/utils'import { DataTableNode, NodeKind } from '~/queries/schema/schema-general'@@ -25,6 +27,12 @@ describe('DataTable utils', () => {// Backtick aliases with spaces['properties.$city AS `City Name`', 'City Name'],['toUpper(x) as `My Display Name`', 'My Display Name'],+ // Double-quoted aliases (HogQL grammar treats double quotes as quoted identifier delimiters)+ [`properties.$city AS "City Name"`, 'City Name'],+ [+ `formatDateTime(toTimeZone(timestamp, 'Europe/Berlin'), '%b %d, %H:%i:%s') as "Absolute Time"`,+ 'Absolute Time',+ ],// Complex expressions["coalesce(properties.$city, 'Unknown') AS City", 'City'],['arrayJoin(properties.$active_feature_flags) AS flag', 'flag'],@@ -161,4 +169,63 @@ describe('DataTable utils', () => {expect(getColumnsForQuery(result)).toEqual(['*', 'event', 'timestamp'])})})++ describe('removeAsAlias', () => {+ it.each([+ // No alias — return as-is+ ['timestamp', 'timestamp'],+ ['event', 'event'],+ ['properties.$lib', 'properties.$lib'],+ ['coalesce(a, b)', 'coalesce(a, b)'],+ // Bare-word alias+ ['properties.$browser AS Browser', 'properties.$browser'],+ ['properties.$browser as browser', 'properties.$browser'],+ // Backtick alias+ ['properties.$city AS `City Name`', 'properties.$city'],+ // Double-quoted alias (the reported user case)+ [+ `formatDateTime(toTimeZone(timestamp, 'Europe/Berlin'), '%b %d, %H:%i:%s') as "Absolute Time"`,+ `formatDateTime(toTimeZone(timestamp, 'Europe/Berlin'), '%b %d, %H:%i:%s')`,+ ],+ // AS followed by trailing comment+ ['x AS foo -- bar', 'x'],+ // AS inside string literal — only outermost trailing AS stripped+ [`replaceAll(x, ' as ', '_') AS cleaned`, `replaceAll(x, ' as ', '_')`],+ // Empty / falsy+ ['', ''],+ ])('removeAsAlias(%p) = %p', (input, expected) => {+ expect(removeAsAlias(input)).toBe(expected)+ })+ })++ describe('orderByForSelectKey', () => {+ const userExpression = `formatDateTime(toTimeZone(timestamp, 'Europe/Berlin'), '%b %d, %H:%i:%s') as "Absolute Time"`+ const userExpressionBare = `formatDateTime(toTimeZone(timestamp, 'Europe/Berlin'), '%b %d, %H:%i:%s')`++ it.each<[string, string, readonly string[], string]>([+ // Direct match against a raw select entry (bare identifier path)+ [+ 'direct match — bare identifier in select',+ 'properties.$lib',+ ['*', 'event', 'properties.$lib', 'timestamp'],+ 'properties.$lib',+ ],+ // Key is the resolved alias name — look up by extractAsAlias and return the bare expression (the reported bug)+ [+ 'alias lookup — double-quoted alias resolves to underlying expression',+ 'Absolute Time',+ ['*', 'event', userExpression, 'timestamp'],+ userExpressionBare,+ ],+ // Backtick-aliased expression+ ['alias lookup — backtick alias', 'City Name', ['properties.$city AS `City Name`'], 'properties.$city'],+ // Fallback — no match in select, return the key with any AS stripped+ ['fallback — empty select returns key as-is', 'event', [], 'event'],+ ['fallback — empty select returns alias-name key as-is', 'Absolute Time', [], 'Absolute Time'],+ // Direct match for a bare identifier present in select (no AS clause to strip)+ ['direct match — bare timestamp', 'timestamp', ['timestamp', 'event'], 'timestamp'],+ ])('%s', (_label, key, select, expected) => {+ expect(orderByForSelectKey(key, select)).toBe(expected)+ })+ })})diff --git a/frontend/src/queries/nodes/DataTable/utils.ts b/frontend/src/queries/nodes/DataTable/utils.tsindex 06ef81d1a310..bd6fb6e97d9d 100644--- a/frontend/src/queries/nodes/DataTable/utils.ts+++ b/frontend/src/queries/nodes/DataTable/utils.ts@@ -74,6 +74,19 @@ export function extractExpressionComment(query: string): string {return query}+/**+ * Strip a trailing `AS <alias>` clause from a HogQL/SQL expression.+ * Handles backticked, double-quoted, and bare-word aliases, with an optional+ * trailing `-- comment`. The trailing `$` anchor prevents accidental matches+ * inside string literals.+ */+export function removeAsAlias(query: string): string {+ if (!query || typeof query !== 'string') {+ return query+ }+ return query.replace(/\s+[Aa][Ss]\s+(`[^`]+`|"[^"]+"|[\w\u0080-\uFFFF]+)(\s*--.*)?$/, '')+}+/** Extract AS alias from SQL expression (e.g., "expr AS foo" -> "foo") */export function extractAsAlias(query: string): string | null {if (!query || typeof query !== 'string') {@@ -84,15 +97,34 @@ export function extractAsAlias(query: string): string | null {return null}- // Match: whitespace + AS (case-insensitive) + whitespace + (backticked or word alias), optionally followed by comment- const asMatch = trimmed.match(/\s+[Aa][Ss]\s+(`[^`]+`|[\w\u0080-\uFFFF]+)(\s*--.*)?$/)+ // Match: whitespace + AS (case-insensitive) + whitespace + (backticked, double-quoted, or word alias),+ // optionally followed by comment. Per the HogQL grammar, both `backticks` and "double quotes" delimit+ // quoted identifiers, so both forms are valid alias delimiters.+ const asMatch = trimmed.match(/\s+[Aa][Ss]\s+(`[^`]+`|"[^"]+"|[\w\u0080-\uFFFF]+)(\s*--.*)?$/)if (asMatch) {const alias = asMatch[1]- return alias.startsWith('`') && alias.endsWith('`') ? alias.slice(1, -1) : alias+ if ((alias.startsWith('`') && alias.endsWith('`')) || (alias.startsWith('"') && alias.endsWith('"'))) {+ return alias.slice(1, -1)+ }+ return alias}return null}+/**+ * Resolve a column header `key` to a HogQL expression suitable for ORDER BY.+ *+ * The events query response returns resolved alias names (e.g. `Absolute Time`)+ * for aliased columns, which is what we get as `key` when the user clicks Sort.+ * But events ORDER BY does not resolve SELECT aliases by name — it needs the+ * underlying expression. Look up the matching raw select entry, then strip the+ * trailing AS clause to ORDER BY the bare expression.+ */+export function orderByForSelectKey(key: string, select: readonly string[]): string {+ const matchingRaw = select.find((s) => s === key) ?? select.find((s) => extractAsAlias(s) === key) ?? key+ return removeAsAlias(matchingRaw)+}+/** Get display label for an expression, trying AS alias first, then comment syntax */export function extractDisplayLabel(query: string): string {if (!query || typeof query !== 'string') {