Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL: Comparing Two Tables - Records that don't exist in second table

If UNION ALL is an addition in T-SQL. What is the equivalent of subtraction?

For example, if I have a table PEOPLE and a table EMPLOYEES. And I know if I remove EMPLOYEES records from PEOPLE I will be left with my companies CONTRACTORS.

Is there a way of doing this that is similar to UNION ALL? One where I don't have to specify any field names? The reason I ask is this is just one hypothetical example. I need to do this several times to many different tables. Assume that the schema of EMPLOYEES and PEOPLE are the same.

like image 955
BuddyJoe Avatar asked Dec 16 '08 18:12

BuddyJoe


People also ask

How do you find records which are not present in another table?

We can get the records in one table that doesn't exist in another table by using NOT IN or NOT EXISTS with the subqueries including the other table in the subqueries.

How do you select all records from one table that do not exist in another table Excel?

select [ selecting columns] From table1 Right OUTER JOIN table2 ON(table1. SQL> select e. select [ selecting columns] From table1 Right OUTER JOIN table2 ON(table1. select column_name from table 1 full outer join table 2 on(connection); here all the data from table 1 and table 2 will get retrieved.


2 Answers

You can use the EXCEPT operator to subtract one set from another. Here's a sample of code using EMPLOYEES and PEOPLE temporary tables. You'll need to use the field names with the EXCEPT operator as far as I know.

CREATE TABLE #PEOPLE
(ID INTEGER,
 Name NVARCHAR(50))

CREATE TABLE #EMPLOYEE
(ID INTEGER,
 Name NVARCHAR(50))
GO

INSERT #PEOPLE VALUES (1, 'Bob')
INSERT #PEOPLE VALUES (2, 'Steve')
INSERT #PEOPLE VALUES (3, 'Jim')
INSERT #EMPLOYEE VALUES (1, 'Bob')
GO

SELECT ID, Name
FROM #PEOPLE
EXCEPT 
SELECT ID, Name
FROM #EMPLOYEE
GO

The final query will return the two rows in the PEOPLE table which do not exist in the EMPLOYEE table.

like image 128
Eric Ness Avatar answered Sep 19 '22 12:09

Eric Ness


Instead of using UNION, use EXCEPT, ( or INTERSECT to get only records in both ) as described in

msdn EXCEPT Link for Sql2k8

msdn EXCEPT Link for Sql2k5

like image 41
Charles Bretana Avatar answered Sep 22 '22 12:09

Charles Bretana