Order Results
Many use cases for queries will need to order the returned data. As a SQL user,
you’re familiar with the ORDER BY
clause. With GraphQL you can order by
attaching an order
object to a type block, as shown below:
SQL syntax:
SELECT posts.id
FROM posts
ORDER BY ...
Similar GraphQL syntax:
query ORDERED_POSTS {
queryPost(order: { ... }) {
id
}
}
You are probably accustomed to query results in ascending order as a SQL user, because that is what you get unless you specify that you want results in descending order. When ordering query results in GraphQL with Dgraph, you specify ascending or descending order, or else the default order of results is determined by ID. In the examples below, query results are ordered by date:
SQL syntax:
SELECT posts.id
FROM posts
ORDER BY
posts.date ASC
Similar GraphQL syntax:
query ORDERED_POSTS {
queryPost(order: { asc: date }) {
id
}
}
Nested ordering of query results
As in SQL, GraphQL lets you specify nested, or sequential, ordering of query
results. GraphQL does this using the by nesting ordering objects inside of the
then
parameter.
So, you can express queries like “Fetch posts in descending order by
date, with posts that share a date in ascending order by title” in GraphQL using
the then
parameter:
SQL syntax:
SELECT posts.id
FROM posts
ORDER BY
posts.date DESC,
posts.title ASC
Similar GraphQL syntax:
query ORDERED_POSTS {
queryPost(order: {
desc: date
then: { asc: title }
}) {
id
}
}
Knowing the overall syntax structure and a few keywords will put you well on your way to becoming a GraphQL expert. Having a typed system means GraphQL IDE tools and plugins can generate many of the queries and mutations that your app will need.
Note: To learn more about Dgraph’s support for ordering query results, see Order and Pagination in the Dgraph documentation.