In SQL, how can I perform a "subtraction" operation?
Asked Answered
I

7

5

Suppose I have two tables, which both have user ids. I want to perform an operation that would return all user IDS in table 1 that are not in table 2. I know there has to be some easy way to do this - can anyone offer some assistance?

Inspection answered 31/1, 2011 at 23:54 Comment(1)
What database platform are you using?Lamonicalamont
O
6

Its slow, but you can normally accomplish this with something like 'not in'. (There are other functions in various RDBMS systems to do this in better ways, Oracle for instance has a 'exists' clause that can be used for this.

But you could say:

select id from table1 where id not in (select id from table2)
Orfield answered 31/1, 2011 at 23:56 Comment(0)
W
6

There are a few ways to do it. Here's one approach using NOT EXISTS:

SELECT userid
FROM table1
WHERE NOT EXISTS
(
    SELECT *
    FROM table2
    WHERE table1.userid = table2.userid
)

And here's another approach using a join:

SELECT table1.userid
FROM table1
LEFT JOIN table2
ON table1.userid = table2.userid
WHERE table2.userid IS NULL

The fastest approach depends on the database.

Wrench answered 31/1, 2011 at 23:57 Comment(0)
D
2

One way is to use EXCEPT if your TSQL dialect supports it. It is equivalent to performing a left join and null test

Deyo answered 31/1, 2011 at 23:58 Comment(0)
S
2
SELECT user_id FROM table1 LEFT JOIN table2 ON table1.user_id = table2.user_id WHERE table2.user_id IS NULL;
Spiro answered 31/1, 2011 at 23:58 Comment(0)
T
1

If it is SQL Server:

SELECT id FROM table1
EXCEPT 
SELECT id FROM table2

Oracle:

SELECT id FROM table1
MINUS
SELECT id FROM table2

Rest: Am not sure....

Tuberous answered 1/2, 2011 at 0:0 Comment(0)
F
0

Try this:

SELECT id FROM table1 WHERE id NOT IN
(
    SELECT id FROM table2
)
Forint answered 31/1, 2011 at 23:57 Comment(0)
F
0
select ID from table1
where ID not in (select ID from table2)
Fu answered 31/1, 2011 at 23:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.