Sample Exam Questions

From the objective of OSS-DB Exam Silver
S3.1 SQL commands (DELETE statement)

Sample Question

3.01

The primary key column of table xxx is an integer type id, and the primary key column of table yyy is also an integer type id.

If both xxx and yyy have rows with the same id, you want to delete all those rows from xxx.
For example, if 'select id from xxx' returns 1, 2, and 3, and 'select id from yyy' returns 2, 3, and 4, you want to delete the rows with id 2 and 3 from xxx. Which SQL statement accomplishes this?

  1. DELETE FROM xxx, yyy WHERE xxx.id = yyy.id;
  2. DELETE FROM xxx, yyy WHERE xxx.id IN (yyy.id);
  3. DELETE FROM xxx JOIN yyy USING xxx.id = yyy.id;
  4. DELETE FROM xxx WHERE id IN (SELECT id FROM yyy);
  5. DELETE FROM xxx WHERE EXISTS (SELECT id FROM yyy); 

※This sample exam is different from those that appear in the actual OSS-DB Exam.
2024/05/01

Answer and Explanation

The basic form of the DELETE statement is:
DELETE FROM table_name WHERE condition
Only rows that meet the condition in the WHERE clause are deleted. However, if the WHERE clause is omitted, all rows are deleted, so be careful.
There are often cases where you want to refer to other tables to determine the rows to be deleted. In such cases, the condition is usually described in the WHERE clause.
Unlike the SELECT statement, you cannot list multiple tables in the FROM clause just because you want to refer to other tables. Options A and B result in syntax errors because they have multiple tables in the FROM clause. If such a description were allowed, it would be unclear which table to delete rows from. Also, you cannot perform table joins using JOIN as in option C.
When referring to other tables in the WHERE clause, IN and EXISTS are often used.
IN is specified in the format:
column_name IN (value list)
If you write a SELECT statement that selects only one column as the value list, the values returned there will be expanded into a list. In other words, the WHERE clause in option D is expanded and executed as
WHERE id IN (2, 3, 4)
This is a correct option that gives the expected result.
Option E can be executed without a syntax error, but the id column of table xxx is not referenced. Therefore, for any row in xxx, the part
EXISTS (SELECT id FROM yyy)
is true, and all rows of table xxx are deleted. You can get the expected result if you write it as
EXISTS (SELECT * FROM yyy WHERE xxx.id = yyy.id)

Therefore, the correct answer is D.

Note that in PostgreSQL's DELETE statement, you can specify the reference table in the USING clause and join tables. For example, you can get the expected result by writing
DELETE FROM xxx USING yyy WHERE xxx.id = yyy.id;