LakeQL
Overview
  • Introduction
Filtering
  • Where Interface
  • Operators
  • Combining Filters
Sorting and Paging
  • Sorting
  • Paging
  • API Reference
GitHub
LakeQL
  1. Query Builder
  2. Sorting and Paging
  3. Sorting

On this page

  1. SortInput Interface
  2. Multiple Sort Fields
  3. transformFields Integration
  4. Why Sorting Matters for Paging

Sorting

Multi-field sorting with configurable direction for query results.

SortInput Interface #

PropertyType
fieldSelectExpression< KyselyDatabase<TableDefinition>, keyof KyselyDatabase<TableDefinition> >

Column name to sort by. Constrained to valid column names from the table type.

directionstring

Sort direction — "asc" for ascending, "desc" for descending.

Each SortInput specifies a column to order by and the sort direction. The field property uses Kysely's SelectExpression type for type safety, but in practice it's a string matching a column name.

Multiple Sort Fields #

The sorting parameter accepts an array. Fields are applied in order — the first entry is the primary sort key, subsequent entries are secondary, tertiary, etc.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21import { generateQuery } from "@lakeql/query-builder"

interface OrderTable {
  id: number
  status: string
  created_at: string
  customerName: string
}

const compiled = generateQuery<OrderTable>({
  catalog: "hive",
  schema: "sales",
  table: "orders",
  selectFields: ["id", "status", "created_at"],
  userQuery: {},
  sorting: [
    { field: "status", direction: "asc" },
    { field: "created_at", direction: "desc" },
  ],
})

Produces:

1
2
ORDER BY "status" ASC, "created_at" DESC

transformFields Integration #

If a sorted field has a mapping in transformFields, the query builder uses the database column name in the ORDER BY clause:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { generateQuery } from "@lakeql/query-builder"

interface OrderTable {
  id: number
  status: string
  created_at: string
  customerName: string
}

const compiled = generateQuery<OrderTable>({
  catalog: "hive",
  schema: "sales",
  table: "orders",
  selectFields: ["id", "status", "created_at"],
  userQuery: {},
  sorting: [{ field: "customerName", direction: "asc" }],
  transformFields: { customerName: "customer_name" },
})

Produces:

1
2
ORDER BY "customer_name" ASC

Why Sorting Matters for Paging #

Without at least one sort field, Trino does not guarantee row ordering between pages. This means a client paginating through results might see duplicate rows or miss rows entirely. Always provide at least one deterministic sort key (such as a primary key or timestamp) when using pagination.

Previous page

Sorting and Paging

Next page

Paging

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21