Home > Backend Development > PHP Tutorial > How to Efficiently Retrieve Total Result Count in PostgreSQL Before Applying LIMIT?

How to Efficiently Retrieve Total Result Count in PostgreSQL Before Applying LIMIT?

DDD
Release: 2024-12-13 22:48:11
Original
688 people have browsed it

How to Efficiently Retrieve Total Result Count in PostgreSQL Before Applying LIMIT?

Optimal Approach to Retrieve Result Count Prior to Limit Application

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.

Postgres Window Functions

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>;
Copy after login

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.

Alternative Options for Result 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.

  • PL/pgSQL: Retrieve the row count after executing an SQL command using GET DIAGNOSTICS.
  • PHP: Use the pg_num_rows function to determine the number of affected rows.

Additional Resources

  • [Calculating the Number of Rows Affected by Batch Queries in PostgreSQL](https://dba.stackexchange.com/questions/247142/calculate-number-of-rows-affected-by-batch-query-in-postgresql)

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template