skip to Main Content

We have mysql table with below columns. I am given startDate and endDate and now I have to fetch rows between those dates. Can some one please help with mysql query with how I can get those rows?

For example if startDate is November 2021 and endDate is March 2022. Then query should select rows with the months between these dates.

month year values
09 2021 30
10 2021 40
11 2021 90
12 2021 10
01 2022 25
02 2022 15
03 2022 89

2

Answers


  1. I think the first step would be to compute a column with a proper DATE value, starting from the column you have.
    For example, STR_TO_DATE(CONCAT(year,'-', month, '-', 1), '%Y-%m-%d') will return a proper SQL date on the 1st day of the year-month that you consider.

    This value can then be compared (with <= and >=) with the limit dates (as requested in the comments, the answer depends on how those are represented).

    Login or Signup to reply.
  2. You can compare tuples in MySQL:

    select month, year, `values`
    from tbl
    where (year, month) >= ('2021', '12')
      and (year, month) <= ('2022', '03');
    

    Another way is combining year and month to a single string:

    select month, year, `values`
    from tbl
    where concat(year, month) between ('202112') and ('202203');
    

    This only works if year and month (at least month) are zero-filled strings.

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