M
M
McMike2017-02-13 12:03:34
PostgreSQL
McMike, 2017-02-13 12:03:34

Why doesn't Distinct work without OrderBy?

The query breaks if I try to remove duplicates for a field using DISTINCT ON, without adding this field to ORDER BY.
Why? How does distinct work in PG? What if you need to remove duplicate records, but sort by a different field?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Fedorov, 2017-02-13
@qonand

https://postgrespro.ru/docs/postgrespro/9.5/sql-se...

A
Artem Klimenko, 2017-02-14
@aklim007

There is a field A by which you make distinct, there is a field B by which you want to sort after eliminating duplicates.
Then there are two options:
- If DISTINCT ON (A) = DISTINCT ON (A, B), in fact, there are no problems doing a distinct on two fields, both of these fields can be specified in the sorting.
- If DISTINCT ON (A) <> DISTINCT ON (A, B), then something strange happens, what result do you expect from sorting if there are no guarantees which of the values ​​of field B will be in the final selection?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question