Which query structure returns rows from customers where the id appears in the customer_id column of orders?

Study for the SQL Basics Test. Improve your knowledge with multiple choice questions and detailed explanations. Prepare effectively to master SQL concepts!

Multiple Choice

Which query structure returns rows from customers where the id appears in the customer_id column of orders?

Explanation:
The key idea here is filtering by membership in a set produced by another query. You want customers whose id appears in the customer_id column of orders, so you test whether a customer’s id is in the list returned by querying orders. Using an IN with a subquery does exactly that: it builds the set of all customer_ids from orders and selects the customers whose id is contained in that set. For example: SELECT c.* FROM customers c WHERE c.id IN (SELECT o.customer_id FROM orders o); This is clear and directly expresses the requirement. With proper indexing on orders.customer_id, it’s typically efficient because the database can quickly check membership. An EXISTS with a subquery would also yield the same result by checking for the existence of at least one matching order for each customer, and it can be effective, especially if the subquery is large and the engine optimizes the lookup. A LEFT JOIN with a NULL check would be more awkward here because it either risks duplicates (without DISTINCT) or adds extra steps to deduplicate, and it’s more work than necessary. A CROSS JOIN would blow up the number of rows dramatically and isn’t suitable for this purpose.

The key idea here is filtering by membership in a set produced by another query. You want customers whose id appears in the customer_id column of orders, so you test whether a customer’s id is in the list returned by querying orders.

Using an IN with a subquery does exactly that: it builds the set of all customer_ids from orders and selects the customers whose id is contained in that set. For example:

SELECT c.* FROM customers c WHERE c.id IN (SELECT o.customer_id FROM orders o);

This is clear and directly expresses the requirement. With proper indexing on orders.customer_id, it’s typically efficient because the database can quickly check membership.

An EXISTS with a subquery would also yield the same result by checking for the existence of at least one matching order for each customer, and it can be effective, especially if the subquery is large and the engine optimizes the lookup.

A LEFT JOIN with a NULL check would be more awkward here because it either risks duplicates (without DISTINCT) or adds extra steps to deduplicate, and it’s more work than necessary. A CROSS JOIN would blow up the number of rows dramatically and isn’t suitable for this purpose.

Subscribe

Get the latest from Passetra

You can unsubscribe at any time. Read our privacy policy