Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting error with trunc function for determining age

I am fairly new to using oracle SQL. I am trying to use the TRUNC function to calculate age

TRUNC((TO_DATE('2022-12-31')-cohort3.BIRTH_DATE)/365.25) AS AGE

but I am getting the following error –

ORA-00932: inconsistent datatypes: expected NUMBER got DATE
00932. 00000 -  "inconsistent datatypes: expected %s got %s"
*Cause:    
*Action:
Error at Line: 40 Column: 29

The birth_date column in the cohort3 table is of type VARCHAR and formatted as YYYY-MM-DD

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried changing VARCHAR to date but that still gave errors.

>Solution :

Don’t stored dates as strings; use a DATE data type.

Assuming that cohort3.BIRTH_DATE has a DATE data type then you want to use MONTHS_BETWEEN to calculate the age (as no year has exactly 365.25 days in it so you will introduce errors around birthdays if you use that value but all years have exactly 12 months):

FLOOR(MONTHS_BETWEEN(SYSDATE, cohort3.BIRTH_DATE)/12) AS age

If BIRTH_DATE is a string (and you are not changing it) then use TO_DATE to convert it to a DATE:

FLOOR(MONTHS_BETWEEN(SYSDATE, TO_DATE(cohort3.BIRTH_DATE, 'YYYY-MM-DD'))/12) AS age

If you want to get a person’s age on a specific day then replace SYSDATE with a DATE literal, such as DATE '2022-12-31'.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading