Three directives carry the sort surface: @defaultOrder sets a static fallback on a field, @orderBy takes a runtime argument, and @order attaches a sort spec to each value of the bound enum. All three share the same column-source shape: exactly one of index:, fields:, or primaryKey:. This recipe covers picking among them, mixing static and dynamic ordering on the same field, cursor stability under pagination, and the collation and tie-breaker pitfalls that bite at scale.
Pick the column source
The three column sources are mutually exclusive on any one directive site; the build rejects setting two or none. Pick by which kind of identity the sort needs:
-
primaryKey: truewhen the order is "stable, in declaration order". This is the default for any paginated@tablefield that omits@defaultOrder, so most fields do not need to spell it out. Spell it out explicitly when you want the intent to survive a refactor that adds@orderBy. -
fields:when the order is "by these named columns, in this order". Optionalcollate:per column. The columns resolve against the return-type’s@table, not the parent’s; an entry can also sort by a column on a related table or by a key a method derives (see Sort by a value on another table). -
index:when an existing database index already projects the right column list (often a multi-column index that pairs the sort key with frequently-filtered columns). Requires<includeIndexes>true</includeIndexes>on the jOOQ generator; otherwise the catalog lookup throws "no matching index" at startup.
A field-based order is the usual choice for "humans want this column":
type Query {
customers: [Customer!]! @asConnection
@defaultOrder(fields: [
{name: "LAST_NAME", collate: "case_insensitive"},
{name: "FIRST_NAME", collate: "case_insensitive"},
{name: "CUSTOMER_ID"}
])
}
CUSTOMER_ID at the end pins the cursor onto a unique key so two rows with identical (last_name, first_name) page deterministically. On a connection or a list you could leave it out: graphitron appends the primary key to any order that does not already identify a row (see Stable cursors and tie-breakers). Listing it yourself changes nothing, and is still the way to put it somewhere other than last.
Static order: @defaultOrder
@defaultOrder is the field-level "this is how this list comes back when nobody asks otherwise". Every example-schema connection field uses it:
type Query {
stores: [Store!]! @asConnection @defaultOrder(primaryKey: true)
filmsConnection(
first: Int, last: Int, after: String, before: String
): FilmsConnection! @defaultOrder(primaryKey: true)
}
The direction: argument is global across the spec: every column in the list sorts the same way. There is no per-column direction surface on @defaultOrder itself; if your design needs per-column direction (e.g. LAST_NAME ASC, RECENT_LOGIN DESC), you have already crossed into "this should be a client choice", and the right tool is @orderBy (each row of the input list carries its own SortDirection).
@defaultOrder is required on @asConnection fields that don’t carry @orderBy; keyset pagination has no anchor without one and the build fails. Connections that only accept dynamic order (@orderBy with no fallback) are not a supported shape; supply @defaultOrder as the fallback for the no-argument case.
Dynamic order: @orderBy and @order
@orderBy activates a runtime argument whose input type binds two fields by type, not by name: one SortDirection enum (the project’s, declared once and reused) and one enum whose values carry @order. The example schema exposes the dynamic shape on filmsOrderedConnection:
type Query {
filmsOrderedConnection(
rating: MpaaRating @field(name: "RATING"),
order: [FilmOrderBy] @orderBy,
first: Int, last: Int, after: String, before: String
): FilmsConnection! @defaultOrder(primaryKey: true)
}
input FilmOrderBy {
field: FilmSort!
direction: SortDirection
}
enum FilmSort {
FILM_ID @order(primaryKey: true)
TITLE @order(fields: [{name: "title"}])
}
enum SortDirection { ASC, DESC }
A request asking order: [{ field: TITLE, direction: ASC }, { field: FILM_ID, direction: ASC }] sorts by title then film_id; the rewrite emits a per-element case "TITLE" → … case "FILM_ID" → … switch in the generated <fieldName>OrderBy(env, srcAlias) helper, building a List<SortField<?>> plus a parallel List<Field<?>> of the same columns for cursor encoding.
The list shape [FilmOrderBy] lets clients compose multi-key orderings; a singular FilmOrderBy argument also works when only one column is ever needed. Either way the cursor binds onto whichever ordering was active for that request.
When @orderBy and @defaultOrder coexist on the same field, the dynamic argument wins when the client supplies it; @defaultOrder fills in when the argument is null or absent. This is why the example field has both: filmsOrderedConnection falls back to PK order when order: is not supplied, and uses the client’s order when it is.
Stable cursors and tie-breakers
@asConnection emits keyset pagination using the active order. The cursor holds the sort columns' values for the last row of the page, in the format How-to: Connections states; jOOQ’s .seek(Field<?>…) consumes the decoded values. Two consequences:
-
The order columns are part of the cursor’s wire bytes. Adding a column to
@defaultOrderor to an@orderenum value invalidates cursors clients have already issued. New cursors decode against the new column list; old cursors decode the wrong number of values and the request fails. Treat the column list and order as part of the public cursor contract. -
Determinism gates "the next page is always the next page". If two rows compare equal on every order column, a seek from the first steps over the second. Graphitron therefore makes every connection’s order identify a row. When the columns you list do not include the table’s primary key (or another key that identifies a row: the type’s
@nodekey, or a unique key whose columns are allNOT NULL), graphitron appends the primary key after them, in the direction of your last column. The appended columns are part of the cursor.@defaultOrder(fields: [{name: "rental_rate", direction: DESC}, {name: "title"}])pages onrental_rate DESC, title ASC, film_id ASC. Listing the key yourself changes nothing, and is still the way to put it somewhere other than last.For a list-valued
@orderByargument the key goes after the whole sequence the client sends, not after each value, and it takes the direction of the last value; with a single-valued argument it is part of each@ordervalue and flips with a runtimedirection:where that value does. Plain lists and child lists are completed the same way, in the same direction: without a cursor a tie never drops a row, but the database is free to return tied rows in a different order from one execution to the next, so graphitron fixes the tie order for them as well. A list that declares no@defaultOrderfalls back on the primary key of the table its target type is bound to, which identifies a row, so there is nothing to append. A list with nothing to fall back on (a table with no primary key, or a function’s result whose type is bound to no table) and no@defaultOrderfails the build withLIST_ORDER_UNDETERMINED, unless its@orderByargument is non-null and single-valued: a nullable one is no order stated, since a client may leave it out, and a list may be sent empty. The fix is@defaultOrdernaming the result’s columns withfields:, or a non-null, single-valued@orderByargument. A field that hops on to a table after a routine (@reference) falls back on that table’s key. Where there is no key at all (a view without a synthetic primary key, a function result bound to no table), the listed columns have nothing appended to them. The build warns under the lint ruleconnection-order-not-uniquefor a connection andlist-order-not-uniquefor a list, and the listed columns have to be unique on their own.A list whose declared order did not identify a row used to leave tied rows in whatever order the database returned them; they now come back ordered by the key. Consumers that read the old, unspecified order see a defined one, which can differ from what they saw before.
Backward pagination (last:/before:) reuses the same cursor encoding; the rewrite reverses each SortField’s direction and its null placement via jOOQ’s `$field()/$sortOrder()/$nullOrdering() model API, runs the seek, and returns rows in the original order. This means a cursor issued from a first: page round-trips correctly through a before: request and vice versa, without any per-direction encoding split.
Where NULL sorts
An order column that admits NULL sorts its NULL rows last, in both directions: @defaultOrder(fields: [{name: "length"}], direction: DESC) orders length DESC NULLS LAST, the longest films first and the films with no length after them. The same holds on plain lists and connections, on single-table and multi-table fields, for @defaultOrder, @orderBy and @order alike. A backward page (last:/before:) and a runtime direction: keep the NULL rows at the end rather than mirroring them to the front. A column declared NOT NULL is rendered with no null placement, since none is observable.
On a connection the seek pages through the NULL rows too: after the last non-null value come the NULL rows, in the order of the key graphitron appends (see Stable cursors and tie-breakers), and a cursor taken inside that run continues within it. Every column of a view counts as admitting NULL, because the database catalog reports it so whatever the data holds.
For an index to serve such an order: ASC NULLS LAST is what a plain b-tree index stores, so it serves an ascending order scanned forward for first: and backward for last:. DESC NULLS LAST is not the mirror of that index; on a table large enough for the sort to matter, declare the index DESC NULLS LAST to serve a descending order on a nullable column.
Sort by a value on another table
A FieldSort entry normally names a column of the field’s own table. Two more forms sort by a value that lives elsewhere, without copying it into that table: path: for a column on a related table, and method: for a key you derive in Java. Both work in @defaultOrder and in @order enum values, on lists and connections, and graphitron keeps owning the direction, the cursor and keyset paging.
A column on a to-one related table: path:
path: walks from the field’s table to the table that holds the column, in the same element shape as @reference(path:); name: is then resolved against the table the path lands on. In the example schema film.original_language_id is a nullable foreign key to language:
type Query {
filmsByOriginalLanguage(first: Int, last: Int, after: String, before: String): FilmsConnection!
@defaultOrder(fields: [{name: "name", path: [{key: "film_original_language_id_fkey"}]}])
}
enum FilmLanguageSort {
ORIGINAL_LANGUAGE @order(fields: [{name: "name", path: [{key: "film_original_language_id_fkey"}]}])
}
A film with no original language sorts on NULL, which sorts last in both directions (see Where NULL sorts).
Every hop must be to-one: each row reaches at most one related row, so each row has exactly one sort key. The build checks this against the jOOQ catalog: a hop is to-one when the columns it joins on cover the primary key or a unique key of the table it reaches. A child-to-parent foreign key passes, and so does a one-to-one extension whose foreign key is itself unique, even when that key admits NULL. A hop that can reach several rows fails the build, naming the hop and the direction it fans out in, because ordering by one of many related rows would pick an arbitrary one. There is no opt-out.
A hop may not carry a condition:, and every hop names a key: or a table:; there is no inferred or empty path, so a column name never silently changes table. method: is the form for any rule about which related row counts.
A key you derive: method:
When the value has to come from several related rows (the latest of a film’s copies, the current one of a record’s names), supply the sort key through method:, a static method with @externalField's calling convention: it takes the field’s jOOQ table, receives the alias the generated query uses, and returns a Field<X> that is that row’s sort key.
type Query {
filmsByLatestStock(first: Int, last: Int, after: String, before: String): FilmsConnection!
@defaultOrder(fields: [{
method: {className: "com.example.FilmSortKeys", method: "latestStockStore"},
direction: DESC
}])
}
public static Field<Integer> latestStockStore(Film film) {
var stock = INVENTORY.as("latest_stock");
return DSL.field(DSL.select(stock.STORE_ID).from(stock)
.where(stock.FILM_ID.eq(film.FILM_ID))
.orderBy(stock.INVENTORY_ID.desc())
.limit(1));
}
The rule for which related row counts lives once, in the method, and the same method can back an @externalField when the value should also be selectable. method is required inside the reference, since there is no field name to default it from, and argMapping: is not supported. The build cannot see inside the method: if it returns more than one row per parent, the database rejects the query at runtime, as it does any scalar subquery that does.
If you would rather keep the rule in the database, a view with a unique key on the parent’s id plus a jOOQ synthetic foreign key to it makes the hop to-one, and path: then serves the same case with no Java code.
How they combine
-
An entry sets exactly one of
name:andmethod:;path:is only valid besidename:.method:withpath:fails the build, since the method already receives the field’s table. -
On a connection or a list, only the field’s own columns count toward identifying a row. A related-table column never does, even when it is that table’s primary key, because many rows can share one related row; a
method:key never does either. An order made only of such entries therefore always has the key appended, even when a related column is named like one of the field’s own key columns (see Stable cursors and tie-breakers). -
Neither form is available on a multi-table interface or union, or over a table-valued function result.
-
A to-one
path:key is an indexed key lookup per row, evaluated for the sort; amethod:key costs what its query costs.
Collation pitfalls
fields[].collate: is passed verbatim to the database. PostgreSQL applies the collation per column at sort time:
enum PersonOrderByField {
NAME_NORSK @order(fields: [
{name: "LAST_NAME", collate: "xdanish_ai"},
{name: "FIRST_NAME", collate: "xdanish_ai"}
])
}
Three things to know before reaching for collation:
-
Misspelled collations surface only at query time, not at build time. The catalog does not validate collation names. A typo emits valid SQL that the database rejects when the request runs.
-
Indexes follow collations. An index built without
COLLATE "xdanish_ai"will not be used for an ordering that names that collation; the planner falls back to a sort. Either build the index with the matching collation or accept the per-page sort cost. -
Cursor stability survives collation changes only if both ends agree. If a database upgrade reweights
case_insensitive’s tertiary tiebreak, cursors issued before the upgrade may decode to a position that no longer corresponds to the same row. This is rare and database-specific; the recipe is "treat collation changes as a hard cursor cut", same as `keyColumnsin@node.
Index-based sorting
@order(index: "IDX_TITLE") and @defaultOrder(index: "IDX_TITLE") reuse a database index’s column list as the sort spec. The lookup happens at build time against the jOOQ-generated catalog, so the column list is fixed at generator time and stays in sync with the schema migration that created the index.
Use indexed orders when:
-
The index already exists for query-planner reasons (it pairs the sort columns with the most common filter columns) and you want the GraphQL order to ride on the same column list. Single source of truth for "what’s the canonical order for this list".
-
The index encodes a multi-column order that would be tedious to maintain twice (in DDL and in a
fields:list).
Avoid them when:
-
The index might be dropped, renamed, or rebuilt with a different column list during operations. The build resolves the index name at generator time; a subsequent DDL change that drops the index makes the next build fail with "no matching index". For volatile indexes, prefer
fields:. -
<includeIndexes>true</includeIndexes>is not enabled on the jOOQ generator. The catalog lookup returns nothing in that case and the directive cannot resolve.
Sort across polymorphism
A field returning a multi-table polymorphic interface or union is read as one statement per participant, combined with UNION ALL. Every branch projects its participant’s primary-key columns, and the combined result is ordered on those columns, position by position, then on the participant’s type name. The order is on plain columns, so it comes out the same on every database: a composite key (1, 10) sorts after (1, 2).
On a root Query field returning a list or a connection, @defaultOrder and @orderBy are lowered onto the participant branches. Each declared column is resolved per participant against that participant’s own table and projected into every branch as its own column, so the combined result sorts by what was declared, with rows of different participants interleaved by the sort column. An @orderBy argument picks among its enum values at request time, and direction: reverses the whole order exactly as on a single-table field. A value that orders by the primary key (@order(primaryKey: true), @defaultOrder(primaryKey: true), or the fallback when nothing else is declared) sorts by the primary-key columns directly.
At each primary-key position the participants' columns must bind to the same Java type, and to the same database type behind any converter; a difference is a build error naming the position and both columns. Columns whose SQL type names differ but which bind alike (a text key beside a varchar one, or Oracle NUMBER keys of different precision that jOOQ binds to the same class) are fine. The rule compares the database type a converter reads, not the converter, so two keys converted to one Java type from different database types (a Converter<Integer, String> beside a Converter<Long, String>) are rejected too.
Every participant has to carry each order column, at the same position in the order, with the same SQL type and the same bound Java type. A participant missing the column fails the build at that participant, and so does a type disagreement: integer against bigint, varchar against text, or a column exposed through a jOOQ converter against one read without it, even when both bind to the same Java class. A converter-backed column therefore orders a union only against columns bound the same way. An index: order has to resolve to the same number of columns on every participant.
A multi-table ordering gets its tie-breaker appended differently from a single-table connection: the primary-key columns and then the participant typename follow the declared columns, on lists and connections alike, and they flip with a runtime direction: where the order itself does. The typename is the part specific to multitable. Two participants can hold equal values on every declared column (and equal primary-key values besides), and without it the cursor would have no defined next row across the participant boundary. On a field whose own declaration already ends in a unique key, the appended columns are inert.
A child field returning a multi-table interface or union, and a single-valued root field, lower no ordering: declaring @defaultOrder or @orderBy on one fails the build rather than being ignored. Sort a single-@table field there instead, or narrow the field’s return type to one participant.
For single-table polymorphism, ordering is unchanged from the non-polymorphic case: the discriminator column is just another projected column, and the sort spec applies to the shared backing table.
Constraints and pitfalls
-
Exactly one of
index:,fields:, orprimaryKey:per@ordervalue and per@defaultOrderdirective. Multiple or none fails the build. -
@orderByargument input types bind by type, not by name. The input must contain exactly oneSortDirection-typed field and exactly one@order-bearing enum field. Field names are free. -
Every value of an
@orderBy-bound enum must declare a sort spec. Missing values fail the build with a per-value diagnostic. -
@defaultOrder.direction:is global across the spec; per-column direction is only available through@orderBy(each list element carries its ownSortDirection). -
Cursor wire format embeds the active order’s columns. Adding, removing, or reordering columns in
@defaultOrderor in an@orderenum value invalidates outstanding cursors. -
Connection orders that do not identify a row get the table’s key appended, which is part of the cursor. Changing a table’s primary key invalidates outstanding cursors on its connections.
-
index:requires jOOQ index generation. With it disabled, the lookup yields no columns and the directive fails to resolve. -
fields[].nameresolves against the field’s return-type@table, not the parent’s, or against the table itspath:lands on. Case-sensitive against the jOOQ-generated identifiers. -
A
path:follows to-one hops only, and carries nocondition:; a key derived from many related rows goes throughmethod:(see Sort by a value on another table). -
collate:is unvalidated at build time; misspellings surface as runtime database errors.
See also
-
@defaultOrdersets the static order on a field. -
@orderByactivates a runtime argument. -
@orderattaches a sort spec to each enum value. -
@asConnectionis the cursor-pagination wrapper that consumes the resolved order. -
How-to: Cursor-paginated connections covers the one-field-one-connection rule,
totalCountperformance, and what the rewrite does about page-size caps.