Implementing Sorting

1. Using Sort Query Parameter

PatternExample
Single field?sort=name
Multi-field?sort=name,createdAt
Object style?sort[name]=asc&sort[createdAt]=desc

2. Implementing Multi-Field Sorting

Example: Multi-Field Sort

GET /users?sort=-createdAt,name
# 1. createdAt DESC
# 2. name ASC (tie-breaker)

3. Specifying Sort Direction

StyleAscendingDescending
Prefix+name (or no prefix)-name
Suffixname:ascname:desc
Paramsort=name&order=ascsort=name&order=desc

4. Using Plus/Minus Prefix

JSON:API standard convention.

ParamResult
?sort=nameAscending (default)
?sort=-nameDescending
?sort=-createdAt,+nameDate desc, name asc

5. Implementing Default Sorting Order

ResourceSensible Default
Time-series data-createdAt (newest first)
User-facing listsName ASC
Search resultsRelevance score DESC
AlwaysInclude stable tie-breaker (id) for pagination consistency

6. Handling Invalid Sort Fields

ApproachTrade-off
400 Bad RequestStrict; client must fix
Ignore + warn headerLenient; less helpful
Whitelist fieldsRequired for SQL injection safety

7. Combining Sorting with Pagination

Warning: Without a stable sort, pagination may skip/duplicate rows. Always append unique tie-breaker.

Example: Stable Sort

ORDER BY created_at DESC, id DESC
LIMIT 20 OFFSET 40;

8. Implementing Nested Field Sorting

SyntaxExample
Dot notation?sort=address.city
JSON:API?sort=author.name
ImplementationSQL JOIN + ORDER BY joined column

9. Documenting Sortable Fields

DocumentationField
OpenAPI enumList sortable field names
Default orderState explicitly
Performance notesIndexed vs non-indexed columns

10. Optimizing Sort Performance

TechniqueBenefit
Composite index on (sortField, id)Index scan, no sort step
Covering indexIndex-only scan
Limit scan with WHEREReduce rows before sort
Cache top-N resultsHot pages of feeds