php - Best way to get result count before LIMIT was applied -
when paging through data comes db, need know how many pages there render page jump controls.
currently running query twice, once wrapped in count()
determine total results, , second time limit applied results need current page.
this seems inefficient. there better way determine how many results have been returned before limit
applied?
i using php , postgres.
pure sql
things have changed since 2008. can use window function full count , limited result in 1 query. (introduced postgresql 8.4 in 2009).
select foo ,count(*) over() full_count bar <some condition> order <some col> limit <pagesize> offset <offset>
note can considerably more expensive without total count. rows have counted, , shortcut taking top rows matching index not possible.
doesn't matter small tables, matters big tables.
consider sequence of events:
where
clause (andjoin
conditions, not here) filter qualifying rows base table(s).(
group by
, aggregate functions go here.)window functions applied considering qualifying rows (depending on
over
clause , frame specification of function). simplecount(*) over()
based on rows.order by
(
distinct
ordistinct on
go here.)limit
/offset
applied based on established order select rows return.
note limit
/ offset
becomes increasingly inefficient growing number of rows in table. consider alternative approaches if need better performance:
alternatives
there different approaches, too. postgres has internal bookkeeping how many rows affected last sql command. clients can access information or count rows (like psql).
for instance, can retrieve number of affected rows in plpgsql after executing sql command with:
get diagnostics integer_var = row_count;
or can use pg_num_rows
in php
code examples:
Comments
Post a Comment