Select last n rows without use of order by clause

后端 未结 2 1224
春和景丽
春和景丽 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条回答
  •  日久生厌
    2021-01-13 07:26

    Use window functions!

    select t2.* from (
      select t1.*, row_number() over() as r, count(*) over() as c
      from (
        -- your generic select here
      ) t1
    ) t2
    where t2.r + :n > t2.c
    

    In the above example, t2.r is the row number of every row, t2.c is the total records in your generic select. And :n will be the n last rows that you want to fetch. This also works when you sort your generic select.

    EDIT: A bit less generic from my previous example:

    select * from (
      select my_table.*, row_number() over() as r, count(*) over() as c
      from my_table
      -- optionally, you could sort your select here
      -- order by my_table.a, my_table.b
    ) t
    where t.r + :n > t.c
    

提交回复
热议问题