QUERY PLAN
Aggregate (cost=859.93..859.94 rows=1 width=8)
-> Sort (cost=851.55..852.95 rows=559 width=998)
Sort Key: c.signed_at DESC, c.created_at DESC
-> Hash Left Join (cost=606.41..826.04 rows=559 width=998)
Hash Cond: (client.sales_rep = sgr.sales_id)
-> Hash Left Join (cost=604.35..819.01 rows=559 width=16)
Hash Cond: (c.client_id = client.id)
-> Hash Join (cost=475.99..689.17 rows=559 width=16)
Hash Cond: (p.id = c.project_id)
-> Seq Scan on tbl_projects p (cost=0.00..201.62 rows=1607 width=4)
Filter: (created_by = ANY ('{1001,1004,1005,1013,5087,5295,5300,5311,5329,5332,5420}'::integer[]))
-> Hash (cost=463.80..463.80 rows=975 width=20)
-> Hash Join (cost=404.58..463.80 rows=975 width=20)
Hash Cond: (c.id = sub.id)
-> Seq Scan on tbl_sales_contracts c (cost=0.00..55.24 rows=1510 width=24)
Filter: need_analysis
-> Hash (cost=392.28..392.28 rows=984 width=4)
-> Subquery Scan on sub (cost=367.68..392.28 rows=984 width=4)
-> HashAggregate (cost=367.68..382.44 rows=984 width=12)
Group Key: sc.id
Filter: (CASE WHEN (sc.including_tax AND ((sum(sci.amount) < sc.amount) OR (sum(sci.amount) IS NULL))) THEN 0 ELSE 1 END = 0)
-> Hash Right Join (cost=291.87..360.30 rows=984 width=17)
Hash Cond: (sci.contract_id = sc.id)
-> Seq Scan on tbl_sales_contract_invoices sci (cost=0.00..52.18 rows=1718 width=10)
-> Hash (cost=280.96..280.96 rows=873 width=11)
-> Hash Join (cost=221.71..280.96 rows=873 width=11)
Hash Cond: (sc.project_id = p_1.id)
-> Seq Scan on tbl_sales_contracts sc (cost=0.00..55.24 rows=1524 width=15)
-> Hash (cost=201.62..201.62 rows=1607 width=4)
-> Seq Scan on tbl_projects p_1 (cost=0.00..201.62 rows=1607 width=4)
Filter: (created_by = ANY ('{1001,1004,1005,1013,5087,5295,5300,5311,5329,5332,5420}'::integer[]))
-> Hash (cost=104.83..104.83 rows=1883 width=8)
-> Seq Scan on tbl_clients client (cost=0.00..104.83 rows=1883 width=8)
-> Hash (cost=1.47..1.47 rows=47 width=4)
-> Seq Scan on tbl_sales_group_relationships sgr (cost=0.00..1.47 rows=47 width=4)