3

So, i have two tables, the target table and the source one. I need to delete the rows that exists in the target table, but doesn't exists in the source table.

And the code:

MERGE INTO (SELECT id_car_bk, car_brand_bk, car_type_bk, new_car
              FROM car_catalog_backup) CB
USING (SELECT id_car, car_brand, car_type FROM car_catalog) C
ON (CB.id_car_bk = b.id_car)
WHEN NOT MATCHED THEN
  INSERT
    (CB.id_car_bk, CB.car_brand_bk, CB.car_type_bk)
  VALUES
    (C.id_car, C.car_brand, C.car_type)
WHEN MATCHED THEN
  UPDATE SET CB.car_brand_bk = C.car_brand;
Barbaros Özhan
  • 59,113
  • 10
  • 31
  • 55
Andrei GH
  • 53
  • 1
  • 5

3 Answers3

1

You can use

DELETE car_catalog_backup b 
 WHERE not exists 
        ( SELECT 0
            FROM car_catalog c 
           WHERE b.id_car_bk = c.id_car );

or

DELETE car_catalog_backup b 
 WHERE b.id_car_bk not in 
        ( SELECT c.id_car
            FROM car_catalog c );

assuming car_catalog is the source, and car_catalog_backup is the target. The First one is preferable, since it's more performant.

If your aim is to find out with a MERGE statement similar to your case, then use the following

MERGE INTO car_catalog_backup a
USING (SELECT id_car, car_brand, car_type, car_brand_bk 
         FROM car_catalog
         JOIN car_catalog_backup
           ON id_car_bk = id_car
         ) b
   ON (a.id_car_bk = b.id_car)
 WHEN MATCHED THEN
   UPDATE SET a.new_car = 1
   DELETE
   WHERE a.car_brand_bk != b.car_brand 
 WHEN NOT MATCHED THEN
   INSERT
    (id_car_bk, car_brand_bk, car_type_bk)
   VALUES
    (b.id_car, b.car_brand, b.car_type)

to delete the records matched for id columns ( a.id_car_bk = b.id_car ) but not matched for brand code columns ( a.car_brand_bk != car_brand ) as an example.

Demo

Barbaros Özhan
  • 59,113
  • 10
  • 31
  • 55
0
Delete from target
Where not exists 
( 
    Select 1
    From source 
    Where join of source and target
)
Saad Ahmad
  • 393
  • 1
  • 7
0

With a left join:

DELETE target 
FROM target LEFT JOIN source 
ON target.someid = source.otherid 
WHERE source.otherid IS NULL;
forpas
  • 160,666
  • 10
  • 38
  • 76