Home > Blogroll, sql > How old are you?

How old are you?

I just come back from holiday, I am quite busy at the moment. Here is a tiny function to get the age

trunc((to_char(sysdate,’YYYYMMDD’)-to_char(birthdate,’YYYYMMDD’))/10000)

it is much safer than add_months, because add_months do some conversion at the end of the month, and I would never accept to wait until Feb 29th, 2008 (28-2-1990 + 18*12 months) to be 18 if I were born Feb 28th, 1990.

Tags:
  1. Anonymous
    September 8th, 2006 at 04:00 | #1

    oh greate!!

    def birthdate = to_date(’2000/02/29′,’yyyy/mm/dd’)
    def sys_date = to_date(’2003/02/28′,’yyyy/mm/dd’)

    select
    trunc((to_char(&sys_date,’YYYYMMDD’)-to_char(&birthdate,’YYYYMMDD’))/10000) as age from dual;

    def sys_date = to_date(’2003/03/01′,’yyyy/mm/dd’)

    select
    trunc((to_char(&sys_date,’YYYYMMDD’)-to_char(&birthdate,’YYYYMMDD’))/10000) as age from dual;

  2. Scott
    February 28th, 2009 at 15:53 | #2

    Inaccuate:

    SELECT TRUNC((’20090731′-’20040731′)/10000) from dual returns 5, right
    SELECT TRUNC((’20090731′-’20040730′)/10000) from dual returns 5, wrong

  3. Laurent
    February 28th, 2009 at 17:44 | #3

    why wrong?
    what do you consider to be right?

  4. November 30th, 2010 at 15:45 | #4

    select trunc((trunc(sysdate) – to_date(’01.01.2000′,’DD.MM.YYYY’))/365) from dual

  5. November 30th, 2010 at 16:43 | #5

    If you born on 1 January 2000, then this function will be accurate until 2008-12-30 !

  1. February 28th, 2008 at 11:53 | #1
*