Set operations

The easiest way to show how a set operation works is to look at a query that uses one:

SELECT * FROM customers WHERE state='MD' 
INTERSECT
SELECT * FROM customers WHERE zip='21340';  

This is obviously a trivial example—you could just put both WHERE clauses into a single line and get the same result more easily. But there are more complicated types of queries you can build using INTERSECT, INTERSECT ALL, EXCEPT, and EXCEPT ALL that are the easiest way to write what you're looking for. EXCEPT is shown later for helping determine whether two queries give the same output, for example.

SetOp changed to HashSetOp in PostgreSQL 8.4. Here are the new and old types of plans you can get when executing an INTERSECT or EXCEPT:

EXPLAIN ...

Get PostgreSQL 10 High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.