Database Basics

From a customer table (cust_id, name) and an orders table (order_id, cust_id, amount), you want the names of customers who have never placed an order. Which SQL statement is correct?

  1. ASELECT name FROM customer WHERE EXISTS (SELECT * FROM orders WHERE orders.cust_id = customer.cust_id)
  2. BSELECT name FROM customer WHERE NOT EXISTS (SELECT * FROM orders)
  3. CSELECT name FROM customer WHERE NOT EXISTS (SELECT * FROM orders WHERE orders.cust_id = customer.cust_id)
Show answer and explanation

Answer: C. SELECT name FROM customer WHERE NOT EXISTS (SELECT * FROM orders WHERE orders.cust_id = customer.cust_id)

EXISTS is a predicate that is true if the subquery in parentheses returns at least one row and false if it returns none; NOT EXISTS is the opposite. Using a column of the outer table inside the subquery, as in orders.cust_id = customer.cust_id, makes it a correlated subquery that checks, for each row of the outer customer table, whether that customer has any orders. Combined with NOT EXISTS, only customers with no orders at all remain. With EXISTS, you get the opposite: customers who have ordered. Without a condition linking the subquery to the customer, the subquery always returns rows as long as the orders table has at least one row, so NOT EXISTS is always false and the result is zero rows. The same result can also be obtained with a LEFT OUTER JOIN, selecting the rows where the orders-side columns are NULL.

  • A. This uses EXISTS, so it finds customers who have placed orders.
  • B. The subquery has no per-customer condition, so if the orders table has even one row, the result is zero rows.
  • C. Correct. It checks for each customer whether any orders exist and keeps only customers with none.
Practice this topic Back to topic

Related calculators

Books on Database Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More Database Basics questions

  1. Which correctly describes a database view in a relational database?
  2. What is the main purpose of normalization of tables in a relational database?
  3. The primary key of an order table (order_no, item_no, qty, cust_no, cust_name) is {order_no, item_no}, and its functional dependencies are {order_no, item_no} → qty, order_no → cust_no and cust_no → cust_name. Which is the correct result of normalizing this table up to third normal form (3NF)?
  4. The primary key of an employee table (emp_no, name, dept_code, dept_name) is emp_no, and every column holds a single value. The functional dependencies are emp_no → name, emp_no → dept_code and dept_code → dept_name. Which correctly states the normal form of this table?
  5. In a database used mainly for reading and aggregation, normalized tables are sometimes deliberately merged into one so that the same data is held in duplicate (denormalization). Which correctly pairs an advantage and a disadvantage of this design?