Suppose that a website contains two tables, the Customers
table and the Orders
table. Write a SQL query to find all customers who never order anything.
Table: Customers
.
+----+-------+ | Id | Name | +----+-------+ | 1 | Joe | | 2 | Henry | | 3 | Sam | | 4 | Max | +----+-------+
Table: Orders
.
+----+------------+ | Id | CustomerId | +----+------------+ | 1 | 3 | | 2 | 1 | +----+------------+
Using the above tables as example, return the following:
+-----------+ | Customers | +-----------+ | Henry | | Max | +-----------+
NOT IN
clause [Accepted]Algorithm
\nIf we have a list of customers who have ever ordered, it will be easy to know who never ordered.
\nWe can use the following code to get such list.
\nselect customerid from orders;\n
Then, we can use NOT IN
to query the customers who are not in this list.
MySQL
\nselect customers.name as \'Customers\'\nfrom customers\nwhere customers.id not in\n(\n select customerid from orders\n);\n