QUERY PLAN
Unique (cost=17420827.40..17421344.90 rows=69000 width=17)
-> Sort (cost=17420827.40..17420999.90 rows=69000 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)
-> GroupAggregate (cost=17196057.71..17415281.76 rows=69000 width=17)
Group Key: tt.dt, cl.id
-> Sort (cost=17196057.71..17239661.02 rows=17441324 width=44)
Sort Key: tt.dt, cl.id
-> Nested Loop Left Join (cost=20.26..13488638.22 rows=17441324 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-07-25 08:54:09+08'::timestamp with time zone) OR ((sh.start_at - sh.alarm_before) > '2025-07-25 08:54:09+08'::timestamp with time zone))
-> Nested Loop Left Join (cost=0.02..41061.53 rows=102695 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..514.88 rows=345 width=36)
-> Seq Scan on tbl_calendars cl (cost=0.00..513.15 rows=345 width=36)
Filter: (created_by = 5300)
-> Materialize (cost=20.24..439.22 rows=1027 width=32)
-> Bitmap Heap Scan on tbl_schedules sh (cost=20.24..434.08 rows=1027 width=32)
Recheck Cond: (created_by = 5300)
-> Bitmap Index Scan on tbl_schedules_created_by_idx (cost=0.00..19.99 rows=1027 width=0)
Index Cond: (created_by = 5300)