Postgresql query between date ranges
To fetch records from a specific date range, make use of the BETWEEN
operator:
You need to replace table_name
, date_column
, start_date
, and end_date
as required. Be sure to format your dates in the YYYY-MM-DD or YYYY-MM-DD HH:MM:SS format for precision. This SQL pattern fetches all the entries where date_column
falls within the start_date
to end_date
, inclusive.
If you want to exclude the end_date
from results, slightly tweak the query as follows:
Additionally, consider timestamp
or timestamptz
if precision and time zones carry weight in your data.
Power-up your query with PostgreSQL's date ranges and operators
PostgreSQL's advanced range types and operators allow for efficient queries within date ranges:
Here, @>
operator checks if the date_column
fell within the specified daterange
. This powerful technique is more optimal than using BETWEEN
and fully utilizes PostgreSQL's range capabilities.
Effortlessly calculate dates with date_trunc
To effortlessly handle start and end dates, harness the power of the date_trunc
function:
This query fetches rows for the current month, automating the start and end date handling without any manual input. You can now enjoy a cup of coffee instead!
Unleashing the power of BETWEEN SYMMETRIC
Occasionally, programmers (yes, even us!) might mix up the date order. To avoid this boo-boo, use BETWEEN SYMMETRIC
:
Now PostgreSQL handles the argument swapping for you. Relax, and let PostgreSQL do the heavy lifting!
Optimizing index for speedy queries
To speed up your range queries, maintain index usage. PostgreSQL optimizes indexing such that it allows range seeks instead of time-consuming table scans:
Don't mind those table scans, indexing has your back!
Dropping ‘excessive row calculations’ weight
Steer clear of DATEPART
for year and month comparisons to avoid computation for each row. Focus on queries using >=
and <
for efficient index use, and leverage date_trunc
function to group by year or month.
Was this article helpful?