3
votes

What would be the most efficient and elegant way to select MAX value from transparent table? For example, let's try to select such simple table as T100, Messages. Let us imagine we should select maximum message number within some application area. We can do this in a multiple ways.
The most obvious is using MAX aggregate function

select MAX(msgnr)
from t100
where arbgb = '/ASU/GENERAL'

And the other is using UP TO 1 ROWS clause

select msgnr
from t100
where arbgb = '/ASU/GENERAL'
and ROWNUM = 1
order by msgnr DESC

Herein above, all SQL statements are given in a native Oracle SQL, as I was doing tests in DBACOCKPIT where this is mandatory.

Built-in cockpit tool showed almost identical results for both requests:

  • estimated costs is 3 for both of them, however, second query has only 2 steps in plan whereas the first has 3.
  • estimated CPU costs for the first query is 21.564 per step, however second has total cost of 21.964.

So we can conclude that second variant is more efficient here.
However, would this be a point in a common case? Would this result be different on different DBs or we can treat it as a rule of thumb?

1

1 Answers

4
votes

Performance measurements always vary depending on a rather large set of parameters, the DBMS being not the least of them. Some DBMS might, for example, be able to use an index to efficiently determine a MAX(...) statement while others might have to resort to some more inefficient form. Also, don't trust the optimizer's predictions - measure the real performance. The optimizer might be wrong for a number of reasons (outdated statistics and broken indexes being the most common ones as far as I have seen), and it's of little help if the optimizer estimates a total cost of 12.345 if the actual cost turns out to be 987.654. Hence, my recommendations would be

  • select only what you need (avoid SELECT *, use WHERE sensibly)
  • measure, measure, measure
  • be wary of most of the unproven and alleged performance rules-of-thumb out there.