I’m trying to figure out which is the more efficient way to get the nth highest record in a mySQL database:
SELECT * FROM table_name ORDER BY column_name DESC LIMIT n - 1, 1
or
SELECT * FROM table_name AS a WHERE n - 1 = ( SELECT COUNT(primary_key_column) FROM products b WHERE b.column_name > a. column_name)
There is an index on column_name.
I would think mySQL would efficiently perform the limit clause and the first option is the way to go.
I wasn’t too clear what the 2nd query does exactly, so if that is more efficient can someone explain why.
Thanks.
I tried EXPLAIN on both those queries on a database of mine (note: the optimizer may choose different plans for your schema/data) and it definitely looks like the first one wins in every regard: it’s simpler to read and understand, and will most likely be faster.
As aaronls said, and EXPLAIN confirms, the second query has a correlated subquery which will require an extra iteration through the entire table for each row.
Since the first one is way easier to read, I’d choose it in a shot. If you do find that it’s a bottleneck (after profiling your application), you could give the second a try but I don’t see how it could possibly be faster.