I have two tables
Table A:
ID 1 2 3 4
Table B:
ID 1 2 3
I have two requests:
I am using SQL Server 2000.
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.
Users select e). ToList(); var result2 = (from e in db.Fi select e). ToList(); List<string> listString = (from e in result1 where !( from m in result2 select m.
You could use NOT IN
:
SELECT A.* FROM A WHERE ID NOT IN(SELECT ID FROM B)
However, meanwhile i prefer NOT EXISTS
:
SELECT A.* FROM A WHERE NOT EXISTS(SELECT 1 FROM B WHERE B.ID=A.ID)
There are other options as well, this article explains all advantages and disadvantages very well:
Should I use NOT IN, OUTER APPLY, LEFT OUTER JOIN, EXCEPT, or NOT EXISTS?
For your first question there are at least three common methods to choose from:
The SQL looks like this:
SELECT * FROM TableA WHERE NOT EXISTS ( SELECT NULL FROM TableB WHERE TableB.ID = TableA.ID ) SELECT * FROM TableA WHERE ID NOT IN ( SELECT ID FROM TableB ) SELECT TableA.* FROM TableA LEFT JOIN TableB ON TableA.ID = TableB.ID WHERE TableB.ID IS NULL
Depending on which database you are using, the performance of each can vary. For SQL Server (not nullable columns):
NOT EXISTS and NOT IN predicates are the best way to search for missing values, as long as both columns in question are NOT NULL.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With