Skip to content
Advertisement

SQL comparing date

I want to compare the current date with a date from a database table.

This code:

DATE_FORMAT(dt,'%y-%m')

gives me a date like this 2020-10

and i want that this code:

DATE_ADD(CURRENT_DATE, INTERVAL - 1 month)

gets date like 2020-10 not 2020-10-12(some day)

Here is the whole sql query:

select count(*)
  from app_tickets t 
 where t.status= 3 
   and DATE_FORMAT(dt,'%y-%m')=DATE_ADD(CURRENT_DATE, INTERVAL - 1 month)

Thanks for help:)

Advertisement

Answer

This can make use of indexes

select count(*) 
from app_tickets t 
where t.status = 3 
  and t.dt >= DATE_FORMAT(CURRENT_DATE - interval 1 month ,'%Y-%m-01') 
  and t.dt  < DATE_FORMAT(CURRENT_DATE ,'%Y-%m-01')
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement