Skip to content
Advertisement

SUBSELECT (SQL)

I have to tables. The first table (customers) shows data about the customers (id, firstname, lastname). The second table shows data about the orders (timestamp and customer id). So, i wanted to see the last order by a customer in my table “customers” and did a SUBSELECT and it worked.

But, there are some customers who never ordered something and so is no value in the column “last_order”. I am trying to filter these customers out with another SUBSELECT after the WHERE but i am failing. Can somebody help me?

Advertisement

Answer

The problem is with the second sub-query, it may return more than one value (one customer may have multiple orders); it should return only one value, so you may limit it by 1 as the following:

Another approach is to use Exists as the following:

Also, you can achieve the required result with a simple Join query as the following:

See a demo from db-fiddle.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement