Search code examples
postgresqldatewhere-clause

Postgres - Pass dynamically generated date to where clause


I need to generate series of date till current_date based on job's last run date

  • last run date ='2022-10-01'
  • current date = '2022-10-05'

generate date like

varchar dynamic_date = '2022-10-01','2022-10-02','2022-10-03','2022-10-04','2022-10-05'

and pass to where to clause

select * 
from t1 
where created_date in (dynamic_date)

this is not allowed as dynamic_date is varchar and created_date is date column

trying to find efficient way to do this


Solution

  • You can use generate_series()

    select * 
    from t1 
    where created_date in (select g.dt::date
                           from generate_series(date '2022-10-01', 
                                                current_date, 
                                                interval '1 day') as g(dt)
                          )
    

    Or even simpler:

    select * 
    from t1 
    where created_date >= date '2022-10-01'
      and created_date <= current_date