Basic Syntax
The sort parameter uses the following format:- field: The name of the field to sort by
- order: Either
ASC(ascending) orDESC(descending)
The field and order are separated by a comma (
,), not the standard delimiter (||).Example
Sort Orders
There are two sort orders available:Ascending Sort
Ascending sort orders results from lowest to highest:Descending Sort
Descending sort orders results from highest to lowest:Multiple Sort Fields
You can sort by multiple fields by adding multiplesort parameters:
- First sort parameter is the primary sort
- Second sort parameter is applied when primary values are equal
- And so on…
Example with Multiple Sorts
- First by role (alphabetically)
- Within each role, by last name (alphabetically)
- Within each last name, by first name (alphabetically)
Sorting Different Data Types
Strings
Numbers
Dates
Booleans
false < true in ascending order.
Sorting with Other Parameters
Combine sorting with filtering, pagination, and field selection:Sort with Filter
Sort with Pagination
Sort with Field Selection
Complete Example
- Filters electronics products that are in stock
- Sorts by price (lowest first)
- Returns only id, name, and price fields
- Limits results to 20 items
Sorting Nested Fields
You can sort by fields in related entities using dot notation:When sorting by nested fields, make sure to include the appropriate
join parameter to load the relation.Common Sorting Patterns
Latest First
Most Popular
Alphabetical Lists
Priority/Status Based
Error Handling
Invalid sort parameters will throw aRequestQueryException:
Performance Considerations
Database Indexes
For optimal performance, create database indexes on frequently sorted fields:Composite Indexes
For multi-field sorts, consider composite indexes:Avoid Sorting Large Datasets
Practical Examples
User Management Dashboard
E-commerce Product Listing
Blog/Content Management
Task Management
Best Practices
- Always specify sort order: Include both field and order (ASC/DESC)
- Use consistent sorting: Maintain the same sort order across paginated requests
- Index sorted fields: Add database indexes to commonly sorted fields
- Combine with pagination: Always limit results when sorting
- Default to DESC for timestamps: Use
sort=createdAt,DESCto show newest items first - Consider multiple sorts: Use multiple sort parameters for ties (e.g., same priority)
- Document default sorting: Let API consumers know the default sort behavior
Next Steps
Pagination
Learn how to paginate sorted results
Filtering
Combine sorting with filters
Relations
Sort by fields in related entities
Query Parameters
Overview of all query parameters