Sorting arguments help you get data in the order you want, like sorting names from A to Z or numbers from smallest to largest.
0
0
Sorting arguments in GraphQL
Introduction
When you want to see a list of products sorted by price from low to high.
When you need to display users ordered by their signup date, newest first.
When showing blog posts sorted by popularity or number of comments.
When you want to list movies sorted alphabetically by title.
When you want to get events sorted by their start date.
Syntax
GraphQL
query {
items(orderBy: {field: ASC}) {
id
name
}
}orderBy is the argument used to sort data.
You specify the field to sort by and the direction: ASC for ascending or DESC for descending.
Examples
This sorts users by their name in ascending order (A to Z).
GraphQL
query {
users(orderBy: {name: ASC}) {
id
name
}
}This sorts products by price in descending order (highest to lowest).
GraphQL
query {
products(orderBy: {price: DESC}) {
id
price
}
}This sorts posts by creation date, newest first.
GraphQL
query {
posts(orderBy: {createdAt: DESC}) {
id
title
}
}Sample Program
This query gets a list of books sorted alphabetically by their title.
GraphQL
query {
books(orderBy: {title: ASC}) {
id
title
}
}OutputSuccess
Important Notes
Sorting works only on fields that support ordering, like strings, numbers, or dates.
If you don't specify sorting, the order of results may be random or default.
You can often combine sorting with filtering to get exactly the data you want.
Summary
Sorting arguments let you control the order of data returned by a query.
Use orderBy with a field and direction (ASC or DESC).
Sorting makes data easier to read and find what you need quickly.