Skip to content
Advertisement

Changing an entire column from YYYY-MM-DD to number of months in MySQL

Suppose you have an entire column in MySQL that is YYYY-MM-DD, and you want to select it as the number of Months to a specific date, and also do it as a new column. Example date counting to can be March 2020.

So the following (table_1):

Emp_Name Hire_Date
Steve 2018-03-28

To

Emp_Name Months_Employed
Steve 24

But do this for every date in the Hire_Date column without manually entering the start and end date in DATEDIFF or TIMESTAMPDIFF.

I have the following, which returns a new column, but with NULL values:

select
Emp_Name, timestampdiff(month, 2021-04-01, Hire_Date) as Months_Employed
from
table_1

I have also tried DATEDIFF and dividing by 12 but it doesn’t work.

Any help is appreciated.

EDIT for Answer that worked:

SELECT 
emp_name, 
TIMESTAMPDIFF(month, hire_date, '2022-03-07')
AS months_employed
FROM table_1

Advertisement

Answer

TIMESTAMPDIFF(MONTH, startDate, endDate) is the correct function to use.

Date constants need to be shown as text strings. '2021-04-01' is April Fools Day 2021. But 2021-04-01, without the quotes, is an arithmetic expression evaluating to 2016.

Here’s a fiddle.

SELECT emp_name, 
       hire_date, 
       TIMESTAMPDIFF(MONTH, hire_date, '2022-03-07') 
  FROM table_1
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement