Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql: check if entry in table A exists in table B

Tags:

sql

exists

I have a definition table that I know is not being maintained very well, let's call this table A. I have another table (call it table B) that is much smaller and ideally should be a subset of table A but I know that table A is somewhat stale and does not contain new entries that are in Table B.

Note, that tables A and B have different columns.

Table A:
ID, Name, blah, blah, blah, blah

Table B:
ID, Name

I want all rows in Table B such that the ID in Table B does NOT exist in Table A. This does not just match rows in Table A; I want only rows in Table B where the ID does NOT exist at all in Table A.

like image 529
codingknob Avatar asked Apr 10 '13 23:04

codingknob


People also ask

How do you check if an entry exists in a table?

To test whether a row exists in a MySQL table or not, use exists condition. The exists condition can be used with subquery. It returns true when row exists in the table, otherwise false is returned. True is represented in the form of 1 and false is represented as 0.

How do you check if a column exists in another table SQL?

Colum view to check the existence of column Name in table SampleTable. IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA. COLUMNS WHERE table_name = 'SampleTable' AND column_name = 'Name' ) SELECT 'Column exists in table' AS [Status] ; ELSE SELECT 'Column does not exist in table' AS [Status];


3 Answers

SELECT *
FROM   B
WHERE  NOT EXISTS (SELECT 1 
                   FROM   A 
                   WHERE  A.ID = B.ID)
like image 130
gdoron is supporting Monica Avatar answered Oct 08 '22 11:10

gdoron is supporting Monica


The classical answer that works in almost every environment is

SELECT ID, Name, blah, blah
FROM TableB TB
LEFT JOIN TableA TA
ON TB.ID=TA.ID
WHERE TA.ID IS NULL

sometimes NOT EXISTS may be not implemented (not working).

like image 31
Danylo Zherebetskyy Avatar answered Oct 08 '22 12:10

Danylo Zherebetskyy


If you are set on using EXISTS you can use the below in SQL Server:

SELECT * FROM TableB as b
WHERE NOT EXISTS
(
   SELECT * FROM TableA as a
   WHERE b.id = a.id
)
like image 14
Abe Miessler Avatar answered Oct 08 '22 11:10

Abe Miessler