views:

719

answers:

7

I know:
Firebird FIRST and SKIP;
MySql LIMIT;
Sql Server ROWNUMBER();

Does someone knows a SQL ANSI way to perform result paging?

A: 

Insert your results into a storage table, ordered how you'd like to display them, but with a new IDENTITY column.

Now SELECT from that table just the range of IDs you're interested in.

(Be sure to clean out the table when you're done)


Or do it on the client, as anything to do with presentation should not normally be done on the SQL Server (in my opinion)

Dems
A: 

I would check out the answers to this question - likely to get you started.

Isaac Dealey
A: 

No official way, no.*

Generally you'll want to have an abstracted-out function in your database access layer that will cope with it for you; give it a hint that you're on MySQL or PostgreSQL and it can add a 'LIMIT' clause to your query, or rownum over a subquery for Oracle and so on. If it doesn't know it can do any of those, fall back to fetching the lot and returning only a slice of the full list.

*: eta: there is now, in ANSI SQL:2003. But it's not globally supported, it often performs badly, and it's a bit of a pain because you have to move/copy your ORDER into a new place in the statement, which makes it harder to wrap automatically:

SELECT * FROM (
    SELECT thiscol, thatcol, ROW_NUMBER() OVER (ORDER BY mtime DESC, id) AS rownumber
)
WHERE rownumber BETWEEN 10 AND 20 -- care, 1-based index
ORDER BY rownumber;

There is also the "FETCH FIRST n ROWS ONLY" suffix in SQL:2008 (and DB2, where it originated). But like the TOP prefix in SQL Server, and the similar syntax in Informix, you can't specify a start point, so you still have to fetch and throw away some rows.

bobince
The ISO SQL:2008 standard specifies that you can indicate a starting point using "OFFSET n" before "FETCH FIRST m ROWS ONLY". But I know of no product which currently implements OFFSET.
Troels Arvin
+5  A: 

See Limit—with offset section on this page: http://troels.arvin.dk/db/rdbms/

BTW, Firebird also supports ROWS clause since version 2.0

Milan Babuškov
A: 

BTW, Troels, PostgreSQL supports Limit/Offset

Lou O'Quin
+1  A: 

ANSI Sql example: offset=41, fetchsize=10

SELECT TOP(10) * FROM table1 WHERE table1.ID NOT IN (SELECT TOP(40) table1.ID FROM table1)

Dušan Stanojević
nice! but I think that TOP isn't sql ansi, is T-SQL :(
Click Ok
+1  A: 

TOP is not ansi

Teste