I have a table and it has a column start_date
. I have two variable fields/filters from_date
and to_date
on which I want my records to be filtered.
I am working on a SQL/PostgreSQL/pgAdmin4 script that returns all the rows whose start_date
is between from_date
and to_date
only matching day and month (not year). For example: let’s say from_date
is ‘2023-12-25’ and to_date
is ‘2023-02-07’. I want to get all the rows where the start_date
lies between these dates regardless of the year.
So, it will return rows falling between 25th Dec and 7th Feb. Thanks in advance.
I have checked this answer In SQL how to return records matching date and month only (ignore year)
and tried the same with the query:
and tried the following query:
SELECT *
FROM mytable
WHERE status = 'Active'
AND (
(
EXTRACT(MONTH FROM from_date::DATE) <= EXTRACT(MONTH FROM to_date::DATE)
AND (TO_CHAR(start_date::date, 'MM/DD') BETWEEN TO_CHAR(from_date::date, 'MM/DD') AND TO_CHAR(to_date::date, 'MM/DD'))
)
OR (
EXTRACT(MONTH FROM from_date::DATE) > EXTRACT(MONTH FROM to_date::DATE)
AND (
(TO_CHAR(start_date::date, 'MM/DD') BETWEEN TO_CHAR(from_date::date, 'MM/DD') AND '31/12')
OR (TO_CHAR(start_date::date, 'MM/DD') BETWEEN '01/01' AND TO_CHAR(to_date::date, 'MM/DD'))
)
)
);
but not getting any data
2
Answers
You can try
This will use the numerical version of the day of the year as the comparison between the given dates.
You might need to swap
from_date
andto_date
around as I’ve takento_date
to be the later date.See https://www.postgresqltutorial.com/postgresql-date-functions/postgresql-date_part/ for more date parts you can use with
date_part
.EDIT: To account for the discrepancies of leap years try this
I created this, which seems to work:
see: DBFIDDLE
d
contains the values likestartdate
,fromdate
andtodate
fromto
calculates some variables used in the final statementdates
creates a list of all the dates from ‘2022-01-01’ to ‘2025-01-01’