Sorting GROQ results using query params instead of template strings

6 replies
Last updated: Dec 15, 2021
Another question: is there a way to sort results based on query params? Currently I’m doing this:
| order(date ${query.sort})
…where
${query.sort}
is a JavaScript expression inside a template string, but I’m curious if this can be done using params.
AI Update

Unfortunately, you cannot pass the order direction (asc or desc) as a parameter in GROQ. The direction keywords are part of the GROQ syntax itself and must be written directly in the query string. So your current approach using template strings is actually the correct way to handle dynamic sorting:

| order(date ${query.sort})

This limitation is mentioned in the Sanity documentation on the order() function, which notes that while you can pass document types and reference tags as parameters to GROQ queries, passing the order expression itself as a parameter (like $orderBy containing "publishedAt desc") doesn't work as expected.

Why This Happens

GROQ params are designed for values that get substituted into the query, not for syntax elements like asc/desc keywords or field names in the order clause. The parser expects these to be literal parts of the query structure.

Best Practices for Your Approach

When using template strings for dynamic sorting, make sure to:

  1. Validate the input to prevent injection issues:
const allowedSortDirections = ['asc', 'desc'];
const sortDirection = allowedSortDirections.includes(query.sort) ? query.sort : 'asc';

const groqQuery = `*[_type == "post"] | order(date ${sortDirection})`;
  1. Consider allowing field name variation too:
const allowedFields = ['date', 'title', 'publishedAt'];
const allowedDirections = ['asc', 'desc'];

const field = allowedFields.includes(query.field) ? query.field : 'date';
const direction = allowedDirections.includes(query.sort) ? query.sort : 'asc';

const groqQuery = `*[_type == "post"] | order(${field} ${direction})`;

This template string approach is the standard pattern for dynamic ordering in GROQ, so you're doing it the right way!

Show original thread
6 replies
Yes. You can do this:
* | order(select(
  $sort == "title" => title,
  $sort == "date" => date,
  _id))
This is like a
switch
statement in JS.
Thank you!
The downside is that this code path is not optimized at the moment. All the documents will be loaded into memory and sorted first, which can be inefficient if you have a lot of documents. How inefficient depends on the size of the documents and so on, so I can’t give you an exact number. But I would recommend not doing it unless you know that the number of documents (after filtering) is less than 1,000 or 1MB.
So I should stick with the template literal method for performance, in other words?
If possible. Note that the above trick also breaks our ability to optimize slicing. So if you have this:
*[some filter that returns 1 million documents]
  | order(select(...)) [0..100]
…then the slow/inefficient ordering will happen on those 1 million documents, even though you’re only extracting 100. With a normal
order()
, we can slice while sorting, which is much faster.
Thanks for the information!

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?