SELECT model, price FROM ( (SELECT model, price FROM pc ORDER BY price DESC LIMIT 1) UNION ALL (SELECT model, price FROM laptop ORDER BY price DESC LIMIT 1) UNION ALL (SELECT model, price FROM printer ORDER BY price DESC LIMIT 1) ) AS subquery_name_required ORDER BY price DESC LIMIT 1;
If the price field is indexed (which should be for such a request), ORDER / LIMIT (or the equivalent TOP) will work very quickly, since DB resets the highest price from the table.
Note. In a database that supports table inheritance (or can be locked to support something similar using discriminator columns), refactoring shared columns into a single table can say a lot about this! Imagine if you start selling scanners, monitors, SSDs, etc. What a nightmare!
[EDIT to show links]
SELECT model, price FROM ( SELECT model, price FROM (SELECT model, price, rank() OVER (ORDER BY price DESC) AS r FROM pc) AS s1 WHERE r=1 UNION ALL SELECT model, price FROM (SELECT model, price, rank() OVER (ORDER BY price DESC) AS r FROM laptop) AS s2 WHERE r=1 UNION ALL SELECT model, price FROM (SELECT model, price, rank() OVER (ORDER BY price DESC) AS r FROM printer) AS s3 WHERE r=1 ) AS subquery_name_required ORDER BY price DESC LIMIT 1;
I do not have enough experience in this type of windows to find out whether the index on price will be checked as much as necessary. I hope so. It is clear that this should not be more complicated than LIMIT 1 , you just have to admit that this is a more complex, but similar request.
source share