How to delete rows in a Teradata table that are not in another table?

Paul Hooper picture Paul Hooper · Dec 1, 2010 · Viewed 31.8k times · Source

What makes my situation tricky is that I don't have a single column key, with a simple list of primary keys to delete (for instance, "delete from table where key in ([list])"). I have multiple columns together as the primary key, and would need to join on all of them.

Using what I know of other databases, I thought this might be done as:

DELETE FROM
    table1 t1
  LEFT OUTER JOIN
      table2 t2
    ON
      t2.key1 = t1.key1 AND
      t2.key2 = t1.key2
  WHERE
    t2.key1 IS NULL;

But Teradata (v12) responds with error number 3706, saying "Syntax error: Joined Tables are not allowed in FROM clause."

Answer

Paul Hooper picture Paul Hooper · Dec 1, 2010

Found this is done by:

DELETE FROM
    table1
  WHERE
    (key1, key2) NOT IN (
      SELECT UNIQUE key1, key2 FROM table2
    );