How do you check if a customer has any orders using EXISTS?

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

Multiple Choice

How do you check if a customer has any orders using EXISTS?

Explanation:
Using EXISTS to check for related rows for each customer. In this query, for every customer c, the inner query searches orders for a row where the customer_id matches c.id. EXISTS returns true as soon as it finds any such row and false if there isn’t one, so the outer query returns only those customers who have at least one order. The inner subquery is correlated to the outer row because it references c.id. SELECT 1 is common here since the actual value isn’t important—the existence of a matching row is what matters. The other patterns don’t fit the same per-customer intention: adding AND 1=0 would make the condition always false and yield no results. Using a COUNT(*) > 0 would work to check for orders but uses a different construct rather than EXISTS. An uncorrelated EXISTS (without referencing the outer table) would just check if any order exists at all, not specifically for each customer.

Using EXISTS to check for related rows for each customer. In this query, for every customer c, the inner query searches orders for a row where the customer_id matches c.id. EXISTS returns true as soon as it finds any such row and false if there isn’t one, so the outer query returns only those customers who have at least one order. The inner subquery is correlated to the outer row because it references c.id. SELECT 1 is common here since the actual value isn’t important—the existence of a matching row is what matters.

The other patterns don’t fit the same per-customer intention: adding AND 1=0 would make the condition always false and yield no results. Using a COUNT(*) > 0 would work to check for orders but uses a different construct rather than EXISTS. An uncorrelated EXISTS (without referencing the outer table) would just check if any order exists at all, not specifically for each customer.

Subscribe

Get the latest from Passetra

You can unsubscribe at any time. Read our privacy policy