Select last n rows without use of order by clause

后端 未结 2 1221
春和景丽
春和景丽 2021-01-13 07:15

I want to fetch the last n rows from a table in a Postgres database. I don\'t want to use an ORDER BY clause as I want to have a generic query. Anyone has any s

2条回答
  •  萌比男神i
    2021-01-13 07:47

    That you get what you expect with Lukas' solution (as of Nov. 1st, 2011) is pure luck. There is no "natural order" in an RDBMS by definition. You depend on implementation details that could change with a new release without notice. Or a dump / restore could change that order. It can even change out of the blue when db statistics change and the query planner chooses a different plan that leads to a different order of rows.

    The proper way to get the "last n" rows is to have a timestamp or sequence column and ORDER BY that column. Every RDBMS you can think of has ORDER BY, so this is as 'generic' as it gets.

    I quote the manual here:

    If ORDER BY is not given, the rows are returned in whatever order the system finds fastest to produce.

    Lukas' solution is fine to avoid LIMIT, which is implemented differently in various RDBMS (for instance, SQL Server uses TOP n instead of LIMIT), but you need to ORDER BY in any case.

    It may be worth mentioning that while window functions are in the SQL standard, they still aren't as generic as you might wish. MySQL, for instance, does not support them.

提交回复
热议问题