YogeshChauhan . com

INTERSECT and EXCEPT in Postgres

in Postgres on July 4, 2020

INTERSECT and EXCEPT, both of them returns distinct rows by comparing the results of two queries.

EXCEPT returns distinct rows from the left input query that aren’t output by the right input query.

INTERSECT returns distinct rows that are output by both the left and right input queries operator.

The basic rules to use EXCEPT and INTERSECT are:

The number and the order of the columns must be the same in all queries.

The data types must be compatible.

INTERSECT

Syntax:


SELECT column(s) FROM table1
INTERSECT
SELECT column(s) FROM table2;

INTERSECT operator example

I am using the database for all examples. It is available on my Github public repo

This query gives us all the customer_id which has placed an order after opening an account.


SELECT customer_id
FROM customers
INTERSECT
SELECT customer_id
FROM orders;

//Output
customer_id
"TOMSP"
"LONEP"
"OLDWO"
...
...
89 rows

EXCEPT

Syntax:


SELECT column(s) FROM table1
EXCEPT
SELECT column(s) FROM table2;

EXCEPT operator example

This query gives us the customer_id who has opened an account but never placed an order.


SELECT customer_id
FROM customers
EXCEPT
SELECT customer_id
FROM orders;

//Output
customer_id
"FISSA"
"PARIS"
amazon

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

How to position an image on top of another image using CSS?CSS:in-range and :out-of-range selector in CSSCSSWHERE Clause in PostgresPostgresHow to get the first element with a class name xyz using JavaScript?JavaScriptHow to import MySQL small sample database into phpMySQL?SQL/MySQLHTML canvas methodsHTML