IN vs ANY operator in PostgreSQL

别等时光非礼了梦想. 提交于 2019-11-26 09:18:37

问题


What is the difference between IN and ANY operator in PostgreSQL?
The working mechanism of both seems to be the same. Can anyone explain this with an example?


回答1:


Logically, quoting the manual:

IN is equivalent to = ANY.

But there are two syntax variants of IN and two variants of the ANY construct. Details:

  • How to use ANY instead of IN in a WHERE clause with Rails?

The IN () variant taking a set is equivalent to = ANY() taking a set, as demonstrated here:

  • postgreSQL - in vs any

But the second variant of each is not equivalent to the other. The second variant of the ANY construct takes an array (must be an actual array type), while the second variant of IN takes a comma-separated list of values. This leads to different restrictions in passing values and can also lead to different query plans in special cases:

  • Index not used with =any() but used with in
  • Pass multiple sets or arrays of values to a function

The ANY construct is far more versatile, as it can be combined with various operators, not just =. Example for LIKE:

SELECT 'foo' LIKE ANY('{FOO,bar,%oo%}');

For a big number of values, providing a set scales better for each:

  • Optimizing a Postgres query with a large IN

Related:

  • Can PostgreSQL index array columns?

Inversion / opposite / exclusion

The inversion of:

SELECT * FROM foo WHERE id = ANY (ARRAY[1, 2]);

"find rows where id is not in the array" - is:

SELECT * FROM foo WHERE id <> ALL (ARRAY[1, 2]);

Which is the same as:

SELECT * FROM foo WHERE NOT (id = ANY (ARRAY[1, 2]));

Rows with id IS NULL do not pass either of these expressions. To include NULL values additionally:

SELECT * FROM foo WHERE (id = ANY (ARRAY[1, 2])) IS NOT TRUE;


来源:https://stackoverflow.com/questions/34627026/in-vs-any-operator-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!