Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A PostgreSQL query with 'ANY' is not working

SELECT "Ticket_id"  FROM "Tickets"  WHERE "Status" = 1 AND ("Ticket_id" !=  ANY(array[1,2,3])) Limit 6 

And the result is 1,2,3,4,5,6

like image 417
Bogo Avatar asked May 20 '12 13:05

Bogo


People also ask

What does any do in PostgreSQL?

PostgreSQL has an ANY operator that is used to compare a scalar value with a set of values returned by a subquery. The below rules must be followed while using PostgreSQL ANY operator: The subquery must return exactly one column.

Is with a clause in PostgreSQL?

With clause: This is defined as a clause that was used to execute the Subquery and large Subquery in PostgreSQL. Name of CTE: This is defined name of the common table expression which was we have used with clause. AS: This is defined as we have used alias name of a common table expression in with clause.

Is not operator PostgreSQL?

The PostgreSQL NOT condition (also called the NOT Operator) is used to negate a condition in a SELECT, INSERT, UPDATE, or DELETE statement.

What is the wildcard in PostgreSQL?

Wildcards in PostgreSQL is used to find matching rows values from tables; it is also used to find matching patterns rows from tables, Wildcards is also used to find matching rows, column and tables names; the output of the wildcard operator will return matching name, which was table name, column name or rows, In ...


1 Answers

You want to use ALL, not ANY. From the fine manual:

9.21.3. ANY/SOME (array)

expression operator ANY (array expression) 

[...] The left-hand expression is evaluated and compared to each element of the array using the given operator, which must yield a Boolean result. The result of ANY is "true" if any true result is obtained.

So if we say this:

1 != any(array[1,2]) 

then we'll get true since (1 != 1) or (1 != 2) is true. ANY is essentially an OR operator. For example:

=> select id from (values (1),(2),(3)) as t(id) where id != any(array[1,2]);  id  ----   1   2   3 (3 rows) 

If we look at ALL, we see:

9.21.4. ALL (array)

expression operator ALL (array expression) 

[...] The left-hand expression is evaluated and compared to each element of the array using the given operator, which must yield a Boolean result. The result of ALL is "true" if all comparisons yield true...

so if we say this:

1 != all(array[1,2]) 

then we'll get false since (1 != 1) and (1 != 2) is false and we see that ALL is essentially an AND operator. For example:

=> select id from (values (1),(2),(3)) as t(id) where id != all(array[1,2]);  id  ----   3 (1 row) 

If you want to exclude all values in an array, use ALL:

select "Ticket_id" from "Tickets" where "Status" = 1   and "Ticket_id" != all(array[1,2,3]) limit 6 
like image 200
mu is too short Avatar answered Oct 09 '22 02:10

mu is too short