Missing Data In Date-Based Queries? Be Sure To Account For The Time Of Day

Steve Sohcot
2 min readMay 30, 2023

--

Often when working with database queries, I have to set criteria on a field of data type DATE.

It’s pretty common for me to do something like:

SELECT * FROM myTable 
WHERE the_month BETWEEN '1/1/2024' AND '1/31/2024'

I recently had to deal with a dataset where I was dealing with DATETIME.

The same query as above was missing some of the data in the output.

The Problem

If there was an entry with a timestamp of November 30 at 6:00 AM, then the following query would not work:

SELECT * FROM myTable 
WHERE the_month BETWEEN '11/1/2024' AND '11/30/2024'

The reason is that when you don’t include a timestamp in your criteria, it’ll default to 12:00 AM.

The above is the same as:

SELECT * FROM myTable 
WHERE the_month BETWEEN '11/1/2024 00:00:00' AND '11/30/2024 00:00:00'

Thus my row of data for 11/30/2024 6:00:00 would not be picked up, as it falls outside of the range in my criteria (i.e. after the End Date).

The Solution

While this is for MySQL, database-wise it also affects SQL Server

I was working with PHP and MySQL. I would query based on user-inputs, where the UI formatted dates as “mm/dd/yyyy” (ex. 11/30/2024 meaning November 30, 2024).

MySQL queries (at least my instance) requires dates to be in the format of “Y-m-d”.

I created a PHP function to convert the dates from my input format into the required MySQL format to query a database. To use this one function, the trick is to pass in a second (optional) parameter to indicate if we need to specify “midnight.”

// PHP function to convert dates to MySQL-friendly format
function convertDateFormatForSQL($date, $endOfDay = false) {

if ($endOfDay) {
return date("Y-m-d 23:59:59", strtotime($date));
} else {
return date("Y-m-d", strtotime($date));
}

}

$startDate = convertDateFormatForSQL("11/1/2024");
$endDate = convertDateFormatForSQL("11/30/2024", true); // set to midnight


$sql = "SELECT * FROM myTable
WHERE the_month BETWEEN $startDate AND $endDate";

Explanation

Pass each date into the function to convert it to “Y-m-d”.

It’s okay for the Start Date to start at 12:00 AM so I did not specify the second parameter in my convertDateFormatForSQL() function. By default, it’s set to false.

However the End Date needs to be at midnight, so I did specify true in the second parameter for that one.

The End Date in the SQL, specifying midnight, will now include the correct results.

--

--

No responses yet