D
D
DUDE2020-06-13 19:09:53
PostgreSQL
DUDE, 2020-06-13 19:09:53

How does DISTINCT ON work?

Hello everyone, I understand how DISTINCT works, but to be honest, I can’t fully figure out what DISTINCT ON does, although there seem to be a lot of examples on the Internet and explanations on English-language forums, and finally in the documentation. What does and when exactly should you use DISTINCT ON?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Melkij, 2020-06-13
@melkij

How will one more explanation help you if you have already, as you say, read many others?
distinct answers the question "show unique combinations of such fields"
distinct on extends the standard behavior and answers the question "show the data of the first row from each unique combination of such fields". And to determine the "first line" - makes it mandatory to use order by.
It is used when you need to find, for example, data on the first order of each of the customers in the store.
Note: postgresql at the time of version 13 does not know how to loose index scan , therefore distinct in the forehead can be elegant in writing, depending on the data distribution, but not very efficient and the planner will have to explain a more appropriate algorithm manually.

D
Dr. Bacon, 2020-06-13
@bacon

google Russian docs for you, https://postgrespro.ru/docs/postgrespro/12/sql-sel...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question