I am trying to create pagination of records from a sql statement, I was able to get next and previous for all but the last record shows the previous record as next due to the sql query only returning 1 row instead of 2. I am setting next based on the first result and previous as the second result.
The data:
- Apple
- Banana
- Grape
- Orange
The sql:
select *
from (select top 1 fruit
FROM table
where fruit > 'Banana'
order by fruit asc) as x
UNION ALL
select *
from (select top 1 fruit
FROM table
where fruit < 'Banana' order by fruit desc) as y
The result:
fruit
--------
Grape
Apple
This works great!
For the first record – I get the correct result for the first record being the true next.
For the last record – I get one result which is the second query that gets the previous record. However I have no way of knowing its the last record so it outputs as Next instead of Previous.
How would I determine that is the last record and the single row being returned is actually the previous?
OR
How can I have the query return a NULL row for the Next query? So I can test against a NULL result?
BONUS POINTS!
How can I have one query that will give me first record, last record and next and previous so I could enable circular pagination? If on first record show last record as previous. If on last record show next record as first record?
Or, shorter, but I’m not sure that it would be more performant…
Or, as a final wierd option…
(This may be usefull if you have thousands+ of records, as each is search quickly and separately.)