
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeThis is a common issue when sorting by dates in GROQ - it typically happens when some documents have null or missing publishedAt values. Here's what's likely happening and how to fix it:
When you use order(publishedAt desc), documents with null or undefined publishedAt values can appear at unpredictable positions in your results, causing the "jumbled" ordering you're seeing where 2021 articles appear, then 2019, then 2021 again.
Filter out null values before sorting:
*[_type == "article" && defined(publishedAt)] | order(publishedAt desc)The defined() function checks that the field exists and has a value, ensuring you only sort documents that actually have a publishedAt date.
1. Use coalesce() to provide a fallback date:
*[_type == "article"] | order(coalesce(publishedAt, _createdAt) desc)This will use _createdAt as a fallback when publishedAt is missing, so all articles can still be included in your results.
2. Separate published and unpublished articles:
{
"published": *[_type == "article" && defined(publishedAt)] | order(publishedAt desc),
"drafts": *[_type == "article" && !defined(publishedAt)] | order(_createdAt desc)
}This gives you explicit control over how each group is handled.
publishedAt valuespublishedAt a required field in your schema to prevent this issue going forward_id, which can also seem random if you're expecting chronological orderThe most common fix is simply adding && defined(publishedAt) to your filter - this should give you clean, properly ordered results!
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.
Content operations
Content backend


The only platform powering content operations
By Industry


Tecovas strengthens their customer connections
Build and Share

Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag store