Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql: alternative to WHERE IN respective WHERE NOT IN

Tags:

sql

postgresql

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 the performence, should I switch i.e. to joins?

Many thanks!

like image 628
MrG Avatar asked Nov 20 '09 09:11

MrG


People also ask

Can I use alias in WHERE clause Postgres?

Column alias is not supported in WHERE or HAVING clauses. postgres=# SELECT emp.

What is difference between <> and != Postgres?

<> is the standard SQL operator meaning "not equal". Many databases, including postgresql, supports != as a synonym for <> . They're exactly the same in postgresql.

How can I list all foreign keys referencing a given table in Postgres?

To get a list of all foreign keys of the table using psql you can use the \d your_table_name command line.

What is <> operator in PostgreSQL?

An operator is a reserved word or a character used primarily in a PostgreSQL statement's WHERE clause to perform operation(s), such as comparisons and arithmetic operations. Operators are used to specify conditions in a PostgreSQL statement and to serve as conjunctions for multiple conditions in a statement.


2 Answers

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.

like image 123
Erlock Avatar answered Oct 06 '22 02:10

Erlock


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.

like image 36
Andomar Avatar answered Oct 06 '22 01:10

Andomar