Open In App

PostgreSQL – ANY Operator

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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.
  • The ANY operator must be preceded by one of the following comparison operator =, <=, >, <, > and <>
  • The ANY operator returns true if any value of the subquery meets the condition, otherwise, it returns false.

For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link in our examples.

Example 1:

Here we will query for the maximum length of film grouped by film category from the “film” table of our sample database.

SELECT title
FROM film
WHERE length >= ANY(
    SELECT MAX( length )
    FROM film
    INNER JOIN film_category USING(film_id)
    GROUP BY  category_id );

Output:

Example 2:
Here we will query for the films whose category is either Action(category_id = 1) or Drama(category_id = 7) from the “category” table of our sample database.

SELECT
    title,
    category_id
FROM
    film
INNER JOIN film_category
        USING(film_id)
WHERE
    category_id = ANY(
        SELECT
            category_id
        FROM
            category
        WHERE
            NAME = 'Action'
            OR NAME = 'Drama'
    );

Output:


Last Updated : 28 Aug, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads