Sort content
How to sort GraphQL query results using best practices, multiple criteria, and performance-optimized patterns.
Sorting content in GraphQL is a powerful way to control how data is presented and retrieved by GraphQL, especially when working with large or dynamic datasets. Use the orderBy directive to specify the exact order in which results should display—whether by publication date, alphabetical order, or custom fields. Combining multiple sort criteria and leveraging variables enables flexible, scalable, and performance-optimized content delivery.
Sort by a single field
To sort results, apply the orderBy field in your GraphQL query. The following query shows articles with the most recent publication dates first:
query {
ArticlePage(
orderBy: { StartPublish: DESC }
) {
items {
Name
StartPublish
}
}
}Sort by multiple fields
Use multiple criteria to break ties and refine your results. The following query sorts articles first by publication date and then alphabetically by name:
query {
ArticlePage(
orderBy: [
{ StartPublish: DESC },
{ Name: ASC }
]
) {
items {
Name
StartPublish
}
}
}Common sort patterns
Sort by publication date (newest first) – Retrieve the latest articles with additional details like teaser text and path.
query GetLatestArticles {
ArticlePage(
orderBy: { StartPublish: DESC }
limit: 10
) {
items {
Name
TeaserText
StartPublish
RelativePath
}
}
}Sort alphabetically – Arrange articles by name in alphabetical order.
query GetAlphabeticalArticles {
ArticlePage(
orderBy: { Name: ASC }
limit: 20
) {
items {
Name
TeaserText
RelativePath
}
}
}Combined sorting with filtering – Filter articles by category and sort by date and name.
query GetFilteredAndSorted($category: String!) {
ArticlePage(
where: {
TeaserText: { contains: $category }
}
orderBy: [
{ StartPublish: DESC },
{ Name: ASC }
]
limit: 15
) {
items {
Name
TeaserText
StartPublish
RelativePath
}
}
}Best practices for sorting
- Include
orderBy– Ensure consistent results when paginating. - Use multiple criteria – Handle ties, such as articles with the same date.
- Combine with filtering – Organize content into specific categories.
- Consider performance – Sort using indexed fields for efficiency.
Use variables for dynamic sorting
Adjust sorting parameters dynamically using variables. This lets you change sorting fields and directions without altering the query structure.
query GetSortedContent($sortField: String!, $sortDirection: String!) {
ArticlePage(
orderBy: { $sortField: $sortDirection }
limit: 10
) {
items {
Name
StartPublish
RelativePath
}
}
}The following are some example variables:
{
"sortField": "StartPublish",
"sortDirection": "DESC"
}Next steps
After sorting your content, you can utilize the Search functionality to discover specific text-based content. Alternatively, if you are handling large content collections, consider implementing Pagination to ensure efficient navigation and seamless browsing for users.
Updated 16 days ago
