logoalt Hacker News

Postgres SELECT DISTINCT Does Not Scale

67 points • by KraftyOne • last Thursday at 6:43 PM • 21 comments • view on HN

Comments

procaryote • today at 7:11 AM

I've generally started to treat use of SELECT DISTINCT as a warning flag, as it's very common that it indicates bad code

Some use it because they don't understand uniqueness constraints and try to fix it in post so to say. Some use it because they forgot a join condition and are absolute amateurs. Some use it because it fixed a problem for them once and now they add it everywhere

These people seem to outnumber the people who use SELECT DISTINCT in a well thought out manner

➕ show 1 reply
nattaylor • today at 3:10 AM

Loose index scan is made for this https://dev.mysql.com/doc/refman/8.0/en/group-by-optimizatio...

Postgres doesn't have it yet https://wiki.postgresql.org/wiki/Loose_indexscan

➕ show 2 replies
sandeepkd • today at 6:14 AM

It says that the company is co-founded by Postgres creator. I find that bit hard to believe given that there is nothing novel in the article, probably discovery for them. I do understand that everyone has to go through their own journey to learn these things but at the same time when you are running business then seeking professional help isnt a bad idea.

Based on my experience queries like these cannot scale, whatever you do. However if you are already on a path where you had invested a lot in such queries then hire a DBA, if you are not far off then hire an architect to model the data for better performance.

➕ show 2 replies
thesuperevil • today at 5:55 AM

[flagged]

colenikol2 • today at 7:31 AM

[dead]

DiabloD3 • today at 2:42 AM

"Postgres SELECT DISTINCT Does Not Scale"

Correct. This is documented in depth: DISTINCT sorts the results first.

The article's use case seems to imply the author did not know about GROUP BY, nor does it imply the author knew about indexes, nor ANALYZE. Postgres 18's new skip scan indexing also could help here, so ensuring the planner chooses that could help.

➕ show 2 replies