Yogesh Chauhan's Blog

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"

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 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
SQL ALL OperatorSQL/MySQLthe box-sizing property in CSSCSSGlobal JavaScript methods to convert variables to numbersJavaScriptQuery to increment or decrement value in MySQL ignoring negative valuesSQL/MySQLAggregate Functions Examples in Postgres for BeginnersPostgresHow to set default timezone using PHP?PHP