INTERSECT clause
The INTERSECT expression returns all rows contained in the results of both the first and the second query. In other words, this expression calculates the intersection of the results of the two queries.
To be able to compute the intersection for two queries, the queries must be compatible. This means that they must have the same number of columns and the corresponding columns must be of compatible types.
Examples
-
Let’s output the list of countries that occur in the
countrycolumn in both the capitals table and the population table:CREATE TABLE capitals (country VARCHAR, capital VARCHAR); CREATE TABLE population (country VARCHAR, population_mil BIGINT); INSERT INTO capitals VALUES ('Russia', 'Moscow'), ('Italy', 'Rome'), ('Spain', 'Madrid'), ('France', 'Paris'); INSERT INTO population VALUES ('Russia', 143), ('Spain', 48), ('Brazil', 211); SELECT country FROM capitals INTERSECT SELECT country FROM population;+---------+ | country | +---------+ | Russia | +---------+ | Spain | +---------+ -
Let’s use the functions
unnestandgenerate_seriesand compute the intersection of two queries — for numbers from1to10and for numbers from10to20:SELECT unnest(generate_series(1, 10)) as numbers INTERSECT SELECT unnest(generate_series(10, 20)) as numbers;+---------+ | numbers | +---------+ | 10 | +---------+