Fazal
Fazal

Reputation: 3051

SQL Query to find missing rows between two related tables

I have two tables:

Table A

Table B

These two tables are directly related to each other through the ABC_ID column.

I want to find all the VAL column values in table A which are not present in table B for the same ABC_ID.

Upvotes: 60

Views: 196651

Answers (3)

8ctopus
8ctopus

Reputation: 3237

Another solution based on JOIN.
Join combines content from table A and table B using a link, the ON part of the request.

SELECT
    *
FROM
    A
INNER JOIN
    B
ON
    B.ABC_ID = A.ABC_ID
WHERE
    B.VAL <> A.VAL

Basically we are combining table A with table B on ABC_ID and then checking where A.VAL is not equal to B.VAL. The joined data with INNER JOIN only contains records where both table A and B have ABC_ID present ().

Upvotes: 0

suresh
suresh

Reputation: 1

DECLARE @start_date DATETIME= '04-01-2021'; DECLARE @End_date DATETIME= '04-30-2021'; declare @min int declare @max int select @min =min(test_uid), @max =max(test_uid) from test where DATE >= @START_DATE AND DATE < DATEADD(DAY, 1, @END_DATE)

select test_UID+1 as FirstMissingId, nextid - 1 as LastMissingId into #tmp from (select test.*,lead(test_UID) over (order by test_UID) as nextid from test where test_UID between @min and @max ) test where nextid <> test_UID+1 CREATE TABLE #tmp1 ( ID INT ) go
declare @lastmissingid BIGINT , @firstmissingid BIGINT declare recscan cursor for select firstmissingid ,lastmissingid from #tmp open recscan fetch next from recscan into @firstmissingid ,@lastmissingid while @@FETCH_STATUS = 0 begin declare @maxcnt int = @lastmissingid
declare @mincnt, int =@firstmissingid

WHILE @Counter <= @maxcnt
BEGIN INSERT #tmp1 values(@Counter) SET @Counter += 1 END fetch next from recscan into @firstmissingid ,@lastmissingid end close recscan deallocate recscan

Upvotes: -4

Larry Lustig
Larry Lustig

Reputation: 50970

SELECT A.ABC_ID, A.VAL FROM A WHERE NOT EXISTS 
   (SELECT * FROM B WHERE B.ABC_ID = A.ABC_ID AND B.VAL = A.VAL)

or

SELECT A.ABC_ID, A.VAL FROM A WHERE VAL NOT IN 
    (SELECT VAL FROM B WHERE B.ABC_ID = A.ABC_ID)

or

SELECT A.ABC_ID, A.VAL LEFT OUTER JOIN B 
    ON A.ABC_ID = B.ABC_ID AND A.VAL = B.VAL FROM A WHERE B.VAL IS NULL

Please note that these queries do not require that ABC_ID be in table B at all. I think that does what you want.

Upvotes: 102

Related Questions