Для дальнейшего повышения производительности мы можем сделать это:
select exists (select id
from blog_post
where company_id = 5
and status_id = 3 limit 1);
- Добавить ограничение во вложенный запрос
- Вместо select * мы можем сделать select any_column
Я пробовал это с образцом базы данных:
с идентификатором и лимитом:
explain analyze (select exists (select user_id from sample_table where sample_ids=4 and user_id=5 limit 1));
QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------------
Result (cost=8.17..8.18 rows=1 width=1) (actual time=0.014..0.014 rows=1 loops=1)
InitPlan 1 (returns $0)
-> Index Scan using sample_table_pkey on sample_table (cost=0.15..8.17 rows=1 width=0) (actual time=0.012..0.012 rows=1 loops=1)
Index Cond: (user_id = 5)
Filter: (sample_ids = 4)
Planning Time: 0.091 ms
Execution Time: 0.032 ms
без идентификатора и *
explain analyze (select exists (select * from sample_table where sample_ids=4 and user_id=5));
QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------------
Result (cost=8.17..8.18 rows=1 width=1) (actual time=0.014..0.014 rows=1 loops=1)
InitPlan 1 (returns $0)
-> Index Scan using sample_table_pkey on sample_table (cost=0.15..8.17 rows=1 width=0) (actual time=0.012..0.012 rows=1 loops=1)
Index Cond: (user_id = 5)
Filter: (sample_ids = 4)
Planning Time: 0.084 ms
Execution Time: 0.034 ms