INTERSECT
Return only rows that appear in both result sets. This set operator identifies the common records shared between two queries.
Syntax
SELECT ...
(INTERSECT [ALL | DISTINCT] | EXCEPT [ALL | DISTINCT] | UNION [ALL | DISTINCT]) SELECT ...
[(INTERSECT [ALL | DISTINCT] | EXCEPT [ALL | DISTINCT] | UNION [ALL | DISTINCT]) SELECT ...]
[ORDER BY [column [, column ...]]]
[LIMIT {[offset,] row_count | row_count OFFSET offset}]Description
MariaDB has supported INTERSECT (as well as EXCEPT) in addition to UNION since MariaDB 10.3.
All behavior for naming columns, ORDER BY and LIMIT is the same as for UNION.
INTERSECT implicitly supposes a DISTINCT operation.
The result of an intersect is the intersection of right and left SELECT results, i.e. only records that are present in both result sets will be included in the result of the operation.
INTERSECT has higher precedence than UNION and EXCEPT (unless running running in Oracle mode, in which case all three have the same precedence). If possible it will be executed linearly, but if not, it will be translated to a subquery in the FROM clause:
(SELECT a,b FROM t1)
UNION
(SELECT c,d FROM t2)
INTERSECT
(SELECT e,f FROM t3)
UNION
(SELECT 4,4);will be translated to:
Parentheses
Parentheses can be used to specify precedence.
Parentheses cannot be used to specify precedence.
MariaDB starting with 10.5.0
ALL/DISTINCT
INTERSECT ALL and INTERSECT DISTINCT . The ALL operator leaves duplicates intact, while the DISTINCT operator removes duplicates. DISTINCT is the default behavior if neither operator is supplied.
DISTINCT is the only behavior available.
Examples
Show customers which are employees:
Difference between UNION, EXCEPT and INTERSECT:
Parentheses for specifying precedence:
See Also
Get Set for Set Theory: UNION, INTERSECT and EXCEPT in SQL (video tutorial)
This page is licensed: CC BY-SA / Gnu FDL
Last updated
Was this helpful?

