-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathANY.sql
More file actions
91 lines (69 loc) · 2.26 KB
/
ANY.sql
File metadata and controls
91 lines (69 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
--PostgreSQL ANY Operator
--The PostgreSQL ANY operator compares a value to a set of values returned by a subquery.
--The following illustrates the syntax of the ANY operator:
expression operator ANY(subquery)
/*In this syntax:
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.
Note that SOME is a synonym for ANY, meaning that you can substitute SOME for ANY in any SQL statement.*/
--PostgreSQL ANY examples
--The following example returns the maximum length of film grouped by film category:
SELECT
MAX( length ),cat.category_id
FROM
film f
INNER JOIN film_category cat
USING(film_id)
GROUP BY
category_id
order by
category_id;
--You can use this query as a subquery in the following statement that finds the films whose lengths are greater than or equal to the maximum length of any film category :
SELECT title
FROM film
WHERE length >= ANY(
SELECT MAX( length )
FROM film
INNER JOIN film_category USING(film_id)
GROUP BY category_id );
/*For each film category, the subquery finds the maximum length. The outer query looks at all these values and determines which film’s lengths are greater than or equal to any film category’s maximum length.
Note that if the subquery does not return any rows, the entire query returns an empty result set.*/
--ANY vs. IN
--The = ANY is equivalent to IN operator.
--The following example gets the film whose category is either Action or Drama
SELECT
title,
category_id
FROM
film
INNER JOIN film_category
USING(film_id)
WHERE
category_id IN(
SELECT
category_id
FROM
category
WHERE
NAME = 'Action'
OR NAME = 'Drama'
);
--The following statement uses the IN operator which produces the same result:
SELECT
title,
category_id
FROM
film
INNER JOIN film_category
USING(film_id)
WHERE
category_id IN(
SELECT
category_id
FROM
category
WHERE
NAME = 'Action'
OR NAME = 'Drama'
);