Order By Date not working in GROQ query
I can help you troubleshoot your GROQ ordering issue! Without seeing your actual query, here are the most common reasons why order() might not work correctly with datetime fields:
Most Common Issues
1. Missing the pipe operator
The order() function must be separated from your query using the pipe operator (|). This is a very common mistake:
// ❌ Wrong - missing pipe
*[_type == "article"] order(date desc)
// ✅ Correct - with pipe
*[_type == "article"] | order(date desc)2. Placement after projections
If you're using a projection (the {} syntax), make sure order() comes after the closing brace, not inside it:
// ❌ Wrong - order inside projection
*[_type == "article"]{
title,
date
| order(date desc)
}
// ✅ Correct - order after projection
*[_type == "article"]{
title,
date
} | order(date desc)3. Null or missing date values
If some documents don't have a date value (even though you have validation), documents created before the validation was added might have null dates. These will sort unpredictably. You can filter them out:
*[_type == "article" && defined(date)] | order(date desc)4. Datetime stored as string
Make sure the datetime is actually stored as a datetime type, not a string. You can verify this in your Studio or by checking a raw document in Vision.
Working Example
Here's a complete, working query for your schema:
*[_type == "article"] | order(date desc) {
_id,
title,
date,
// other fields
}For descending order (newest first), use desc. For ascending (oldest first), use asc or just order(date) since ascending is the default.
The order() function documentation explains that it must be separated from other components using the pipe operator, and placement in the pipeline matters—it should typically come after projections when sorting by projected fields.
If you're still having issues after checking these common problems, share your actual GROQ query and I can help pinpoint the specific issue!
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.