BLOG // May 2, 2021

Limiting and sorting GraphQL queries in Gatsby

My blog is powered by Gatsby and Strapi, and all the content is loaded using GraphQL from the Strapi API. The example below is from Gatsby, but can be used in any GraphQL query.

Limiting and Sorting

On the front page I sort by the created_at field (my "date") and limit the output to four, i.e. the four most recent blogs. This can be achieved simply by adding the following to your GraphQL query:

export const pageQuery = graphql`
  query IndexQuery {
      limit: 4
      sort: { fields: [created_at], order: DESC }
    ) {
      edges {
        node {
          created_at(formatString: "LL")

As you can see I'm specifically talking about the limit and sort options, and how they work. This is an easy way to limit the number of items with GraphQL, and to sort them.

Side Tip: Dates

Did you notice the side tip? Dates can be formatted directly in GraphQL, and "LL" gives you those nice "May 1, 2021" dates. You can apply this type of query to any date field:

created_at(formatString: "LL")

If you're interested in load testing GraphQL this is a great guide.


Subscribe to new articles

If you enjoy my content, consider subscribing. You will only receive new blog stories, no other email.



© 2022 Dave Blakey. All rights reserved.

Development, startup and tech tips from Gatsby to Laravel, Strapi to PHP.