25

I am doing some paging in my application, returning 20 rows from the database at a time using PostgreSQL's standard OFFSET and LIMIT keywords. For instance, to get page 1 page:

SELECT stuff FROM table WHERE condition ORDER BY stuff OFFSET 0 LIMIT 20

It is a requirement of the application that we also show to the user the total number of records. So, obviously, I can get the total by issuing a separate query:

SELECT COUNT(*) FROM table WHERE condition

But if there are a large number of rows then this is not an optimal solution. I notice that MySQL has a very useful function called FOUND_ROWS() that does exactly what I am looking for:

http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function%5Ffound-rows

Is there an equivalent in PostgreSQL?

3 Answers 3

58

PostgreSQL has had window functions for a while now which can be used to do many things including counting rows before LIMIT is applied.

Based on the example above:

SELECT stuff,
       count(*) OVER() AS total_count
FROM table
WHERE condition
ORDER BY stuff OFFSET 40 LIMIT 20
Sign up to request clarification or add additional context in comments.

3 Comments

will count(*) OVER() AS total_count be executed for every row? e.g. if we have 20 rows, does it mean it will be calculated 20 times, or only once?
It will be executed only once.
Thank you very much! This is the best solution for my needs.
0

There is no equivalent. look at

http://archives.postgresql.org/pgsql-novice/2007-07/msg00108.php

Comments

-2
SELECT
    n_live_tup     
FROM
    pg_stat_user_tables     
WHERE 
    relname = 'table_Name';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.