I need to fetch the records that are falling between the start date and end date in oracle SQL. I 'll be having varStartDate
and varEndDate
. I want to fetch all records that are falling between the varStartDate
and varEndDate
. I am trying below query where first I am fetching recent start date i.e. in the past and end date i.e. in future. Secondly once I have the start date and end date I am to fetch all the records where startdate
>= and enddate
<=.
Start Date and End Date are DATE
datatype.
Leave Type | Start Date | End Date | LeaveNumber |
---|---|---|---|
Annual Leave | 08-OCT-21 | 08-OCT-21 | 24042 |
Annual Leave | 29-NOV-21 | 29-NOV-21 | 24043 |
Annual Leave | 23-DEC-21 | 23-DEC-21 | 30069 |
Annual Leave | 29-DEC-21 | 31-DEC-21 | 30112 |
Annual Leave | 24-JAN-22 | 24-JAN-22 | 30189 |
Query:
with RosterStartDate as (
select max(start_date) as START_DATE
from Payrollrecords
where START_DATE < TO_DATE('2021-11-20','YYYY-MM-DD')
),
RosterEndDate as (
select min(end_date) as END_DATE
from Payrollrecords where END_DATE >= TO_DATE('2022-11-30','YYYY-MM-DD')
)
select *
from Payrollrecords
where START_DATE = (select START_DATE from RosterStartDate)
and END_DATE = (select END_DATE from RosterEndDate)
The query is returning no records if RosterEndDate.END_DATE
is null
( it is nul
l if no end date is found beyond the varEndDate
). It would be great if you can help me the with the optimized query.