Question

I'm trying to fetch the n-th row of a query result. Further posts suggested the use of OFFSET or LIMIT but those forbid the use of variables (ERROR: argument of OFFSET must not contain variables). Further I read about the usage of cursors but I'm not quite sure how to use them even after reading their PostgreSQL manpage. Any other suggestions or examples for how to use cursors?

My main goal is to calculate the p-quantile of a row and since PostgreSQL doesn't provide this function by default I have to write it on my own.

Cheers

Was it helpful?

Solution

The following returns the 5th row of a result set:

select *
from (
   select <column_list>,
          row_number() over (order by some_sort_column) as rn
) t
where rn = 5;

You have to include an order by because otherwise the concept of "5th row" doesn't make sense.

You mention "use of variable" so I'm not sure what you are actually trying to achive. But you should be able to supply the value 5 as a variable for this query (or even a sub-select).

You might also want to dig further into windowing functions. Because with that you could e.g. do a sum() over the 3 rows before the current row (or similar constructs) - which could also be useful for you.

OTHER TIPS

if you would like to get 10th record, below query also work fine.

 select * from table_name order by sort_column limit 1 offset 9

OFFSET simply skip that many rows before beginning to return rows as mentioned in LIMIT clause.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top