Articles sorted by publishedAt DESC return jumbled results with wrong order

17 replies
Last updated: Jan 28, 2026
When fetching articles sorted by
publishedAt
date ordered DESC, results are somewhat jumbled with some of the articles that should be at the end of the list are being inserted at the beginning. The results in the screenshot start with the latest articles: 2021, then 2019 then 2021 again.
AI Update

This 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:

The Problem

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.

The Solution

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.

Alternative Approaches

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.

Additional Tips

  • Always check your documents in the Vision plugin or Studio to verify which ones have missing publishedAt values
  • Consider making publishedAt a required field in your schema to prevent this issue going forward
  • Remember that GROQ's default ordering (when no explicit order is specified) is ascending by _id, which can also seem random if you're expecting chronological order

The most common fix is simply adding && defined(publishedAt) to your filter - this should give you clean, properly ordered results!

Show original thread
17 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?