Thursday, October 27, 2011

highest 10 ids

My colleague asked me today, how can I get the 10 highest ids in a table?
Sounds simple, right, but for many usage of ordered analytic function here is new... we always think about MAX, TOP etc... so here is a quick reference:

SELECT ID FROM TABLE

QUALIFY RANK() OVER (ORDER BY ID DESC) <=10;





Update:
My assumption here is that ID field I use here is unique. If it is not unique, rank() cannot be used, row_number() needs to be used instead.
(thanks for pointing this out, carlosal!!)

Also, TOP can be used along with ORDER BY clause and achieve the result, but in my opinion & experience, ordered analytic function is much faster for this task than TOP


SELECT TOP 10 ID FROM TABLE
ORDER BY ID DESC;