Answer the question
In order to leave comments, you need to log in
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
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 questionAsk a Question
731 491 924 answers to any question