Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

postgres order by not working properly with DISTINCT ON

I have a postgres table with the structure(id: int, idarray: int[], title: text, ident: text). I want to search the table with something like title LIKE …(i didnt include that because its not relevant for the issue) and then sort out the duplicates. these are defined by the idarray.

 id | idarray | title | ident 
----+---------+-------+-------
  2 | {2}     | test  | x
  3 | {3}     | test  | y
  4 | {4}     | test  | z
  1 | {5,1}   | test  | a
SELECT DISTINCT ON (idarray)
  *
FROM info
ORDER BY
  idarray,
  CASE
    WHEN ident = 'a' THEN 1
    WHEN ident = 'y' THEN 2
    ELSE 3
  END,
  CASE
    WHEN ident IN ('a', 'y') THEN id
    ELSE -id
  END DESC;

The problem is that it should order the endresult by id. 1 Should be on the top and not at the bottom.

The expected behavour is that it should order by the first given argument(in this case id). It should prioritize in each group with this order a, y, biggest id.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I got the same issue And Fixed it with this link.

Please check the same at

PostgreSQL DISTINCT ON with different ORDER BY

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading