In database paging, determining the total number of pages is crucial for rendering pagination controls. However, executing separate count and limit queries for this purpose can be inefficient. This article explores an improved technique to obtain the result count without applying database limits.
PostgreSQL versions 8.4 and later introduced window functions, enabling the calculation of aggregate functions over partitioned subsets of data. This allows us to determine the total count and retrieve the limited result in a single query.
SELECT foo, COUNT(*) OVER() AS full_count FROM bar WHERE <some condition> ORDER BY <some col> LIMIT <pagesize> OFFSET <offset>;
However, this method may incur additional performance overhead as it requires counting all qualifying rows, potentially impacting the performance for large tables or OFFSET values close to the total row count.
In cases where performance is a concern, alternative approaches can be employed to obtain the final count of affected rows, independent of OFFSET and LIMIT applications. Postgres internal bookkeeping tracks this information, which some clients can access.
The above is the detailed content of How to Efficiently Retrieve Total Result Count in PostgreSQL Before Applying LIMIT?. For more information, please follow other related articles on the PHP Chinese website!