It is a quirky but helpful feature that may come in handy when solutions like JOIN do not apply.
How It Works
Using the minus operator in SQL requires two select statements that return a similar number of records and similar data type as the result set.
The minus operator will then return unique records that exist in the first select statement but not the second.
The syntax of the minus operator in SQL is as shown:
The syntax above illustrates how to combine two select statements using the minus operator.
NOTE: In some databases, the MINUS operator is not supported—for example, SQL Server, PostgreSQL, and Google BigQuery. You can use the EXCEPT statement or LEFT OUTER join as an alternative.
Suppose we have two tables:
We can perform a minus operation on the tables as shown:
NOTE: The above example uses PostgreSQL. Replace the except with minus for supported databases.
The query above should return:
This article introduced the SQL minus operator and how it works. Consider the documentation to learn more.
Thanks for reading!!