Testing for query equivalence

In one of the Hash Join examples, a complicated query using EXISTS was used to determine whether each product had ever been ordered. There's theoretically another way to figure that out: the inventory information for each product includes a sales count. If those are complete—every product is included in that inventory, even if it's never been sold—then a query looking for zero sales of an item should give the same results:

SELECT prod_id FROM inventory WHERE sales=0;  

This looks like the same list, but it's long enough that comparing every entry would be tedious. You can easily compare the output from two queries to see whether they produce the same rows using the EXCEPT construct:

SELECT prod_id FROM products ...

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.