'Subtracting different data types in oracle

I have a date string that I need subtract a field from and then divide.

(‘31-DEC-2021’ - b.RECIP_DOB)/365.25 as age

Getting the following error:

Inconsistent data types, expected char got date



Solution 1:[1]

'31-DEC-2021' may look like a date but it is a string literal.

Do not use a string, use a date literal:

(DATE '2021-12-31' - b.RECIP_DOB)/365.25 AS age

If you do want to use a string then explicitly convert it from a string to a date using TO_DATE:

(TO_DATE('31-DEC-2021', 'DD-MON-YYYY', 'NLS_DATE_LANGUAGE=English')
   - b.RECIP_DOB)/365.25 AS age

However, you should use MONTHS_BETWEEN rather than assuming an average of 365.25 days-per-year:

MONTHS_BETWEEN(DATE '2021-12-31', b.RECIP_DOB)/12 AS age

db<>fiddle here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MT0