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.

feat(sql-editor): add sort selector and automatic sorting to BI mode (#81859)

Marius Andra703940f4c43f
diff --git a/frontend/src/scenes/data-warehouse/editor/bi/BIEditor.tsx b/frontend/src/scenes/data-warehouse/editor/bi/BIEditor.tsx
index dc410c6cd5b5..13ab2ecb431a 100644
--- a/frontend/src/scenes/data-warehouse/editor/bi/BIEditor.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/bi/BIEditor.tsx
@@ -36,6 +36,7 @@ import {
BIFilterOperator,
BIShelf,
BIField,
+ BISortDirection,
PIVOT_TABLE_QUERY_LIMIT,
getBIDataSourceKey,
isDateTimeBIField,
@@ -93,9 +94,14 @@ const LIMIT_OPTIONS = BI_QUERY_LIMITS.map((limit) => ({
label: limit === 1000 ? '1k' : limit === 10000 ? '10k' : limit === 50000 ? '50k' : String(limit),
}))
+const SORT_DIRECTION_OPTIONS: { value: BISortDirection; label: string }[] = [
+ { value: 'desc', label: 'Descending' },
+ { value: 'asc', label: 'Ascending' },
+]
+
export function BIEditor({ tabId }: { tabId: string }): JSX.Element {
const logic = biEditorLogic({ tabId })
- const { activeDropShelf, activeExpressionEditorId, availableDataSources, config, databaseLoading } =
+ const { activeDropShelf, activeExpressionEditorId, availableDataSources, config, databaseLoading, sortOptions } =
useValues(logic)
const { biEditorHeight, biEditorResizerProps } = useValues(editorSizingLogic)
const { setDatabaseTreeCollapsed } = useActions(editorSizingLogic)
@@ -116,6 +122,7 @@ export function BIEditor({ tabId }: { tabId: string }): JSX.Element {
setFilterOperator,
setFilterValue,
setLimit,
+ setSort,
setValueAggregation,
setValueCustomExpression,
} = useActions(logic)
@@ -193,6 +200,40 @@ export function BIEditor({ tabId }: { tabId: string }): JSX.Element {
dropdownMatchSelectWidth={false}
data-attr="bi-editor-query-limit"
/>
+ <LemonSelect
+ value={config.sort?.key ?? null}
+ options={[
+ {
+ value: null,
+ label: 'Auto',
+ tooltip:
+ 'Sorts by the newest date or the highest value first, so the top rows stay within the limit.',
+ },
+ ...sortOptions.map((option) => ({ value: option.key, label: option.label })),
+ ]}
+ onChange={(key) =>
+ setSort(key === null ? null : { key, direction: config.sort?.direction ?? 'desc' })
+ }
+ renderButtonContent={(option) => `Sort: ${option?.label ?? 'Auto'}`}
+ aria-label="Sort results by"
+ size="small"
+ dropdownMatchSelectWidth={false}
+ disabledReason={
+ sortOptions.length === 0 ? 'Add a field to rows or columns first' : undefined
+ }
+ data-attr="bi-editor-sort"
+ />
+ {config.sort ? (
+ <LemonSelect
+ value={config.sort.direction}
+ options={SORT_DIRECTION_OPTIONS}
+ onChange={(direction) => config.sort && setSort({ key: config.sort.key, direction })}
+ aria-label="Sort direction"
+ size="small"
+ dropdownMatchSelectWidth={false}
+ data-attr="bi-editor-sort-direction"
+ />
+ ) : null}
<LemonButton
type="secondary"
size="small"
diff --git a/frontend/src/scenes/data-warehouse/editor/bi/biEditorAnalytics.ts b/frontend/src/scenes/data-warehouse/editor/bi/biEditorAnalytics.ts
index 2649e8a94201..37889be53357 100644
--- a/frontend/src/scenes/data-warehouse/editor/bi/biEditorAnalytics.ts
+++ b/frontend/src/scenes/data-warehouse/editor/bi/biEditorAnalytics.ts
@@ -41,6 +41,8 @@ function getBIEditorConfigProperties(config: BIConfig): Record<string, unknown>
fields.flatMap((field) => (field.dateBucket === undefined ? [] : [field.dateBucket]))
),
custom_expression_count: customExpressionCount,
+ sort_kind: config.sort ? 'manual' : 'auto',
+ sort_direction: config.sort?.direction ?? null,
}
}
diff --git a/frontend/src/scenes/data-warehouse/editor/bi/biEditorLogic.ts b/frontend/src/scenes/data-warehouse/editor/bi/biEditorLogic.ts
index 543958f2e5f6..92865abf1703 100644
--- a/frontend/src/scenes/data-warehouse/editor/bi/biEditorLogic.ts
+++ b/frontend/src/scenes/data-warehouse/editor/bi/biEditorLogic.ts
@@ -21,10 +21,13 @@ import {
BIQueryBuildResult,
BIQueryLimit,
BIShelf,
+ BISort,
+ BISortOption,
DEFAULT_BI_CONFIG,
buildBIQuery,
createDefaultDateFilter,
defaultAggregationForField,
+ getBISortOptions,
isBIFieldCompatible,
normalizeBIConfig,
} from './biEditorTypes'
@@ -60,6 +63,7 @@ function setDataSourceInConfig(config: BIConfig, source: BIDataSource): BIConfig
columns: [],
values: [],
filters: defaultDateFilter ? [defaultDateFilter] : [],
+ sort: null,
}
}
@@ -198,6 +202,7 @@ export interface biEditorLogicValues {
config: BIConfig
editorView: BIEditorView
generatedQuery: BIQueryBuildResult | null
+ sortOptions: BISortOption[]
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -302,6 +307,9 @@ export interface biEditorLogicActions {
setLimit: (limit: BIQueryLimit) => {
limit: 100 | 1000 | 10000 | 50000
}
+ setSort: (sort: BISort | null) => {
+ sort: BISort | null
+ }
setValueAggregation: (
index: number,
aggregation: BIAggregation
@@ -331,6 +339,7 @@ export interface biEditorLogicMeta {
databaseConnectionId: string | null
) => BIDataSource[]
generatedQuery: (config: BIConfig) => BIQueryBuildResult | null
+ sortOptions: (config: BIConfig) => BISortOption[]
}
}
@@ -370,6 +379,7 @@ export const biEditorLogic = kea<biEditorLogicType>([
setFilterOperator: (index: number, operator: BIFilterOperator) => ({ index, operator }),
setFilterValue: (index: number, value: string) => ({ index, value }),
setLimit: (limit: BIQueryLimit) => ({ limit }),
+ setSort: (sort: BISort | null) => ({ sort }),
setFieldExpression: (shelf: BIShelf, index: number, expression: string) => ({ shelf, index, expression }),
setFieldDateBucket: (shelf: BIShelf, index: number, dateBucket: BIDateBucket | null) => ({
shelf,
@@ -438,6 +448,7 @@ export const biEditorLogic = kea<biEditorLogicType>([
),
}),
setLimit: (config, { limit }) => normalizeBIConfig({ ...config, limit }),
+ setSort: (config, { sort }) => normalizeBIConfig({ ...config, sort }),
setFieldExpression: (config, { shelf, index, expression }) =>
setFieldExpressionInConfig(config, shelf, index, expression),
setFieldDateBucket: (config, { shelf, index, dateBucket }) =>
@@ -484,6 +495,10 @@ export const biEditorLogic = kea<biEditorLogicType>([
(selectors) => [selectors.config],
(config: BIConfig): BIQueryBuildResult | null => buildBIQuery(config),
],
+ sortOptions: [
+ (selectors) => [selectors.config],
+ (config: BIConfig): BISortOption[] => getBISortOptions(config),
+ ],
}),
listeners(({ actions, props: logicProps, values }) => ({
persistState: ({ editorView, config }) => {
@@ -539,6 +554,10 @@ export const biEditorLogic = kea<biEditorLogicType>([
actions.persistState(values.editorView, values.config)
actions.syncGeneratedQuery()
},
+ setSort: () => {
+ actions.persistState(values.editorView, values.config)
+ actions.syncGeneratedQuery()
+ },
setFieldExpression: () => {
actions.persistState(values.editorView, values.config)
actions.syncGeneratedQuery()
diff --git a/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.test.ts b/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.test.ts
index 1d9a8121afad..ad56a2bbbe01 100644
--- a/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.test.ts
@@ -3,13 +3,16 @@ import { ChartDisplayType } from '~/types'
import {
BIConfig,
+ BIEditorView,
BIField,
buildBIQuery,
createDefaultDateFilter,
defaultAggregationForField,
getBIDataSourceKey,
getBIFieldId,
+ getBISortOptions,
isBIFieldCompatible,
+ parseBIEditorState,
} from './biEditorTypes'
const eventField: BIField = {
@@ -63,6 +66,8 @@ describe('BI editor query generation', () => {
" lower(event) LIKE lower('%sign\\'up%')",
'GROUP BY',
' event',
+ 'ORDER BY',
+ ' sum_revenue DESC',
'LIMIT 1000',
].join('\n')
const config: BIConfig = {
@@ -163,9 +168,17 @@ describe('BI editor query generation', () => {
})
expect(result?.query).toEqual(
- ['SELECT', ' event,', ' count(*) AS count', 'FROM events', 'GROUP BY', ' event', 'LIMIT 100'].join(
- '\n'
- )
+ [
+ 'SELECT',
+ ' event,',
+ ' count(*) AS count',
+ 'FROM events',
+ 'GROUP BY',
+ ' event',
+ 'ORDER BY',
+ ' count DESC',
+ 'LIMIT 100',
+ ].join('\n')
)
})
@@ -309,6 +322,95 @@ describe('BI editor query generation', () => {
expect(isBIFieldCompatible(source, field)).toBe(expected)
})
+ const sortableConfig: BIConfig = {
+ source: { table: 'events' },
+ chartType: ChartDisplayType.ActionsBar,
+ rows: [browserField],
+ columns: [],
+ values: [{ field: revenueField, aggregation: 'sum' }],
+ filters: [],
+ limit: 1000,
+ }
+
+ test.each([
+ ['automatically by the first value, descending', undefined, 'ORDER BY\n sum_revenue DESC'],
+ [
+ 'by a selected dimension',
+ { key: `rows:${browserField.id}`, direction: 'asc' },
+ 'ORDER BY\n properties.$browser ASC',
+ ],
+ [
+ 'by a selected value',
+ { key: `values:${revenueField.id}`, direction: 'asc' },
+ 'ORDER BY\n sum_revenue ASC',
+ ],
+ [
+ 'automatically when the sorted field no longer exists',
+ { key: 'rows:removed-field', direction: 'asc' },
+ 'ORDER BY\n sum_revenue DESC',
+ ],
+ ] as const)('sorts %s', (_name, sort, expectedClause) => {
+ expect(buildBIQuery({ ...sortableConfig, sort })?.query).toContain(expectedClause)
+ })
+
+ it('auto-sorts date dimensions newest first', () => {
+ const result = buildBIQuery({ ...sortableConfig, rows: [{ ...timestampField, dateBucket: 'day' }] })
+
+ expect(result?.query).toContain('ORDER BY\n toStartOfDay(timestamp) DESC')
+ })
+
+ it('offers dimensions and values as sort options, and a count fallback without values', () => {
+ expect(getBISortOptions(sortableConfig).map((option) => option.key)).toEqual([
+ `rows:${browserField.id}`,
+ `values:${revenueField.id}`,
+ ])
+ expect(getBISortOptions({ ...sortableConfig, values: [] }).map((option) => option.key)).toEqual([
+ `rows:${browserField.id}`,
+ 'values:count',
+ ])
+ expect(getBISortOptions({ ...sortableConfig, rows: [] })).toEqual([])
+ })
+
+ it('keeps every aggregation of the same field sortable', () => {
+ const twoAggregationsConfig: BIConfig = {
+ ...sortableConfig,
+ values: [
+ { field: revenueField, aggregation: 'sum' },
+ { field: revenueField, aggregation: 'average' },
+ ],
+ }
+
+ expect(getBISortOptions(twoAggregationsConfig).map((option) => option.key)).toEqual([
+ `rows:${browserField.id}`,
+ `values:${revenueField.id}`,
+ `values:${revenueField.id}:2`,
+ ])
+ expect(
+ buildBIQuery({
+ ...twoAggregationsConfig,
+ sort: { key: `values:${revenueField.id}:2`, direction: 'asc' },
+ })?.query
+ ).toContain('ORDER BY\n average_revenue_2 ASC')
+ })
+
+ test.each([
+ ['a state persisted before sort existed', {}, null],
+ [
+ 'an explicit sort',
+ { rows: [eventField], sort: { key: `rows:${eventField.id}`, direction: 'asc' } },
+ { key: `rows:${eventField.id}`, direction: 'asc' },
+ ],
+ ['a sort whose field was removed', { sort: { key: 'rows:removed-field', direction: 'desc' } }, null],
+ ])('restores %s', (_name, configOverrides, expectedSort) => {
+ const persistedConfig = { ...sortableConfig, rows: [], values: [], ...configOverrides }
+
+ expect(parseBIEditorState(BIEditorView.BI, persistedConfig)?.config.sort).toEqual(expectedSort)
+ })
+
+ it('rejects a persisted state with a malformed sort', () => {
+ expect(parseBIEditorState(BIEditorView.BI, { ...sortableConfig, sort: { key: 1, direction: 'up' } })).toBeNull()
+ })
+
it('keeps same-named sources and fields distinct across connections', () => {
const sources = [
{ table: 'events' },
diff --git a/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.ts b/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.ts
index e5e96a6dc3c3..f117437fe741 100644
--- a/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.ts
+++ b/frontend/src/scenes/data-warehouse/editor/bi/biEditorTypes.ts
@@ -19,6 +19,19 @@ export type BIQueryLimit = (typeof BI_QUERY_LIMITS)[number]
export const PIVOT_TABLE_QUERY_LIMIT: BIQueryLimit = 1000
+export type BISortDirection = 'asc' | 'desc'
+
+export interface BISort {
+ key: string
+ direction: BISortDirection
+}
+
+export interface BISortOption {
+ key: string
+ label: string
+ expression: string
+}
+
export type BIFilterOperator =
| 'equals'
| 'not_equals'
@@ -73,6 +86,8 @@ export interface BIConfig {
values: BIValue[]
filters: BIFilter[]
limit: BIQueryLimit
+ /** null sorts automatically: newest date or highest value first, so top rows survive the LIMIT. */
+ sort?: BISort | null
}
export interface BIEditorState {
@@ -95,14 +110,21 @@ export const DEFAULT_BI_CONFIG: BIConfig = {
values: [],
filters: [],
limit: 1000,
+ sort: null,
}
export function normalizeBIConfig(config: BIConfig): BIConfig {
- if (config.chartType !== ChartDisplayType.TwoDimensionalHeatmap || config.limit <= PIVOT_TABLE_QUERY_LIMIT) {
- return config
+ let normalized = config
+ if (normalized.chartType === ChartDisplayType.TwoDimensionalHeatmap && normalized.limit > PIVOT_TABLE_QUERY_LIMIT) {
+ normalized = { ...normalized, limit: PIVOT_TABLE_QUERY_LIMIT }
+ }
+
+ const sort = normalized.sort
+ if (sort && !getBISortOptions(normalized).some((option) => option.key === sort.key)) {
+ normalized = { ...normalized, sort: null }
}
- return { ...config, limit: PIVOT_TABLE_QUERY_LIMIT }
+ return normalized
}
const BI_AGGREGATIONS = new Set<BIAggregation>([
@@ -310,9 +332,20 @@ export function parseBIEditorState(editorViewValue: unknown, configValue: unknow
}
})
: null
+ const sortCandidate = candidate.sort
+ // undefined tolerates states persisted before sort existed
+ const sort: BISort | null | undefined =
+ sortCandidate === undefined || sortCandidate === null
+ ? null
+ : typeof sortCandidate === 'object' &&
+ typeof sortCandidate.key === 'string' &&
+ (sortCandidate.direction === 'asc' || sortCandidate.direction === 'desc')
+ ? { key: sortCandidate.key, direction: sortCandidate.direction }
+ : undefined
if (
source === undefined ||
+ sort === undefined ||
!Object.values(ChartDisplayType).includes(candidate.chartType as ChartDisplayType) ||
!rows ||
rows.some((field) => !field) ||
@@ -335,6 +368,7 @@ export function parseBIEditorState(editorViewValue: unknown, configValue: unknow
values: values as BIValue[],
filters: filters as BIFilter[],
limit: candidate.limit as BIQueryLimit,
+ sort,
}
const fields = [
...config.rows,
@@ -470,17 +504,131 @@ function filterExpression(filter: BIFilter): string | null {
}
}
-export function buildBIQuery(config: BIConfig): BIQueryBuildResult | null {
- if (!config.source) {
- return null
- }
+interface BIConfiguredValue {
+ value: BIValue
+ expression: string
+}
+
+interface BIQueryParts {
+ rowDimensions: BIDimension[]
+ columnDimensions: BIDimension[]
+ configuredValues: BIConfiguredValue[]
+}
+function computeBIQueryParts(config: BIConfig): BIQueryParts {
const rowDimensions = config.rows
.map((field, index) => ({ alias: dimensionAlias('row', field, index), field }))
.filter(({ field }) => field.expression.trim() || field.name.trim())
const columnDimensions = config.columns
.map((field, index) => ({ alias: dimensionAlias('column', field, index), field }))
.filter(({ field }) => field.expression.trim() || field.name.trim())
+ const configuredValues = config.values
+ .map((value) => ({ value, expression: aggregationExpression(value) }))
+ .filter((configuredValue): configuredValue is BIConfiguredValue => !!configuredValue.expression)
+
+ return { rowDimensions, columnDimensions, configuredValues }
+}
+
+const SORT_AGGREGATION_LABELS: Record<Exclude<BIAggregation, 'custom'>, string> = {
+ count: 'Count',
+ count_distinct: 'Count distinct',
+ sum: 'Sum',
+ average: 'Average',
+ minimum: 'Minimum',
+ maximum: 'Maximum',
+}
+
+function sortValueLabel(value: BIValue): string {
+ if (value.aggregation === 'custom') {
+ return value.customExpression?.trim() || 'Custom value'
+ }
+
+ return `${SORT_AGGREGATION_LABELS[value.aggregation]} of ${value.field.name || value.field.expression}`
+}
+
+export function getBISortOptions(config: BIConfig): BISortOption[] {
+ if (!config.source) {
+ return []
+ }
+
+ const { rowDimensions, columnDimensions, configuredValues } = computeBIQueryParts(config)
+ // Without dimensions the query returns a single aggregate row, so there is nothing to sort
+ if (rowDimensions.length === 0 && columnDimensions.length === 0) {
+ return []
+ }
+
+ // The same field can back several value entries with different aggregations, so value keys
+ // carry an occurrence suffix; the first occurrence keeps the unsuffixed key persisted states use
+ const valueOccurrences = new Map<string, number>()
+ const options: BISortOption[] = [
+ ...rowDimensions.map(({ field }) => ({
+ key: `rows:${field.id}`,
+ label: field.name || field.expression,
+ expression: fieldExpression(field),
+ })),
+ ...columnDimensions.map(({ field }) => ({
+ key: `columns:${field.id}`,
+ label: field.name || field.expression,
+ expression: fieldExpression(field),
+ })),
+ ...(configuredValues.length > 0
+ ? configuredValues.map(({ value }, index) => {
+ const occurrence = valueOccurrences.get(value.field.id) ?? 0
+ valueOccurrences.set(value.field.id, occurrence + 1)
+ return {
+ key: occurrence === 0 ? `values:${value.field.id}` : `values:${value.field.id}:${occurrence + 1}`,
+ label: sortValueLabel(value),
+ expression: escapePropertyAsHogQLIdentifier(aggregationAlias(value, index)),
+ }
+ })
+ : [{ key: 'values:count', label: 'Count', expression: 'count' }]),
+ ]
+
+ const seenKeys = new Set<string>()
+ return options.filter((option) => {
+ if (seenKeys.has(option.key)) {
+ return false
+ }
+ seenKeys.add(option.key)
+ return true
+ })
+}
+
+function buildOrderByExpression(
+ config: BIConfig,
+ dimensions: BIDimension[],
+ configuredValues: BIConfiguredValue[]
+): string | null {
+ if (dimensions.length === 0) {
+ return null
+ }
+
+ const sort = config.sort
+ const selectedOption = sort ? getBISortOptions(config).find((option) => option.key === sort.key) : undefined
+ if (sort && selectedOption) {
+ return `${selectedOption.expression} ${sort.direction === 'asc' ? 'ASC' : 'DESC'}`
+ }
+
+ // Auto sort keeps the most relevant rows inside the LIMIT: newest first for date
+ // dimensions, largest first otherwise
+ const firstDimension = dimensions[0]
+ if (isDateTimeBIField(firstDimension.field)) {
+ return `${fieldExpression(firstDimension.field)} DESC`
+ }
+
+ const firstValueAlias =
+ configuredValues.length > 0
+ ? escapePropertyAsHogQLIdentifier(aggregationAlias(configuredValues[0].value, 0))
+ : 'count'
+ return `${firstValueAlias} DESC`
+}
+
+export function buildBIQuery(config: BIConfig): BIQueryBuildResult | null {
+ if (!config.source) {
+ return null
+ }
+
+ const { rowDimensions, columnDimensions, configuredValues } = computeBIQueryParts(config)
const dimensions = [...rowDimensions, ...columnDimensions]
const dimensionExpressions = dimensions.map(({ field }) => fieldExpression(field))
const isPivotTable = config.chartType === ChartDisplayType.TwoDimensionalHeatmap
@@ -491,11 +639,6 @@ export function buildBIQuery(config: BIConfig): BIQueryBuildResult | null {
.filter((axis): axis is BIPivotAxis => axis !== null)
.map(({ alias, expression }) => `${expression} AS ${alias}`)
: dimensionExpressions
- const configuredValues = config.values
- .map((value) => ({ value, expression: aggregationExpression(value) }))
- .filter(
- (configuredValue): configuredValue is { value: BIValue; expression: string } => !!configuredValue.expression
- )
const valueExpressions =
configuredValues.length > 0
? configuredValues.map(
@@ -525,6 +668,11 @@ export function buildBIQuery(config: BIConfig): BIQueryBuildResult | null {
queryParts.push(`GROUP BY\n ${dimensionExpressions.join(',\n ')}`)
}
+ const orderByExpression = buildOrderByExpression(config, dimensions, configuredValues)
+ if (orderByExpression) {
+ queryParts.push(`ORDER BY\n ${orderByExpression}`)
+ }
+
queryParts.push(`LIMIT ${normalizeBIConfig(config).limit}`)
const query = queryParts.join('\n')
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
index 72b499ff0c93..30ae629ba9c4 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
@@ -1508,6 +1508,7 @@ describe('sqlEditorLogic', () => {
values: [],
filters: [{ field: eventField, operator: 'equals', value: 'signup' }],
limit: 1000,
+ sort: null,
}
const configEventProperties = {
source_kind: 'project_data',
@@ -1521,6 +1522,8 @@ describe('sqlEditorLogic', () => {
filter_operator_types: ['equals'],
date_bucket_types: [],
custom_expression_count: 0,
+ sort_kind: 'auto',
+ sort_direction: null,
}
it('captures BI mode selection and query runs without query contents', async () => {