I found this example on the MySQL Tutorial:
SELECT article, dealer, price
FROM shop
WHERE price=(SELECT MAX(price) FROM shop);
My question: is the subquery (SELECT MAX(price) FROM shop) done once a time, or it is done repeatedly until the max price for the query is found?
In terms of performance is this other solution better?
SELECT s1.article, s1.dealer, s1.price
FROM shop s1
LEFT JOIN shop s2 ON s1.price < s2.price
WHERE s2.article IS NULL;
Thanks.
The sub query is non correlated so any sensible implementation will only evaluate it once. Note that MySQL does have a problem with
INthough where the semantically equivalentLeads to the sub query being evaluated multiple times.
As far as evaluating performance you would need to look at the
explain planfor both in your particular RDBMS.The most efficient solution might be to use
SELECT TOP .. WITH TIESor equivalent if you have a covering index on thepricecolumn and your RDBMS has such a construct.