Can GROQ query random documents by type?

13 replies
Last updated: Nov 29, 2025
Am I right in thinking that it isn’t currently possible to query a random document, or X random documents, of a given type using GROQ?
AI Update

You're correct! GROQ doesn't currently have a built-in random() function or order(random()) capability to query random documents. This is a known limitation of the query language.

However, there are several workarounds you can use to achieve random or pseudo-random document selection:

Client-Side Randomization

The most straightforward approach is to fetch more documents than you need and randomize them on the client side:

*[_type == "post"][0...20]

Then in your application code, shuffle the results and take the number you need.

Using Modulo with Document ID

You can create a pseudo-random selection by using the document's _id with modulo operations. This gives you different "buckets" of documents:

*[_type == "post" && string::split(_id, "")[0] in ["a", "b", "c"]]

This selects documents whose ID starts with certain characters. You can vary which characters you use to get different sets.

Time-Based Rotation

Another approach is to rotate which documents you fetch based on the current time:

*[_type == "post"] | order(_createdAt desc)[($seed % count(*))...($seed % count(*) + 5)]

Where $seed is a parameter you pass based on the current day/hour/minute to rotate through different documents.

Using Score Functions

If you're doing any kind of search or filtering, you can combine the score() function with the boost() function in creative ways to vary results, though this isn't truly random.

The lack of a native random() function is a deliberate design choice in GROQ, as true randomization can be challenging to implement efficiently in a distributed query system and can make caching less effective. For most use cases, the client-side randomization approach works well and keeps your queries cacheable and performant.

Show original thread
13 replies

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?