Subqueries in a DELETE Statement - Teradata Database

SQL Data Manipulation Language

Product
Teradata Database
Release Number
15.10
Language
English (United States)
Last Update
2018-10-06
dita:id
B035-1146
lifecycle
previous
Product Category
Teradata® Database

Subqueries in a DELETE Statement

DELETE statement predicates can include subqueries that reference the delete target table, as well as other tables. The following DELETE statement is an example:

     DELETE FROM publisher 
     WHERE 0 = (SELECT COUNT(*)
                FROM book 
                WHERE book.pub_num=publisher.pub_num);

Two publishers have books in the library and two publishers do not.

The subquery executes once for each row of the outer reference, the publisher table. Because two publishers have no books in the library, the two rows that represent those publishers are deleted from the publisher table.

To modify this DELETE to use a noncorrelated subquery, change the subquery code to include all tables it references in its FROM clause.

     DELETE FROM publisher 
     WHERE 0 = (SELECT COUNT(*)
                FROM book, publisher
                WHERE book.pub_num=publisher.pub_num);

When coded this way, the subquery predicate has a local defining reference, so the DELETE statement does not contain a correlated subquery. The count, determined once, is nonzero, so no rows are deleted.