Select a row field with a minimum value of another column using sub query and aggregate function

StackOverflow https://stackoverflow.com/questions/21365922

  •  03-10-2022
  •  | 
  •  

Question

Attempting to complete exercises from the following link for the northwind example database in MySQL.

http://laerer.rhs.dk/andersb/basicprog/database/exercises/northwindselect.htm

The Question "Using SUBQUERY...find the minimum unitPrice from the table products. Use this price to find productID and productName for the product(s) which has the minimal price." has me a little confused.

The following Query

    SELECT ProductID, ProductName 
    FROM products 
    ORDER BY UnitPrice
    LIMIT 1;

seems to produce the correct answer but doesn't use a SUB QUERY. Is this standard practice to produce fields from a row having a MIN/MAX value from another column? I.e. without using the aggregate functions MIN()/MAX().

I would guess that this method would be computationally expensive; having the DBMS sort the table before printing just the top row. Would a SUB QUERY or any other method be more efficient? Perhaps using the appropriate aggregate function rather than ORDER BY. If so, what query should I use?

Was it helpful?

Solution

Your method finds one product with the minimum price. If there are more than one, then you are missing them.

So, the more general solution is to use something a lot like your query as a subquery:

select p.*
from products p join
     (SELECT UnitPrice
      FROM products 
      ORDER BY UnitPrice
      LIMIT 1
     ) pmin
     on p.UnitPrice = pmin.UnitPrice;

Actually, the subquery would more commonly be written:

     (SELECT min(UnitPrice)
      FROM products 
     ) pmin

Both produce the same answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top