Is it Possible to Perform a Slice based on a Value Received in the Same Query?
Great question! Yes, you can absolutely perform a dynamic slice in GROQ using parameters. The key is understanding how GROQ parameters work with the slice operator.
Dynamic Slicing with Parameters
GROQ supports using parameters (prefixed with $) directly in slice operations. Here's the basic syntax:
*[_type == "movie"] | order(_createdAt desc) [$start..$end]You can pass these parameters when executing the query through your client:
await client.fetch(query, { start: 0, end: 10 })Using a Single Limit Parameter
If you're receiving a single number (like a limit) and want to slice from the beginning, you can do:
*[_type == "post"][0...$limit]Or for non-inclusive slicing (which excludes the end index):
*[_type == "post"][0...$limit] // includes item at $limit
*[_type == "post"][0...$limit] // excludes item at $limit (note the three dots)Important Notes About Slice Syntax
From the GROQ documentation, there are two slice operators:
[0..5]- inclusive (returns indices 0, 1, 2, 3, 4, 5 - that's 6 items)[0...5]- non-inclusive (returns indices 0, 1, 2, 3, 4 - that's 5 items)
Your Concern About Query Execution Order
You mentioned wondering if the "inner query is performed first" - and you're right to think about execution order! However, parameters are resolved before the query executes, not during. So when you use $limit in a slice operation, that value is already available when the slice happens.
If you're trying to use a value from within the same query result to control slicing (like getting a number from a document and using it to slice), that's not directly possible in a single GROQ query since slicing happens at the pipeline level, not within projections.
Example with Offset and Limit
A common pagination pattern:
*[_type == "post"]
| order(publishedAt desc)
[$offset...$offset + $limit]Then fetch with:
await client.fetch(query, { offset: 20, limit: 10 })Without seeing your specific query, this should help you implement dynamic slicing! If you're trying to do something more complex (like using a value from a document to control slicing in the same query), feel free to share your code and I can provide more specific guidance.
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.