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.

Was it helpful?

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.

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