QUERY PLAN
Unique (cost=38815.43..38857.43 rows=5600 width=17)
-> Sort (cost=38815.43..38829.43 rows=5600 width=17)
Sort Key: (date(tt.dt)) DESC, (CASE WHEN ((count(cl.alarm_before) <> 0) OR (count(sh.alarm_before) <> 0)) THEN true ELSE false END)
-> HashAggregate (cost=38368.79..38466.79 rows=5600 width=17)
Group Key: tt.dt, cl.id
-> Nested Loop Left Join (cost=4.55..37927.71 rows=44108 width=44)
Join Filter: ((((((date(tt.dt))::text || ' 00:00:00'::text))::timestamp without time zone >= sh.start_at) AND ((((date(tt.dt))::text || ' 23:59:59'::text))::timestamp without time zone <= sh.end_at)) OR (((((date(tt.dt))::text || ' 00:00:00'::text))::timestamp without time zone <= sh.start_at) AND ((((date(tt.dt))::text || ' 23:59:59'::text))::timestamp without time zone >= sh.start_at)) OR (((((date(tt.dt))::text || ' 00:00:00'::text))::timestamp without time zone <= sh.end_at) AND ((((date(tt.dt))::text || ' 23:59:59'::text))::timestamp without time zone >= sh.end_at)))
Filter: (((cl.start_at - cl.alarm_before) > '2025-08-29 05:44:44+08'::timestamp with time zone) OR ((sh.start_at - sh.alarm_before) > '2025-08-29 05:44:44+08'::timestamp with time zone))
-> Nested Loop Left Join (cost=0.02..3817.66 rows=8335 width=36)
Join Filter: ((((((date(tt.dt))::text || ' 00:00:00'::text))::timestamp without time zone >= cl.start_at) AND ((((date(tt.dt))::text || ' 23:59:59'::text))::timestamp without time zone <= cl.end_at)) OR (((((date(tt.dt))::text || ' 00:00:00'::text))::timestamp without time zone <= cl.start_at) AND ((((date(tt.dt))::text || ' 23:59:59'::text))::timestamp without time zone >= cl.start_at)) OR (((((date(tt.dt))::text || ' 00:00:00'::text))::timestamp without time zone <= cl.end_at) AND ((((date(tt.dt))::text || ' 23:59:59'::text))::timestamp without time zone >= cl.end_at)))
-> Function Scan on generate_series tt (cost=0.02..10.02 rows=1000 width=8)
-> Materialize (cost=0.00..517.72 rows=28 width=36)
-> Seq Scan on tbl_calendars cl (cost=0.00..517.58 rows=28 width=36)
Filter: (created_by = 5446)
-> Materialize (cost=4.53..103.33 rows=32 width=32)
-> Bitmap Heap Scan on tbl_schedules sh (cost=4.53..103.17 rows=32 width=32)
Recheck Cond: (created_by = 5446)
-> Bitmap Index Scan on tbl_schedules_created_by_idx (cost=0.00..4.53 rows=32 width=0)
Index Cond: (created_by = 5446)