---
title: "The DISTINCT in your COUNT"
url: https://daily.dev/posts/the-distinct-in-your-count-ieqwekrgt
source_url: https://postgr.es/p/9rw
type: article
source: "Planet PostgreSQL"
published: 2026-08-05T21:01:15.384Z
updated: 2026-08-06T01:43:49.474Z
tags: ["sql", "postgresql"]
reading_time: 9
upvotes: 0
comments: 0
language: en
---

> ## Documentation Index
> Fetch the complete documentation index at: https://daily.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# The DISTINCT in your COUNT

**[Planet PostgreSQL](https://daily.dev/sources/planet-postgresql)** · 9 min read · 0 upvotes · 0 comments

## Summary

COUNT(DISTINCT col) in PostgreSQL silently disables parallel query execution because the aggregate has no combine function — workers can't merge partial distinct counts without shipping all values to one place. This forces a single-core serial sort that often spills to disk. The fix is to push deduplication into a GROUP BY subquery, which PostgreSQL can parallelize via partial hash aggregates. On a 10M-row table this rewrite yields ~3.4x speedup (1211ms vs 360ms) and eliminates disk spill. The same parallelism block affects any aggregate with an inner ORDER BY (string_agg, array_agg, percentile_cont). The per-group variant (GROUP BY country, COUNT(DISTINCT user_id)) has an analogous rewrite using stacked GROUP BYs, though the planner may not always choose the parallel path.

## Full article

daily.dev links to this article rather than hosting it. Read it at the original source: <https://postgr.es/p/9rw>

## Similar posts on daily.dev

- [All Your GUCs in a Row: enable\_distinct\_reordering and enable\_group\_by\_reordering](https://daily.dev/posts/all-your-gucs-in-a-row-enable-distinct-reordering-and-enable-group-by-reordering-xhdvyn0ky) · Planet PostgreSQL · 0 upvotes · 0 comments

---

Tags: [#sql](https://daily.dev/tags/sql), [#postgresql](https://daily.dev/tags/postgresql)

[View this post on daily.dev](https://daily.dev/posts/the-distinct-in-your-count-ieqwekrgt)
