Pi

October 29, 2009

Postgres Paginations

Filed under: Uncategorized — rqmedes @ 6:07 am

As a follow up on pagination in MSSQL the pagination technique also works in postgres.

Pagination in MSSQL with total number of records.

although it is alot simpler in postgres
SELECT * , count(*) OVER()as total from “Table” limit 20 OFFSET 10

Advertisements

October 23, 2009

Sql Server Pagination With Total Number of Records

Filed under: SQL — Tags: , — rqmedes @ 1:00 am

Pagination is  easy in most scenarios

You usually handle it in code letting your favourite  ORM such as NHibernate  take  care of it for you.
There are times when you are required to hand-roll your own sql which is as simple as

SELECT * FROM <Table>  WHERE <Criteria> LIMIT 0, 10

or for SQL Server

ROW_NUMBER() OVER (ORDER BY <Column>) AS RowNumber

But this doesn’t  return the total number of  records,  important for  presenting   ‘Page 1 of 380‘.
I assume  most would  do an additional sql call.

SELECT  COUNT(*)  FROM  <Table>  WHERE <Criteria>

In SQL Server it is easy to get both in one query.

WITH Results AS (
SELECT ROW_NUMBER() OVER (ORDER BY <Column>) AS RowNumber,
ROW_NUMBER() OVER (ORDER BY <Column> DESCAS RowNumberDesc,
* FROM <Table>
WHERE <Criteria>)
SELECT * FROM Results  WHERE RowNumber BETWEEN <Start> AND <End>

This will return the results  between <Start> and  <End>  ordered by <Column>.
You can  get the Total Number of records  by adding the <Start> value to the  RowNumberDesc  value of the first record returned.
Preliminary benchmarking shows that it performs faster than running the two queries method.

Create a free website or blog at WordPress.com.