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;

Thursday, February 17, 2011

Issue in INTERVAL function

I kept getting an annoying error, while I was trying to use interval function on timestamp field. This ended up to be an bug in teradata's feature. Totally surprised they have not handled this issue. Hopefully they will fix it after my DBA raises a ticket.
Here is the issue:
INTERVAL function does not adjust dates(for leap year or for february) as ADD_MONTHS does. For example, when you execute the following:
SELECT ADD_MONTHS('2011-01-31',1)
You will get an output as 2011-02-28
But, when you use interval function instead:
SELECT CAST('2011-01-31' AS DATE)+ INTERVAL '1' MONTH
You will get an error (2665: Invalid date).

Weird! isn't it? hopefully they fix it sooner and my post will be obsolete.