Need help in optimizing a slow Postgres Query
Select A.Daily,
       count(distinct da.user) as Users
from 
    (
        -- calculate all constants needed once
        select date(d) as Daily,
               date(d) - Interval '30' DAY as DailyStart,
               date(d) - Interval '1' DAY as DailyEnd
        from generate_series(current_date - Interval '10' DAY, current_date - Interval '1' DAY, '1 day') d 
    -- GROUP BY by unique value makes no sense
    -- ORDER BY in subquery is ignored
    ) as A 
                                 -- avoid fn(table.field)
join public.downloads_activity da on da.created_at &gt;= A.DailyStart 
                                 and da.created_at &lt; A.DailyEnd
group by 1
order by 1