Subqueries and CTEs · Problem 59 of 118

Customers with Both Account Types

MediumSubqueries and CTEsBank data

Return the customer_id of every customer who owns at least one checking account and at least one savings account. Sort by customer_id.

Hint 1

Test each condition with its own EXISTS (SELECT 1 FROM accounts ...).

Reference solution

SELECT c.customer_id
FROM customers AS c
WHERE EXISTS (SELECT 1 FROM accounts AS a WHERE a.customer_id = c.customer_id AND a.account_type = 'checking')
  AND EXISTS (SELECT 1 FROM accounts AS a WHERE a.customer_id = c.customer_id AND a.account_type = 'savings')
ORDER BY c.customer_id;

Each EXISTS is a yes/no question about the current customer. Joining accounts once and filtering type = 'checking' AND type = 'savings' fails because one row has only one type. Questions like "has A and has B" need two looks at the child table: two EXISTS, two joins, or a GROUP BY ... HAVING COUNT(DISTINCT ...).

Another way. Group the accounts per customer and require both types.

SELECT customer_id
FROM accounts
GROUP BY customer_id
HAVING COUNT(DISTINCT account_type) = 2
ORDER BY customer_id;