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.
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.
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];
SELECT *
FROM B
WHERE NOT EXISTS (SELECT 1
FROM A
WHERE A.ID = B.ID)
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).
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
)
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