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(data-table): Persist table sort on column configurations (#57214)

Arthur Moreira de Deus830ac792f8c4
diff --git a/frontend/src/queries/nodes/DataTable/TableView/tableViewLogic.ts b/frontend/src/queries/nodes/DataTable/TableView/tableViewLogic.ts
index 2439a427aa69..61a15bfafc95 100644
--- a/frontend/src/queries/nodes/DataTable/TableView/tableViewLogic.ts
+++ b/frontend/src/queries/nodes/DataTable/TableView/tableViewLogic.ts
@@ -57,6 +57,7 @@ function getViewData(
...(visibility && { visibility }),
columns: props.query.select,
filters: props.query.properties,
+ order_by: props.query.orderBy ?? [],
}
}
const event: EventSyntheticMarker = {
@@ -77,6 +78,7 @@ function getViewData(
...(visibility && { visibility }),
columns: props.query.select,
filters: [...(props.query.properties || []), event, events],
+ order_by: props.query.orderBy ?? [],
}
}
@@ -92,11 +94,14 @@ function getQueryFromView(
query: TableViewSupportedQueryType,
view: ColumnConfigurationApi
): TableViewSupportedQueryType {
+ const orderByOverride = view.order_by != null ? { orderBy: view.order_by } : {}
+
if (!isEventsQuery(query)) {
return {
...query,
select: view.columns || [],
properties: view.filters || [],
+ ...orderByOverride,
} as TableViewSupportedQueryType
}
@@ -114,6 +119,7 @@ function getQueryFromView(
properties,
event,
events,
+ ...orderByOverride,
} as EventsQuery
}
diff --git a/posthog/api/column_configuration.py b/posthog/api/column_configuration.py
index 3a46114cd026..46ef4c134b2a 100644
--- a/posthog/api/column_configuration.py
+++ b/posthog/api/column_configuration.py
@@ -19,6 +19,13 @@ from posthog.models import ColumnConfiguration
class ColumnConfigurationSerializer(serializers.ModelSerializer):
filters = serializers.JSONField(required=False, default=dict)
+ order_by = serializers.ListField(
+ child=serializers.CharField(),
+ required=False,
+ allow_null=True,
+ allow_empty=True,
+ help_text="Ordered list of HogQL expressions describing the table sort. Null preserves the current sort on apply (legacy rows); an empty list explicitly means no sort.",
+ )
class Meta:
model = ColumnConfiguration
@@ -28,6 +35,7 @@ class ColumnConfigurationSerializer(serializers.ModelSerializer):
"columns",
"name",
"filters",
+ "order_by",
"visibility",
"created_by",
"created_at",
@@ -91,6 +99,17 @@ class ColumnConfigurationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
if len(columns) > 100:
return Response({"error": "cannot configure more than 100 columns"}, status=400)
+ order_by = request.data.get("order_by")
+ if order_by is not None:
+ if not isinstance(order_by, list):
+ return Response({"error": "order_by must be a list"}, status=400)
+
+ if not all(isinstance(item, str) for item in order_by):
+ return Response({"error": "all order_by entries must be strings"}, status=400)
+
+ if len(order_by) > 100:
+ return Response({"error": "cannot order by more than 100 expressions"}, status=400)
+
return super().create(request, *args, **kwargs)
def perform_create(self, serializer):
diff --git a/posthog/api/test/test_column_configuration.py b/posthog/api/test/test_column_configuration.py
index 278dea52566c..7e8fac5b9c7b 100644
--- a/posthog/api/test/test_column_configuration.py
+++ b/posthog/api/test/test_column_configuration.py
@@ -1,5 +1,6 @@
from posthog.test.base import APIBaseTest
+from parameterized import parameterized
from rest_framework import status
from posthog.models import ColumnConfiguration, User
@@ -23,6 +24,7 @@ class TestColumnConfigurationAPI(APIBaseTest):
assert data["name"] == "Column configuration", "Should have default name"
assert data["visibility"] == ColumnConfiguration.Visibility.SHARED, "Should have default visibility"
assert data["filters"] == []
+ assert data["order_by"] is None, "order_by defaults to null when not supplied"
def test_create_column_configuration_empty_objects_filters(self):
response = self.client.post(
@@ -246,6 +248,78 @@ class TestColumnConfigurationAPI(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "cannot configure more than 100 columns" in response.json()["error"]
+ @parameterized.expand(
+ [
+ ("populated", ["timestamp DESC"]),
+ ("empty list (distinct from null)", []),
+ ]
+ )
+ def test_create_with_order_by(self, _name: str, order_by: list[str]):
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/column_configurations/",
+ {
+ "context_key": "people-list",
+ "columns": ["*", "person", "timestamp"],
+ "order_by": order_by,
+ },
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED
+ assert response.json()["order_by"] == order_by
+
+ @parameterized.expand(
+ [
+ ("non-list", "timestamp DESC", "order_by must be a list"),
+ ("non-string entry", ["timestamp DESC", 5], "all order_by entries must be strings"),
+ ("too many entries", [f"col_{i}" for i in range(101)], "cannot order by more than 100 expressions"),
+ ]
+ )
+ def test_invalid_order_by_is_rejected(self, _name: str, order_by, expected_error: str):
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/column_configurations/",
+ {
+ "context_key": "people-list",
+ "columns": ["*", "person", "timestamp"],
+ "order_by": order_by,
+ },
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert expected_error in response.json()["error"]
+
+ def test_legacy_row_serializes_order_by_as_null(self):
+ config = ColumnConfiguration.objects.create(
+ team=self.team,
+ context_key="people-list",
+ columns=["*", "person", "timestamp"],
+ )
+
+ response = self.client.get(
+ f"/api/environments/{self.team.id}/column_configurations/{config.id}/",
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["order_by"] is None
+
+ def test_update_order_by(self):
+ create_response = self.client.post(
+ f"/api/environments/{self.team.id}/column_configurations/",
+ {
+ "context_key": "people-list",
+ "columns": ["*", "person", "timestamp"],
+ "order_by": ["timestamp DESC"],
+ },
+ )
+ config_id = create_response.json()["id"]
+
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}/column_configurations/{config_id}/",
+ {"order_by": ["person.created_at ASC"]},
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["order_by"] == ["person.created_at ASC"]
+
def test_team_isolation(self):
other_team = self.organization.teams.create(name="Other Team")
diff --git a/posthog/migrations/1147_columnconfiguration_order_by.py b/posthog/migrations/1147_columnconfiguration_order_by.py
new file mode 100644
index 000000000000..988a52e3ec04
--- /dev/null
+++ b/posthog/migrations/1147_columnconfiguration_order_by.py
@@ -0,0 +1,24 @@
+# Generated by Django 5.2.13 on 2026-04-30 19:46
+
+import django.contrib.postgres.fields
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1146_subscription_enabled"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="columnconfiguration",
+ name="order_by",
+ field=django.contrib.postgres.fields.ArrayField(
+ base_field=models.TextField(),
+ blank=True,
+ default=None,
+ null=True,
+ size=None,
+ ),
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index 5f649ddf0d57..87f940da0f72 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1146_subscription_enabled
+1147_columnconfiguration_order_by
diff --git a/posthog/models/column_configuration.py b/posthog/models/column_configuration.py
index 3166c6b64221..e2beb0de0e6f 100644
--- a/posthog/models/column_configuration.py
+++ b/posthog/models/column_configuration.py
@@ -15,6 +15,7 @@ class ColumnConfiguration(UUIDModel):
context_key = models.CharField(max_length=255, db_index=True)
columns = ArrayField(models.TextField(), null=False, blank=False, default=list)
filters = models.JSONField(default=dict, null=True, blank=True)
+ order_by = ArrayField(models.TextField(), null=True, blank=True, default=None)
visibility = models.CharField(max_length=10, choices=Visibility, default=Visibility.SHARED)
created_by = models.ForeignKey("posthog.User", on_delete=models.CASCADE, null=True)
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 36778e7cf426..3802129e1d70 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -26,6 +26,11 @@ export interface ColumnConfigurationApi {
/** @maxLength 255 */
name?: string
filters?: unknown
+ /**
+ * Ordered list of HogQL expressions describing the table sort. Null preserves the current sort on apply (legacy rows); an empty list explicitly means no sort.
+ * @nullable
+ */
+ order_by?: string[] | null
visibility?: VisibilityEnumApi
/** @nullable */
readonly created_by: number | null
@@ -50,6 +55,11 @@ export interface PatchedColumnConfigurationApi {
/** @maxLength 255 */
name?: string
filters?: unknown
+ /**
+ * Ordered list of HogQL expressions describing the table sort. Null preserves the current sort on apply (legacy rows); an empty list explicitly means no sort.
+ * @nullable
+ */
+ order_by?: string[] | null
visibility?: VisibilityEnumApi
/** @nullable */
readonly created_by?: number | null
diff --git a/products/product_analytics/frontend/generated/api.zod.ts b/products/product_analytics/frontend/generated/api.zod.ts
index f141db6db376..1a148702ba08 100644
--- a/products/product_analytics/frontend/generated/api.zod.ts
+++ b/products/product_analytics/frontend/generated/api.zod.ts
@@ -18,6 +18,12 @@ export const ColumnConfigurationsCreateBody = /* @__PURE__ */ zod.object({
columns: zod.array(zod.string()).optional(),
name: zod.string().max(columnConfigurationsCreateBodyNameMax).optional(),
filters: zod.unknown().optional(),
+ order_by: zod
+ .array(zod.string())
+ .nullish()
+ .describe(
+ 'Ordered list of HogQL expressions describing the table sort. Null preserves the current sort on apply (legacy rows); an empty list explicitly means no sort.'
+ ),
visibility: zod
.enum(['private', 'shared'])
.optional()
@@ -33,6 +39,12 @@ export const ColumnConfigurationsUpdateBody = /* @__PURE__ */ zod.object({
columns: zod.array(zod.string()).optional(),
name: zod.string().max(columnConfigurationsUpdateBodyNameMax).optional(),
filters: zod.unknown().optional(),
+ order_by: zod
+ .array(zod.string())
+ .nullish()
+ .describe(
+ 'Ordered list of HogQL expressions describing the table sort. Null preserves the current sort on apply (legacy rows); an empty list explicitly means no sort.'
+ ),
visibility: zod
.enum(['private', 'shared'])
.optional()
@@ -48,6 +60,12 @@ export const ColumnConfigurationsPartialUpdateBody = /* @__PURE__ */ zod.object(
columns: zod.array(zod.string()).optional(),
name: zod.string().max(columnConfigurationsPartialUpdateBodyNameMax).optional(),
filters: zod.unknown().optional(),
+ order_by: zod
+ .array(zod.string())
+ .nullish()
+ .describe(
+ 'Ordered list of HogQL expressions describing the table sort. Null preserves the current sort on apply (legacy rows); an empty list explicitly means no sort.'
+ ),
visibility: zod
.enum(['private', 'shared'])
.optional()
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 284f114f1281..3fd87824ab14 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -9209,6 +9209,11 @@ export namespace Schemas {
/** @maxLength 255 */
name?: string;
filters?: unknown;
+ /**
+ * Ordered list of HogQL expressions describing the table sort. Null preserves the current sort on apply (legacy rows); an empty list explicitly means no sort.
+ * @nullable
+ */
+ order_by?: string[] | null;
visibility?: VisibilityEnum;
/** @nullable */
readonly created_by: number | null;
@@ -27473,6 +27478,11 @@ export namespace Schemas {
/** @maxLength 255 */
name?: string;
filters?: unknown;
+ /**
+ * Ordered list of HogQL expressions describing the table sort. Null preserves the current sort on apply (legacy rows); an empty list explicitly means no sort.
+ * @nullable
+ */
+ order_by?: string[] | null;
visibility?: VisibilityEnum;
/** @nullable */
readonly created_by?: number | null;