0

I need to select all data from a table 'followup' between followup_date and first of next month (including 1rst of next month). The format of my date in DB (obtained from an API) is d-m-Y.

The follow-up date for example is: 18-07-2020.

I have the following query:

SELECT * from followup 
WHERE DATEDIFF(STR_TO_DATE(`followup_date`,'%d-%m-%Y'), DATE_FORMAT(CURDATE() + INTERVAL 1 MONTH,'%Y-%m-01'))- 1 < 0 ;

I am getting -15 days as difference and getting records correctly, including 1rst. Is the query correct and efficient and will it work correctly for all months.

Requesting suggestions from experts for improvements, if any.

Pamela
  • 684
  • 1
  • 7
  • 21

1 Answers1

1

You should convert your followup_date column to a DATE type. You can then make your query sargable by removing the function calls on followup_date and simply comparing it with the target date:

SELECT * from followup 
WHERE `followup_date` <= DATE_FORMAT(CURDATE() + INTERVAL 1 MONTH,'%Y-%m-01')

I suspect adding one day to LAST_DAY(CURDATE()) might be more efficient:

SELECT * from followup 
WHERE `followup_date` <= LAST_DAY(CURDATE()) + INTERVAL 1 DAY

Demo on SQLFiddle

Nick
  • 138,499
  • 22
  • 57
  • 95