'I want to fetch the data where I will put the date and I will get data from last three years to the entered date

imagine if I put the date 27th Jan 2022 then I should get all the records from 26th Jan 2019 till 27th Jan 2022.



Solution 1:[1]

There are a couple of ways to do this. One caveat is how you are defining three years:

select '2022-01-27'::date - interval '3 years';
      ?column?       
---------------------
 2019-01-27 00:00:00

or as you have it:

2019-01-26 to 2022-01-27.

Using your definition:

SELECT * FROM some_table WHERE date_fld BETWEEN '2019-01-26' and '2022-01-27';

--Using a date range

select * from  some_table where date_fld <@ daterange('2019-01-26', '2022-01-27', '[]');
 t
--or
select * from some_table where  date_fld <@ daterange('2019-01-26', '2022-01-28');
t

By default date ranges are exclusive on the upper bound, that is why you need to include either the '[]' or bump the upper bound up one date(which is actually what the '[]' does).

For more information on ranges Ranges and Range operators

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1