SQL | MINUS Operator
The Minus Operator in SQL is used with two SELECT statements. The MINUS operator is used to subtract the result set obtained by first SELECT query from the result set obtained by second SELECT query. In simple words, we can say that MINUS operator will return only those rows which are unique in only first SELECT query and not those rows which are common to both first and second SELECT queries.
As you can see is in the above diagram, the MINUS operator will return only those rows which are present in the result set from Table1 and not present in the result set of Table2.
SELECT column1 , column2 , ... columnN FROM table_name WHERE condition MINUS SELECT column1 , column2 , ... columnN FROM table_name WHERE condition; columnN: column1, column2.. are the name of columns of the table. Important Points:
- The WHERE clause is optional in the above query.
- The number of columns in both SELECT statements must be same.
- The data type of corresponding columns of both SELECT statement must be same.
SELECT NAME, AGE , GRADE FROM Table1 MINUS SELECT NAME, AGE, GRADE FROM Table2
The above query will return only those rows which are unique in ‘Table1’. We can clearly see that values in the fields NAME, AGE and GRADE for the last row in both tables are same. Therefore, the output will be the first three rows from Table1. The obtained output is shown below:
Note: The MINUS operator is not supported with all databases. It is supported by Oracle database but not SQL server or PostgreSQL.
This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Learn SQL for interviews using SQL Course by GeeksforGeeks.