: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
feat(insights): allow sorting columns on SQL insight tables (#63312)
Sam Pennington9795a1e963f8
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 8a6dcc56b119..e345a1bc37ec 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6199,13 +6199,13 @@ snapshots:scenes-app-insights-mcp-missing-capability--mcp-missing-capability--light:hash: v1.k794b7964.f16f9a878965f2a9c65430ae15d8f28aa5e42cf06d164c2d8a34bcbb825403bf.V9V7xTdOK4Ae-b5Ks5E5oZCMfBIxv_HImZRcJUFOMLcscenes-app-insights-side-panel-actions--saved-data-visualization--dark:- hash: v1.k794b7964.a8a525b15dd0282c16eade2f18dea7a5a40973ba1c018ecf0a8837652be9a848.7yep8vfzpbTSx45P2rQnhL1OBmnL00jVZ9BUwI5rmRM+ hash: v1.k794b7964.3911a695d4b7b073bd0bfbaa183acb078d81df968e2cfecd18f84bc1c181bb66.2Hh9UrgF9n3vN3ZVif3FKqyz4F9mFROKhyLIEflEvDYscenes-app-insights-side-panel-actions--saved-data-visualization--light:- hash: v1.k794b7964.a5c990eb24f7c6b1604ce80b2862d5d775743da574766533880f333e894cdd1e.bWyUXjps8Um0awlGIGDb4VokVcgADYsysG_Hj6fxBL8+ hash: v1.k794b7964.b2284d70e408723520169087ec7e1fe035feb374a854e737de7eb79c43aa39fc.jeFjd9ZtkbDwsQwQXGXkfabL6oCdNbFqWrqHcQAS0Jwscenes-app-insights-side-panel-actions--saved-hog-ql-data-table--dark:- hash: v1.k794b7964.a8a525b15dd0282c16eade2f18dea7a5a40973ba1c018ecf0a8837652be9a848.hWViKr55Lwx0IT-s9ZUYLANiWe6mz0uqkgbLGRxK0VY+ hash: v1.k794b7964.dd73871a7578a0735c6678305046c9c7482e5ab4db83df4ae24b4fed4a8071b0.znK2ZmIRBpBNi0THeBH4RHAIEasVqp8RpGqIpARFVMIscenes-app-insights-side-panel-actions--saved-hog-ql-data-table--light:- hash: v1.k794b7964.a5c990eb24f7c6b1604ce80b2862d5d775743da574766533880f333e894cdd1e.PGxY8ztW21A8vlf__DrtqJtkcoD2TvLSXJOQ5DCKAHs+ hash: v1.k794b7964.5b4c6ba0ac07ba8ea0dc4d24a980821992ee75f62b2f885972e5d332394bed34.PnQhji05di1PUTIp8bvdzvWMfEmF0FfC_K5lAZiLAEEscenes-app-insights-side-panel-actions--saved-trends-insight--dark:hash: v1.k794b7964.e236a1e99e95775e1e69c07f4c336f58ebc7d2a25a557271638d225368ca081a.CgTT0P5qfYJ-wavjUYdmYjcc7vrm_ZiXNjlkaEyDuKgscenes-app-insights-side-panel-actions--saved-trends-insight--light:@@ -6231,9 +6231,9 @@ snapshots:scenes-app-insights-sqllinechart--sql-line-chart-trend-line-quill--light:hash: v1.k794b7964.c446ceed66b1a6056048603e17712a321d2689665867604245510d335c5fc547.aEjCQVGwfNkQ49GMID3RZuoXhA8T_hAD2xalr1WcXIEscenes-app-insights-sqltableconditionalformatting--conditional-formatting-dark--dark:- hash: v1.k794b7964.6a09bd0fd015c4e072926c1ae2c7aa6e63245d8a202f2115894ad9294966a827.dHUY30WwiPjsAuOOqE5STWSsx4s1yBR_3KVczyNzR6M+ hash: v1.k794b7964.0e449eb24ddac2d743015dddb582d1cb0e0b00652497ef29b0a39786257cc814.vdMIdrhfQYn0vDRSKnMQXndXhvqhgir0S5WvIsTwMigscenes-app-insights-sqltableconditionalformatting--conditional-formatting-light--light:- hash: v1.k794b7964.d36479c0918232c1699974423947f5e4275220dd73407bb43b61aa5d1db72ce2.wHTxjjrO1gIW4D1_-JQ9Dby_EnWKug6pdte84r-Nvq8+ hash: v1.k794b7964.6083a0b91ef406d9aea7da39361e0f196feb610f71692b6a0b77b891dba7ace4.XxxJrYAqDFlGaroMDkK1SI9wNd1OiDhd4-C3qhTERoEscenes-app-legal-documents--legal-documents-list--dark:hash: v1.k794b7964.9cb90971cdadb1eadf912754aeb2a82d4fcaf5d91aa716a39bed7b324e8f03be.M6963VTBjXD11KLz9OLd6vbdx2IBcrzUYEli26SO2asscenes-app-legal-documents--legal-documents-list--light:diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Table.test.ts b/frontend/src/queries/nodes/DataVisualization/Components/Table.test.tsnew file mode 100644index 000000000000..5e4d3233ebc8--- /dev/null+++ b/frontend/src/queries/nodes/DataVisualization/Components/Table.test.ts@@ -0,0 +1,31 @@+import { TableDataCell } from '../dataVisualizationLogic'+import { ColumnScalar } from '../types'+import { compareTableCells } from './Table'++function cell(value: string | number | boolean | Date | null, type: ColumnScalar = 'STRING'): TableDataCell<any> {+ return { value, formattedValue: value === null ? null : String(value), type }+}++describe('compareTableCells', () => {+ it.each([+ ['both null', cell(null), cell(null), 0],+ ['a null sorts after b (to bottom of ascending)', cell(null), cell(1, 'INTEGER'), 1],+ ['b null sorts after a (to bottom of ascending)', cell(1, 'INTEGER'), cell(null), -1],+ ['numbers compare numerically, not lexically', cell(2, 'INTEGER'), cell(10, 'INTEGER'), -1],+ ['equal numbers', cell(5, 'INTEGER'), cell(5, 'INTEGER'), 0],+ ['numeric strings use numeric-aware compare', cell('2'), cell('10'), -1],+ ['plain strings compare lexically', cell('apple'), cell('banana'), -1],+ [+ 'datetime columns compare chronologically across formats',+ cell('2024-01-01T00:00:00Z', 'DATETIME'),+ cell('2024-12-31', 'DATE'),+ -1,+ ],+ ['unparseable date falls back to string compare', cell('not-a-date', 'DATETIME'), cell('zzz', 'DATETIME'), -1],+ ['undefined cells are treated as null', undefined, cell(1, 'INTEGER'), 1],+ ])('%s', (_label, a, b, expected) => {+ expect(+ Math.sign(compareTableCells(a as TableDataCell<any> | undefined, b as TableDataCell<any> | undefined))+ ).toBe(expected)+ })+})diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Table.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Table.tsxindex 38e1a3aefdf5..b8546e8805ce 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/Table.tsx+++ b/frontend/src/queries/nodes/DataVisualization/Components/Table.tsx@@ -5,8 +5,9 @@ import posthog from 'posthog-js'import React from 'react'import { IconPin, IconPinFilled } from '@posthog/icons'-import { LemonTable, LemonTableColumn, Tooltip } from '@posthog/lemon-ui'+import { LemonBanner, LemonTable, LemonTableColumn, Tooltip } from '@posthog/lemon-ui'+import { dayjs } from 'lib/dayjs'import { execHog } from 'lib/hog'import { lightenDarkenColor } from 'lib/utils/colors'import { InsightEmptyState, InsightErrorState } from 'scenes/insights/EmptyStates'@@ -20,6 +21,7 @@ import { renderColumn } from '../../DataTable/renderColumn'import { renderColumnMeta } from '../../DataTable/renderColumnMeta'import { getContrastingTextClass } from '../colorUtils'import { TableDataCell, convertTableValue, dataVisualizationLogic } from '../dataVisualizationLogic'+import { ColumnScalar } from '../types'interface TableProps {query: DataVisualizationNode@@ -59,6 +61,39 @@ function getDisplayedColumnTitle(return label || title || columnName}+function isDateColumn(type: ColumnScalar | undefined): boolean {+ return type === 'DATE' || type === 'DATETIME'+}++// Numbers sort numerically, dates chronologically by epoch, everything else by a+// numeric-aware string compare, and empty cells sort to the bottom of an ascending sort.+export function compareTableCells(a: TableDataCell<any> | undefined, b: TableDataCell<any> | undefined): number {+ const aValue = a?.value+ const bValue = b?.value+ if (aValue == null && bValue == null) {+ return 0+ }+ if (aValue == null) {+ return 1+ }+ if (bValue == null) {+ return -1+ }+ if (typeof aValue === 'number' && typeof bValue === 'number') {+ return aValue - bValue+ }+ // Parse dates to epoch ms so values with different formats or timezones sort+ // chronologically rather than lexicographically.+ if (isDateColumn(a?.type) && isDateColumn(b?.type)) {+ const aTime = dayjs(aValue as string | number | Date).valueOf()+ const bTime = dayjs(bValue as string | number | Date).valueOf()+ if (!Number.isNaN(aTime) && !Number.isNaN(bTime)) {+ return aTime - bTime+ }+ }+ return String(aValue).localeCompare(String(bValue), undefined, { numeric: true })+}+// Plain-text representation of a cell, used as the hover title so clipped content is// still visible on hover. The full value stays in the DOM (CSS ellipsis only), so// selecting and copying a cell copies the whole value, not just the clipped portion.@@ -87,8 +122,11 @@ export const Table = (props: TableProps): JSX.Element => {pinnedColumns,isColumnPinned,isPinningEnabled,+ isTransposed,+ hasSortedTable,+ hasMoreData,} = useValues(dataVisualizationLogic)- const { toggleColumnPin } = useActions(dataVisualizationLogic)+ const { toggleColumnPin, setTableSorted } = useActions(dataVisualizationLogic)const sourceTabularColumnsByName = new Map(sourceTabularColumns.map((column) => [column.column.name, column]))@@ -169,6 +207,9 @@ export const Table = (props: TableProps): JSX.Element => {return {...columnMeta,key: column.name,+ // Sorting reorders rows, which doesn't make sense once the table is transposed+ // (rows become the original columns), so only offer it in the normal orientation.+ sorter: isTransposed ? undefined : (a, b) => compareTableCells(a[index], b[index]),title: (<div className="flex items-center gap-1"><span>{formattedTitle}</span>@@ -253,39 +294,52 @@ export const Table = (props: TableProps): JSX.Element => {)return (- <LemonTable- className="DataVisualizationTable"- dataSource={tabularData}- columns={tableColumns}- pinnedColumns={isPinningEnabled ? pinnedColumns : undefined}- loading={responseLoading}- pagination={{ pageSize: DEFAULT_PAGE_SIZE }}- maxHeaderWidth="15rem"- emptyState={- responseError ? (- <InsightErrorState- query={props.query}- excludeDetail- title={- queryCancelled- ? 'The query was cancelled'- : response && 'error' in response- ? (response as any).error- : responseError- }- />- ) : (- <InsightEmptyState- heading="There are no matching rows for this query"- detail=""- sampleDataVariant="table"- />- )- }- footer={tabularData.length > 0 ? <LoadNext query={props.query} /> : null}- rowClassName="DataVizRow"- embedded={props.embedded}- allowContentScroll={!!props.embedded}- />+ <>+ {hasSortedTable && hasMoreData && (+ <LemonBanner type="info" className="mb-2" dismissKey="data-visual">+ Sorting only reorders the rows already loaded, not the full dataset.+ </LemonBanner>+ )}+ <LemonTable+ className="DataVisualizationTable"+ dataSource={tabularData}+ columns={tableColumns}+ pinnedColumns={isPinningEnabled ? pinnedColumns : undefined}+ loading={responseLoading}+ useURLForSorting={false}+ onSort={(newSorting) => {+ if (newSorting) {+ setTableSorted()+ }+ }}+ pagination={{ pageSize: DEFAULT_PAGE_SIZE }}+ maxHeaderWidth="15rem"+ emptyState={+ responseError ? (+ <InsightErrorState+ query={props.query}+ excludeDetail+ title={+ queryCancelled+ ? 'The query was cancelled'+ : response && 'error' in response+ ? (response as any).error+ : responseError+ }+ />+ ) : (+ <InsightEmptyState+ heading="There are no matching rows for this query"+ detail=""+ sampleDataVariant="table"+ />+ )+ }+ footer={tabularData.length > 0 ? <LoadNext query={props.query} /> : null}+ rowClassName="DataVizRow"+ embedded={props.embedded}+ allowContentScroll={!!props.embedded}+ />+ </>)}diff --git a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.test.ts b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.test.tsindex b99171dfee02..04afdb84bc98 100644--- a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.test.ts+++ b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.test.ts@@ -470,6 +470,14 @@ describe('dataVisualizationLogic', () => {expect(logic.values.query.tableSettings?.transpose).toEqual(true)})+ it('flags the table as sorted only after setTableSorted', async () => {+ await expectLogic(logic).toMatchValues({ hasSortedTable: false })++ logic.actions.setTableSorted()++ await expectLogic(logic).toMatchValues({ hasSortedTable: true })+ })+it('does not mutate the original query when updating y-axis formatting', async () => {const queryWithAxisSettings: DataVisualizationNode = {...defaultQuery,diff --git a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.tsindex e91ad77241b1..6f644213370b 100644--- a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts+++ b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts@@ -411,6 +411,7 @@ const shouldUseFirstNumericColumnAsContinuousChartXAxis = (// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface dataVisualizationLogicValues {+ hasMoreData: boolean // dataNodeLogicqueryCancelled: boolean // dataNodeLogicresponse:| ErrorTrackingQueryResponse@@ -442,6 +443,7 @@ export interface dataVisualizationLogicValues {dataVisualizationProps: DataVisualizationLogicPropseffectiveVisualizationType: ChartDisplayTypehasDateTimeColumns: boolean+ hasSortedTable: booleanisChartSettingsPanelOpen: booleanisColumnPinned: (columnName: string) => booleanisPinningEnabled: boolean@@ -522,6 +524,9 @@ export interface dataVisualizationLogicActions {setSideBarTab: (tab: SideBarTab) => {tab: SideBarTab}+ setTableSorted: () => {+ value: true+ }setTransposeResults: (transpose: boolean) => {transpose: boolean}@@ -765,7 +770,7 @@ export const dataVisualizationLogic = kea<dataVisualizationLogicType>([variablesOverride: props.variablesOverride,limitContext: props.limitContext,}),- ['response', 'responseLoading', 'responseError', 'queryCancelled'],+ ['response', 'responseLoading', 'responseError', 'queryCancelled', 'hasMoreData'],themeLogic,['isDarkModeOn'],sceneLogic,@@ -834,6 +839,7 @@ export const dataVisualizationLogic = kea<dataVisualizationLogicType>([}),setConditionalFormattingRulesPanelActiveKeys: (keys: string[]) => ({ keys }),toggleColumnPin: (columnName: string) => ({ columnName }),+ setTableSorted: true,setTransposeResults: (transpose: boolean) => ({ transpose }),_setQuery: (node: DataVisualizationNode) => ({ node }),})),@@ -1136,6 +1142,12 @@ export const dataVisualizationLogic = kea<dataVisualizationLogicType>([},},],+ hasSortedTable: [+ false,+ {+ setTableSorted: () => true,+ },+ ],})),selectors({columns: [