zabbix=# EXPLAIN ANALYZE SELECT e.* FROM events e WHERE EXISTS (SELECT NULL FROM functions f, items i, hosts_groups hgg JOIN rights r ON r.id = hgg.groupid AND r.groupid IN ( '32', '50', '56' ) WHERE e.objectid = f.triggerid AND f.itemid = i.itemid AND i.hostid = hgg.hostid GROUP BY f.triggerid HAVING Min(r.permission) > 0 AND Max(r.permission) >= 2) AND e.object = '0' AND e.source = '0' ORDER BY e.clock LIMIT 1 offset 0; QUERY PLAN ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ - Limit (cost=0.56..61.00 rows=1 width=40) (actual time=146.021..146.021 rows=1 loops=1) -> Index Scan using events_2 on events e (cost=0.56..76464189.79 rows=1265166 width=40) (actual time=146.020..146.020 rows=1 loops=1) Index Cond: ((source = 0) AND (object = 0)) Filter: (SubPlan 1) Rows Removed by Filter: 266 SubPlan 1 -> GroupAggregate (cost=1.40..29.62 rows=1 width=12) (actual time=0.031..0.031 rows=0 loops=267) Filter: ((min(r.permission) > 0) AND (max(r.permission) >= 2)) -> Nested Loop (cost=1.40..29.60 rows=1 width=12) (actual time=0.030..0.030 rows=0 loops=267) -> Nested Loop (cost=1.13..27.79 rows=5 width=16) (actual time=0.007..0.015 rows=6 loops=267) -> Nested Loop (cost=0.85..27.04 rows=2 width=16) (actual time=0.005..0.009 rows=2 loops=267) -> Index Scan using functions_1 on functions f (cost=0.42..10.13 rows=2 width=16) (actual time=0.002..0.003 rows=2 loops=267) Index Cond: (e.objectid = triggerid) -> Index Scan using items_pkey on items i (cost=0.42..8.45 rows=1 width=16) (actual time=0.002..0.002 rows=1 loops=514) Index Cond: (itemid = f.itemid) -> Index Only Scan using hosts_groups_1 on hosts_groups hgg (cost=0.28..0.34 rows=3 width=16) (actual time=0.001..0.002 rows=3 loops=514) Index Cond: (hostid = i.hostid) Heap Fetches: 530 -> Index Scan using rights_2 on rights r (cost=0.28..0.35 rows=1 width=12) (actual time=0.002..0.002 rows=0 loops=1498) Index Cond: (id = hgg.groupid) Filter: (groupid = ANY ('{32,50,56}'::bigint[])) Rows Removed by Filter: 4 Total runtime: 146.103 ms (23 rows)