Sql "between" not inclusive
To exclude the endpoints in SQL select queries, use >
and <
rather than BETWEEN
. For instance, to exclude the dates '2021-01-01' and '2021-01-31', your SQL statement should look like:
The SQL engine will ignore the boundary dates and yield only the rows with dates within the specified range.
Overview: The details matter in dates
Factoring Time with Dates
In SQL, the data type datetime
treats 'YYYY-MM-DD'
as 'YYYY-MM-DD 00:00:00'
. If your need is to include an entire day's data, like for '2021-01-31', you should form your SQL query so that the end date is less than the sequential day:
Date-only Filtering in Datetime Column
When dealing with a single date search in a datetime column, the CAST
function can bring you closer to accuracy:
Practice Variable Declarations
When using functions like DATEDIFF
, it's a good practice to declare your variables beforehand:
Parentheses for grouping
Use parentheses for better clarity in complex queries, especially those involving multiple inequalities:
Digging Deeper: More nuances of date comparison
Using DATE function
To fetch data at date-level precision, leverage the DATE
function:
Matching Date Formats
Be sure that the date format in your query matches your database's to avoid perennial facepalm 🤦♂️ situations:
Inclusive Query for Time Interval
Managing inclusivity within specific time intervals eliminates any off-by-a-minute errors:
Was this article helpful?