This article is half-done without your Comment! *** Please share your thoughts via Comment ***
In this post, I am going to demonstrate the PostgreSQL Pagination or Custom paging query using OFFSET and LIMIT.
Whenever thousands or millions of rows are returning from the database at that time paging is required.
Using custom paging we can return only limited data for a particular page.
For example, database stored procedure returned 10,00,00 records at one call.
How can you arrange this many data into the application grid or any report?In this kind of requirement, database paging is playing an important role.
The Application has to call a stored procedure using two primary parameters.
Page number
Page size
PostgreSQL provides powerful LIMIT and OFFSET features.
LIMIT and OFFSET fetches only small portion of rows from a primary the result set.
Using LIMIT you can set a total number of rows which are limited.
Using OFFSET you can skip a number of rows which number is defined by OFFSET.
For more details please visit this official document.
Below is a stored function for Custom Paging.
Below, is a created one Employee table with 10 rows.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
CREATE TABLE Employee ( EmpID SERIAL ,EmpName CHARACTER VARYING(50) ,Gender CHAR(1) ,AGE SMALLINT ); INSERT INTO Employee ( EmpName ,Gender ,AGE ) VALUES ('Anvesh','M',27) ,('Mohan','M',30) ,('Roy','M',31) ,('Meera','F',27) ,('Richa','F',26) ,('Martin','M',35) ,('Mahesh','M',38) ,('Paresh','M',22) ,('Alina','F',21) ,('Alex','M',24); |
Below is custom paging stored procedure:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
CREATE OR REPLACE FUNCTION fn_GetEmployeeData ( Paging_PageSize INTEGER = NULL ,Paging_PageNumber INTEGER = NULL ) RETURNS TABLE ( outEmpID INTEGER ,outEmpName CHARACTER VARYING ,outGender CHAR(1) ,outAge SMALLINT ) AS $BODY$ DECLARE PageNumber BIGINT; BEGIN /* *************************************************************** Construct Custom paging parameter... **************************************************************** */ IF (paging_pagesize IS NOT NULL AND paging_pagenumber IS NOT NULL) THEN PageNumber := (Paging_PageSize * (Paging_PageNumber-1)); END IF; /* ************************************************ Custome paging SQL Query construction....... ************************************************ */ RETURN QUERY SELECT EmpID ,EmpName ,Gender ,Age FROM public.Employee ORDER BY EmpID LIMIT Paging_PageSize OFFSET PageNumber; EXCEPTION WHEN OTHERS THEN RAISE; END; $BODY$ LANGUAGE 'plpgsql'; |
Now execute some sample:
1 |
SELECT *FROM public.fn_GetEmployeeData(2,2) |
1 |
SELECT *FROM public.fn_GetEmployeeData(4,2) |
Above sample only return four row at second page, mean row number 5 to 8
Please Note:
Whenever you are using LIMIT at that time do not forget to use default ORDER BY which helps LIMIT to restricting data into a particular order.