I have tried both:
smthng = ANY
(select id from exmplTable)
smthng IN
(select id from exmplTable)
and I am getting the same results for my data.
Is there any difference for the two expressions?
PostgreSQL has an ANY operator that is used to compare a scalar value with a set of values returned by a subquery. Syntax: expression operator ANY(subquery) The below rules must be followed while using PostgreSQL ANY operator: The subquery must return exactly one column.
Note that the <> ANY operator is different from NOT IN. The ANY and ALL operators are used with a WHERE or HAVING clause. The ANY operator returns true if any of the subquery values meet the condition. The ALL operator returns true if all of the subquery values meet the condition.
Hash join strategy Building the hash table is an extra start-up effort, but probing the hash is much faster than scanning the inner relation.
In general, EXISTS and direct JOIN of tables often results in good results. PostgreSQL optimizes the IN clause to a hashed sub-plan in many cases. “IN” can result in a better plan and execution in some specific situations. Again, everything depends on how a query is rewritten/transformed internally.
No, in these variants are same:
You can see - the execution plans are same too:
postgres=# explain select * from foo1 where id in (select id from foo2); ┌──────────────────────────────────────────────────────────────────┐ │ QUERY PLAN │ ╞══════════════════════════════════════════════════════════════════╡ │ Hash Semi Join (cost=3.25..21.99 rows=100 width=4) │ │ Hash Cond: (foo1.id = foo2.id) │ │ -> Seq Scan on foo1 (cost=0.00..15.00 rows=1000 width=4) │ │ -> Hash (cost=2.00..2.00 rows=100 width=4) │ │ -> Seq Scan on foo2 (cost=0.00..2.00 rows=100 width=4) │ └──────────────────────────────────────────────────────────────────┘ (5 rows) postgres=# explain select * from foo1 where id = any (select id from foo2); ┌──────────────────────────────────────────────────────────────────┐ │ QUERY PLAN │ ╞══════════════════════════════════════════════════════════════════╡ │ Hash Semi Join (cost=3.25..21.99 rows=100 width=4) │ │ Hash Cond: (foo1.id = foo2.id) │ │ -> Seq Scan on foo1 (cost=0.00..15.00 rows=1000 width=4) │ │ -> Hash (cost=2.00..2.00 rows=100 width=4) │ │ -> Seq Scan on foo2 (cost=0.00..2.00 rows=100 width=4) │ └──────────────────────────────────────────────────────────────────┘ (5 rows)
This may be an edge case but:
select * from myTable where id IN ()
will produce: ERROR: syntax error at or near ")"
but
select * from myTable where id = ANY('{}');
Will return an empty result set
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With