MediumSQL
Customers With at Least One Order
SQLDatabases
Write a SQL query that returns the names of all customers who have placed
at least one order, ordered alphabetically.
Tables
customers: id, nameorders: id, customer_id, amount
| customers | orders | |||
|---|---|---|---|---|
| id | name | id | customer_id | amount |
| 1 | Alice | 1 | 1 | 150 |
| 2 | Bob | 2 | 1 | 200 |
| 3 | Carol | 3 | 3 | 75 |
| 4 | Dave |
Bob and Dave have no orders → excluded.
Expected output (column: name)
Alice
Carol
EXISTS (subquery)returns TRUE if the subquery yields any row.It stops scanning as soon as one match is found — efficient for large tables.
Sample tests
Test #1Alice has 2 orders, Carol has 1, Bob and Dave have none
Input: "CREATE TABLE customers (id INTEGER, name TEXT);\nCREATE TABLE orders (id INTEGER, customer_id INTEGER, amount INTEGER);\nINSERT INTO customers VALUES (1, 'Alice'), (2, 'Bob'), (3, 'Carol'), (4, 'Dave');\nINSERT INTO orders VALUES (1, 1, 150), (2, 1, 200), (3, 3, 75);"
Output: "Alice\nCarol"