Question

Using the following query,

SELECT * 
FROM   product 
WHERE  sale_price IN(SELECT max(sale_price)
                     FROM   product)

returns a row with a maximum value in the sale_price column of type DECIMAL(35,2) in the specified table product.


Can this query be rewritten using EXISTS() that can return the same result - a row from the product table with a maximum value in the sale_price column?

SELECT * 
FROM   product p 
WHERE  EXISTS(SELECT max(pp.sale_price) 
              FROM   product pp 
              WHERE  p.prod_id = pp.prod_id) 

Rewriting the query like this is incorrect and returns all rows from the given table based on the condition which matches every row in that table.

Était-ce utile?

La solution

You misunderstood the EXISTS operator: it returns TRUE for each row of product where the subquery returns at least one row (which your subquery does for every single row, because a MAX(...) will return something if there's at least one row).

To rewrite the query with EXISTS you need to check that there does not exist an item with a higher sale price, like this:

SELECT * 
FROM  product p 
WHERE NOT EXISTS (
    SELECT *
    FROM   product pp 
    WHERE  p.sale_price < pp.sale_price
)

The logic here is that if there does not exist a product pp with a higher sale_price, then p must be a product with the highest sale_price.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top