Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle date difference to get number of years

Tags:

select

oracle

Is there a way to calculate the number of years between dates. Not sure how to do this while accounting for leap and what not. Is it possible to do an IF statement maybe in the SELECT?

Thanks

like image 391
Matt Avatar asked Oct 30 '11 03:10

Matt


People also ask

How do I calculate years between two dates in SQL?

In MS SQL Server, the DATEDIFF function is used to get the difference between two dates in terms of years, months, days, hours, minutes etc. SELECT DATEDIFF(day, '2018-03-13', GETDATE()) AS "Difference in days"

How can I find the difference between two dates in Oracle?

Answer: Oracle supports date arithmetic and you can make expressions like "date1 - date2" using date subtraction to get the difference between the two dates.

Is there a year function in Oracle?

The YEAR function returns the year part of a value. The argument must be a date, timestamp, or a valid character string representation of a date or timestamp. The result of the function is an integer between 1 and 9 999.

Does Oracle have a datediff function?

Use the @DATEDIFF function to calculate the difference between two dates or datetimes, in days or seconds. The difference between the specified dates. Valid values can be: DD , which computes the difference in days.


1 Answers

I'd use months_between, possibly combined with floor:

select floor(months_between(date '2012-10-10', date '2011-10-10') /12) from dual;  select floor(months_between(date '2012-10-9' , date '2011-10-10') /12) from dual; 

floor makes sure you get down-rounded years. If you want the fractional parts, you obviously want to not use floor.

like image 171
René Nyffenegger Avatar answered Sep 22 '22 04:09

René Nyffenegger