9

I am using the following pgsql query to select index_id and making a distinct query on the level column.

SELECT DISTINCT ON (level) index_id FROM indexes 

Although its working, it is returning the first index_id for each level, i would like to get the highest index_id in each distinct level

Paritosh
  • 10,474
  • 4
  • 54
  • 71
John Smith
  • 359
  • 3
  • 7
  • 15

2 Answers2

14

Use order by to get the max index_id

SELECT DISTINCT ON (level) index_id 
FROM indexes 
order by level, index_id desc
Clodoaldo Neto
  • 108,856
  • 25
  • 211
  • 247
  • When I do this, it doesn't necessarily give me the "last" row of the distinct set. My rows seem almost random - maybe something wrong with my index? – Adam Hughes Aug 31 '20 at 15:29
5

Try tou use GROUP BY instead of DISTINCT ON

SELECT MAX(index_id)  FROM indexes GROUP BY level
valex
  • 23,701
  • 6
  • 42
  • 60