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, name
orders: id, customer_id, amount

customersorders
idnameidcustomer_idamount
1Alice11150
2Bob21200
3Carol3375
4Dave

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"