Quote:
|
Originally Posted by db2user
What's a faster method for retrieving the last timestamp in a table that has thousands of records? Using the MAX function or LIMIT 1? Or does it not matter?
SELECT * from tblname where id = 1234 ORDER BY datetime desc LIMIT 1
OR
SELECT MAX(datetime) from tblname where id = 1234
|
First of all, for a fair comparison, you should either replace "*" by "datetime" in the first query, or alternatively move the second query into a subquery:
Code:
SELECT datetime FROM tbl WHERE ... ORDER BY datetime DESC FETCH FIRST ROW ONLY
versus
SELECT MAX(datetime) FROM tbl WHERE ...
or else
Code:
SELECT * FROM tbl WHERE ... ORDER BY datetime DESC FETCH FIRST ROW ONLY
versus
SELECT * FROM tbl WHERE datetime = (SELECT MAX(datetime) FROM tbl WHERE ...)
The elements of the two pairs may even return different results, e.g. when several rows have the same timestamp.
When no index exists on the datetime column, the two queries of the first interpretation will have exactly the same access path (viz. a table scan followed by a sorting).
For the two last queries the second one will only have to sort the datetime column (like in the first two queries) but then re-access the table to get all matching rows. I.e.: two table scans.
So it would need twice the I/O for the tablespace as compare to the third query, but that one will need more I/O (and CPU) during the sorting since it will have to sort the full table.
Hence, the answer to the question "which is better" also depends on the sizes of the other columns in the table!
When an index exists with datetime as its first column, access paths for the two variants for each interpretation will be identical (as Knut Stolze already pointed out).