In the following example, LEFT JOIN 70% faster than EXCEPT (PostgreSQL 9.4.3)
Example:
There are three tables. suppliers , parts , shipments . We need to get all the parts that are not supplied by any supplier in London.
Database (has indexes for all involved columns):
CREATE TABLE suppliers ( id bigint primary key, city character varying NOT NULL ); CREATE TABLE parts ( id bigint primary key, name character varying NOT NULL, ); CREATE TABLE shipments ( id bigint primary key, supplier_id bigint NOT NULL, part_id bigint NOT NULL );
Number of records:
db=
Request using EXCEPT .
SELECT parts.* FROM parts EXCEPT SELECT parts.* FROM parts LEFT JOIN shipments ON (parts.id = shipments.part_id) LEFT JOIN suppliers ON (shipments.supplier_id = suppliers.id) WHERE suppliers.city = 'London' ;
A query using a LEFT JOIN with a table returned by a subquery.
SELECT parts.* FROM parts LEFT JOIN ( SELECT parts.id FROM parts LEFT JOIN shipments ON (parts.id = shipments.part_id) LEFT JOIN suppliers ON (shipments.supplier_id = suppliers.id) WHERE suppliers.city = 'London' ) AS subquery_tbl ON (parts.id = subquery_tbl.id) WHERE subquery_tbl.id IS NULL ;
vrybas
source share