12

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
  • 11,144
  • 5
  • 56
  • 74
John Smith
  • 449
  • 5
  • 8
  • 16

2 Answers2

16

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
  • 118,695
  • 26
  • 233
  • 260
  • 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
6

Try tou use GROUP BY instead of DISTINCT ON

SELECT MAX(index_id)  FROM indexes GROUP BY level
valex
  • 23,966
  • 7
  • 43
  • 60