SQL – EXCEPT and INTERSECT clauses

Let´s say that you have two tables that you want to know what they have in common and what they have different.

You could query the two tables using the clause “EXISTS” and/or “NOT EXISTS” to retrieve the information you want.

– What exist in PROJECT_A and do not exist in PROJECT_B

– What exist in PROJECT_A and exists in PROJECT_B

– What exist in PROJECT_B and don´t exist in PROJECT_A

There´s a easier way to do that:

EXCEPT AND INTERSECT

EXCEPT

– What exist in PROJECT_A and do not exist in PROJECT_B

– What exist in PROJECT_B and don´t exist in PROJECT_A

INTERSECT

– What exist in PROJECT_A and exists in PROJECT_B

Note that in the example above, there´s no specification of columns, it´s possible only when the tables have the same structure. It works similarly to the clause UNION. Be sure that the two queries have the same number of columns with the same datatype on the SELECT CLAUSE.

The script for this solution is in the link below.

Leave a Reply