Design REST API sorting: define allowed keys and a stable order
API sorting defines the order in which a collection is returned. OData uses $orderby, but REST APIs vary in the syntax they support. For paged lists or repeatable reads, state the sort explicitly and include a unique tie-breaker; do not let clients inject arbitrary database expressions.
API sorting defines the order in which a collection is returned. OData uses $orderby, but REST APIs vary in the syntax they support. For paged lists or repeatable reads, state the sort explicitly and include a unique tie-breaker; do not let clients inject arbitrary database expressions.
Define the client sort contract
OData $orderby accepts one or more properties with ascending asc or descending desc directions. When omitted, ascending is the usual default in OData examples and relational databases, but an API should state its default in the contract. For example, this request puts newest products first and uses ID to order equal timestamps:
GET /api/products?$orderby=createdAt desc,id ascThis is OData-style syntax. Document sortable fields, whether multiple keys are allowed, each field's direction, default order, null placement, string comparison rules, and errors for invalid or disallowed fields. ASP.NET Core OData query options are not enabled by default; a service can enable only selected options and apply them to specific endpoints.
Validate sort requests with an allowlist
A sort key selects a database column or expression; it is not an ordinary value. Binding values as parameters does not safely substitute a column name in ORDER BY, so do not concatenate client field names into a query string. Map API field names to server-selected query expressions through an allowlist, and accept only directions permitted for each field.
For example, createdAt might map to created_at, while price maps to a bounded price expression. Reject unknown fields, invalid directions, or too many sort keys with documented errors. Decide separately whether users may sort by properties they cannot see. Hiding a field in the response does not prevent its value from leaking through ordering patterns or timing.
Handle ties, pagination, and changing data
Rows with equal sort values have no defined relative order without another key. For pagination, add a unique tie-breaker such as an ID as the final sort key. createdAt desc,id asc, for example, defines order even when timestamps match. PostgreSQL recommends an ORDER BY that establishes a unique order when LIMIT is used to obtain a predictable subset.
A unique order makes page boundaries repeatable for the same data state, but rows can move if sort keys or records change while reading. Guaranteeing a snapshot that prevents duplicates or omissions across pages is a separate consistency policy. Whatever pagination method is used—offset, cursor, or keyset—the sort order and keys must remain the same across pages.
Check semantics and datastore cost
Sorting depends on value types and comparison rules. Null placement, case and accent handling, and locale-aware string ordering can depend on database and collation settings, so specify required behavior in the contract. PostgreSQL puts nulls last by default for ascending order and first for descending order; another database or API may behave differently.
Many combinations of sort fields and directions can make indexing every case impractical. PostgreSQL B-tree indexes can provide sorted output and may help retrieve the first rows for some ORDER BY plus LIMIT queries. Indexes also add write and maintenance cost, and whether an index scan or explicit sort is better depends on selectivity and the plan. Measure real filter, sort, and page-size combinations and inspect query plans.
Implementation checklist
Document allowed sort fields and directions, defaults, null placement, and string comparison rules.
Parse each request and check fields, directions, and key count against server allowlists and limits.
Map allowed field names to server query expressions; do not build SQL from raw client text.
For pagination, append a unique tie-breaker and keep the ordering fixed across pages.
Check ties, nulls, case and locale behavior, rejected fields, large results, and representative query plans.
Sources
[OData: Query options overview — `$orderby`](https://learn.microsoft.com/en-us/odata/concepts/queryoptions-overview)
[ASP.NET Core OData 8: Fundamentals overview](https://learn.microsoft.com/en-us/odata/webapi-8/fundamentals/overview)
[PostgreSQL 17: Sorting Rows (`ORDER BY`)](https://www.postgresql.org/docs/17/queries-order.html)
[PostgreSQL 15: Indexes and `ORDER BY`](https://www.postgresql.org/docs/15/indexes-ordering.html)
[PostgreSQL 18: `SELECT`, `ORDER BY`, and `LIMIT`](https://www.postgresql.org/docs/current/sql-select.html)
[OWASP: SQL Injection Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html)