Return the name of customers who have at least one account and whose accounts are ALL active (not a single closed…
SQLLevel: IntermediateBonus drills (mixed difficulty)
Return the name of customers who have at least one account and whose accounts are ALL active (not a single closed one).
Table definitions (from the source exercise):
CREATE TABLE customers(customer_id INTEGER PRIMARY KEY, name TEXT, city TEXT, signup_date TEXT, credit_score INTEGER);
CREATE TABLE accounts(account_id INTEGER PRIMARY KEY, customer_id INTEGER, product_type TEXT, open_date TEXT, credit_limit INTEGER, status TEXT);
Hints
- Define one output row and the source-table keys.
- Check duplicates, NULLs and the order of filtering and aggregation.
Answer
Approach: Group by customer; the 'none closed' condition is SUM(CASE WHEN status 'active' THEN 1 ELSE 0 END) = 0 in HAVING.
SELECT c.name
FROM customers c
JOIN accounts a ON a.customer_id = c.customer_id
GROUP BY c.customer_id, c.name
HAVING SUM(CASE WHEN a.status <> 'active' THEN 1 ELSE 0 END) = 0;
The source uses SQLite with a MySQL compatibility layer. Date and string functions are dialect dependent; the query is preserved as published.
Source and licence: SQL Practice Lab — Ebrahim Sharifi · MIT