Featured image of post MYSQL records of previous month

MYSQL records of previous month

The Question: how to get MYSQL rows of last month ?

The “simple” question “how do i get MySQL records of previous month” unfolded many threads , sometimes even giving false positive answers like:

take the difference between now and now-1 month (DO NOT !)

The Solution: Two MYSQL timestamps with INTERVAL calculated

Ok, not only sometimes false postives are recommended , in fact very often.. , so here we go with a proper example:

SELECT o.row_a , o.row_b,
WHERE row.something = `foo`
AND (o.`date_add` >= DATE_FORMAT( CURRENT_DATE - INTERVAL 2 MONTH, '%Y/%m/01' ) )
AND (o.`date_add`  < DATE_FORMAT( CURRENT_DATE - INTERVAL 1 MONTH, '%Y/%m/01' ) )

( only the part from AND on is important to us )

To get other months ( or days or years), just modify the INTERVAL 1 MONTH and the second AND statement

ADDENDUM: current month

to have “nearly the same” query for the current month, do

AND (o.`date_add` >= DATE_FORMAT( CURRENT_DATE, '%Y/%m/01' ) )
AND (o.`date_add`  < DATE_FORMAT( CURRENT_DATE + INTERVAL 1 MONTH, '%Y/%m/01' ) )

 /etc/docker/daemon.json contents of custom setup

      ...