Joint session with Vercel: How to build intelligent storefronts (May 15th)

Articles sorted by publishedAt DESC return jumbled results with wrong order

17 repliesLast updated: Nov 29, 2025

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

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

Was this answer helpful?

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.

Related contributions