Returning the total number of rows as a separate column when using limit

From: Andreas Joseph Krogh <andreak(at)officenet(dot)no>
To: pgsql-sql <pgsql-sql(at)postgresql(dot)org>
Subject: Returning the total number of rows as a separate column when using limit
Date: 2007-11-05 07:36:38
Message-ID: 200711050836.38130.andreak@officenet.no
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

This is a re-post as I didn't get any response last time
========================================================
Hi.

AFAICS the information about the *total* number of rows is in the "result"
somehow. When I execute a "limit 1" query with EXPLAIN ANALYZE, I se the
total number of columns in "rows=200819", so the information is there.

andreak=# EXPLAIN ANALYZE select p.id from onp_crm_person p order by p.created
DESC limit 1;

QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
Limit (cost=0.00..0.04 rows=1 width=12) (actual time=0.046..0.048 rows=1
loops=1)
-> Index Scan Backward using origo_person_created_idx on onp_crm_person p
(cost=0.00..8396.45 rows=200819 width=12) (actual time=0.041..0.041 rows=1
loops=1)
Total runtime: 0.104 ms
(3 rows)

Is it possible to use some sort of "magic" function to get this number out as
a separate column? And is this number accurate? It has to be the same as
running a separate "count(*)"-query to count the totals, which is exactly
what I'm trying to avoid.

Oracle has a special rownum and over() which can be used to accomplish this:

SELECT tmp.*, max(rownum) over() as total_count
FROM (subquery) tmp

Does PG have any equivalent way?

--
Andreas Joseph Krogh <andreak(at)officenet(dot)no>
Senior Software Developer / Manager
------------------------+---------------------------------------------+
OfficeNet AS | The most difficult thing in the world is to |
Karenslyst Allé 11 | know how to do a thing and to watch |
PO. Box 529 Skøyen | somebody else doing it wrong, without |
0214 Oslo | comment. |
NORWAY | |
Tlf: +47 24 15 38 90 | |
Fax: +47 24 15 38 91 | |
Mobile: +47 909 56 963 | |
------------------------+---------------------------------------------+

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Asko Oja 2007-11-05 09:30:55 Re: Backup Database
Previous Message Volkan YAZICI 2007-11-04 17:57:19 Partitioning and Foreign Keys