Jimmy Jimmy - 1 month ago 15
SQL Question

Getting the number of months between two dates sql

I have a table with columns

id, last_name, date_hired

I need to find out the number of months since date_hired and today. I can't figure out how to use the date_hired in
Months_Between
function. Here's what I have so far:

SELECT LAST_NAME AS Name,
MONTHS_BETWEEN(
TO_DATE(DATE_HIRED,'MM-DD-YYYY'),
TO_DATE('01-01-1995','MM-DD-YYYY')) "Months"
FROM EMPLOYEES;


I have searched for this question but none of the other questions use data from another column.

Answer

If DATE_HIRED is DATE datatype, use

SELECT LAST_NAME AS Name, 
   MONTHS_BETWEEN(DATE_HIRED, SYSDATE) "Months"
  FROM EMPLOYEES;

If it is CHAR datatype (or derived), use

SELECT LAST_NAME AS Name, 
   MONTHS_BETWEEN(TO_DATE(DATE_HIRED,'MM-DD-YYYY'), SYSDATE) "Months"
  FROM EMPLOYEES;

Format 'MM-DD-YYYY' depends on your client NLS settings.