skip to Main Content

In my table, I have a ‘start_date’ and ‘end_date’ column,

eg:

start_date end_date
2000/12/12 2010/10/12
1988/12/12 2003/04/03
1994/12/12 2008/09/21

What is the statement that I need to use to extract the years between the start & end date?
I want to create & view another column called AS ‘num_years_worked’ but I’m not sure what to input at the front.

Tried a few variations from Google but couldn’t get it to work.

2

Answers


  1. you can find it out using this query:

    SELECT TIMESTAMPDIFF(YEAR , start_date ,    end_date) from table
    
    Login or Signup to reply.
  2. You can just select the YEAR of both dates and build the difference of them:

    SELECT start_date, end_date,
    YEAR(end_date) - YEAR(start_date) AS difference
    FROM yourtable;
    

    You can also use TIMESTAMPDIFF for that:

    SELECT start_date, end_date,
    TIMESTAMPDIFF(YEAR,start_date,end_date) AS difference
    FROM yourtable;
    

    The difference is that this only "counts" entire years, so you might get different results compared to the first option.

    Try out which better meets your requirements.

    See here a working example according to your sample data: db<>fiddle

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search