I need to select min ID value from top 5 rows in the table. I get top IDs with this query:
SELECT id FROM items ORDER BY id DESC LIMIT 5
It works fine and returns ID values from top 5 rows:
314
313
312
311
310
Now, trying to get the minimal ID from this set:
SELECT MIN(id) FROM items ORDER BY id DESC LIMIT 5
I expect the result to be 310 but SQLite return 1.
What’s up with that? Where am I wrong and do I achieve my goal?
UPDATE:
SELECT MIN(id) FROM (SELECT id FROM news_items ORDER BY id DESC LIMIT 5) works, so now I’m just curious about what’s wrong with the first query.
Assuming that you are actually using
MINinstead ofMAX, then the explanation is very simple. TheORDER BY id DESC LIMIT 5is the last part that gets evaluated on your query. So, on your first query, you are retrieving the minimum value forid(it should be0), then theORDER BY ....is irrelevent (you are ordering and limiting just one row)