开发者

Postgresql: alternative to WHERE IN respective WHERE NOT IN

开发者 https://www.devze.com 2022-12-11 20:10 出处:网络
I have several statements which access very large Postgresql tables i.e. with: SELECT a.id FROM a WHERE a.id IN ( SELECT b.id FROM b );

I have several statements which access very large Postgresql tables i.e. with:

SELECT a.id FROM a WHERE a.id IN ( SELECT b.id FROM b );
SELECT a.id FROM a WHERE a.id NOT IN ( SELECT b.id FROM b );

Some of them even access even more tables in that way. What is the best approach to increase t开发者_运维问答he performence, should I switch i.e. to joins?

Many thanks!


JOIN will be far more efficient, or you can use EXISTS:

SELECT a.id FROM a WHERE EXISTS (SELECT 1 FROM b WHERE b.id = a.id)

The subquery will return at most 1 row.


Here's a way to filter rows with an INNER JOIN:

SELECT     a.id 
FROM       a 
INNER JOIN b ON a.id = b.id

Note that each version can perform differently; sometimes IN is faster, sometimes EXISTS, and sometimes the INNER JOIN.


Yes, i would recomend going to joins. It will speed up the select statements.

0

精彩评论

暂无评论...
验证码 换一张
取 消