Page 1 of 1

Fetching the last few rows from a table

PostPosted: Mon Mar 05, 2018 3:05 pm
by riya_kottoor
Hi,

Is there a way to fetch the last few rows from a table? Suppose i want last 5 rows. How can i do this?
If i do an order by descending and fetch first 5 rows, the order may differ from the actual order in which rows were inserted into the table.

Please suggest.

Re: Fetching the last few rows from a table

PostPosted: Mon Mar 05, 2018 4:26 pm
by NicC
Have you got anything to select on like a timestamp or sequence number?

Re: Fetching the last few rows from a table

PostPosted: Tue Mar 06, 2018 2:30 am
by prino
riya_kottoor wrote:Hi,

Is there a way to fetch the last few rows from a table? Suppose i want last 5 rows. How can i do this?
If i do an order by descending and fetch first 5 rows, the order may differ from the actual order in which rows were inserted into the table.

And what makes you thing that just fetching the last five rows will get them in the order they were inserted?

Sigh...

Re: Fetching the last few rows from a table

PostPosted: Tue Mar 06, 2018 3:06 am
by Robert Sample
Suppose i want last 5 rows. How can i do this?
Depending upon how the database is defined, what you want may not be possible. DB2 results are NOT necessarily returned in the order inserted into the database (with or without an ORDER BY clause); hence unless you have some form of sequence number or timestamp on each row, you CANNOT know what the 'last 5 rows" are -- period.

Re: Fetching the last few rows from a table

PostPosted: Tue Mar 06, 2018 11:34 am
by riya_kottoor
Okay. So fetch may return rows in jumbled order? Then how "FETCH FIRST n ROWS ONLY" works? we can't assure that the n rows which got fetched are the first n rows that got inserted to the table, right?

Re: Fetching the last few rows from a table

PostPosted: Tue Mar 06, 2018 12:25 pm
by enrico-sorichetti
the clause
FIRST n ROWS ONLY


will return the FIRST n ROWS according to the FETCH/READ LOGIC/RULES of DB2
and the logic/rule is that the without an ORDER clause the order in which the rows are fetched/read is UNPREDICTABLE

Re: Fetching the last few rows from a table

PostPosted: Tue Mar 06, 2018 2:35 pm
by riya_kottoor
thank you all for making the concept clear for me.