I keep seeing answers like this: https://stackoverflow.com/a/21277074/4236404 being the default accepted answer for how to get the Month to date rows in a MySQL query.
The current answer(s):
SELECT id, created
FROM table1
WHERE MONTH(created) = MONTH(CURDATE())
AND YEAR(created) = YEAR(CURDATE())
This query will work, but it's inefficient and MySQL will perform a full scan to get the results.
Therefore the correct way to get the rows for a Month to Date (MTD) query is as follows (I will use PDO and PHP to demonstrate:
//get the first day of the month
$month_first_day = date( "Y-m-01" );
//select the record where the created date is equal to or bigger than the first day of the current month.
$stmt = $pdo->prepare('SELECT id, created FROM table1 WHERE created >= :first_day_of_month');
$stmt->bindParam(':first_day_of_month', $month_first_day);
$stmt->execute();
$realm_data = $stmt->fetch();
Bonus queries:
To get all records for today do the following:
$today = date( "Y-m-d" );
$stmt = $pdo->prepare('SELECT id, created FROM table1 WHERE created >= :today');
$stmt->bindParam(':today', $today);
$stmt->execute();
$realm_data = $stmt->fetch();
To get all the records for yesterday do the following:
$today = date( "Y-m-d" );
$yesterday = date( "Y-m-d", time()-86400 );
$stmt = $pdo->prepare('SELECT id, created FROM table1 WHERE created >= :yesterday AND created < :today');
$stmt->bindParam(':today', $today);
$stmt->bindParam(':yesterday', $yesterday);
$stmt->execute();
$realm_data = $stmt->fetch();
To get all the records for the last 7 days do the following:
$seven_days_ago = date('Y-m-d', strtotime('-7 days'));
$stmt = $pdo->prepare('SELECT id, created FROM table1 WHERE created >= :seven_days_ago');
$stmt->bindParam(':seven_days_ago', $seven_days_ago);
$stmt->execute();
$realm_data = $stmt->fetch();
Assumptions/Tip:
The column in MySQL is set to the datetime format.