Oracle SQL: Finding Difference Between two dates in YEARS

My friend asked me how to create following SQL query:

For each employee hired before 1992, display the employee’s last name, hire date and calculate the number of YEARS between TODAY and the date the employee was hired. Label the column Years worked.
Order your results by the number of years employed.
Round the number of years up to the closest whole number.

I was trying to find the solution in the Net, but unfortunately found nothing that would help, that is why I decided to make this query by my one. It appeared to be very simple.

Here is the query:

So first line selects employee last_name and hire_date, and also I created new column called Years Worked by getting the Date in number format (TO_CHAR) subtracting hire_date from the system date and dividing by 365 to find the value in year. If the year has 366 days it does not really matter because we are using ROUND function and it cuts all decimals. In line 3 WHERE clause checks if hire_Date is smaller than 1992.Last line orders everything by Years Worked column starting from the biggest amount of years worked.

That’s it, Have fun!

About the author

Anatoly Spektor

IT Consultant with 6 years experience in Software Development and IT Leadership. Participated in such projects as Eclipse IDE, Big Blue Button, Toronto 2015 Panam Games.

View all posts

6 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *