Can I get the number of results plus the results with a single query?

From: Perry Smith <pedz(at)easesoftware(dot)com>
To: pgsql-general list <pgsql-general(at)lists(dot)postgresql(dot)org>
Subject: Can I get the number of results plus the results with a single query?
Date: 2022-08-15 13:49:33
Message-ID: 75BBE3C5-D495-47B8-A81C-6359391E3B99@easesoftware.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

I like to have what I call “baby sitting” messages such as “Completed 15 out of 1023”. To do this, I need the number of results a query returns but I also need the results.

Currently I’m doing this with two queries such as:

SELECT COUNT(*) FROM table WHERE …. expression …
SELECT * FROM table WHERE …. expression …

But this requires two queries. Is there a way to do the same thing with just one query somehow?

I’ve been toying with row_number() and then sort by row_number descending and pick off the first row as the total number. The problem is that mucks with the order of the original query because of the sort on row_number. I’ve even thought about reversing the order and then reversing the order a second time but that seems to be getting more than a little absurd.

Thank you for your time,
Perry

Responses

Browse pgsql-general by date

  From Date Subject
Next Message David G. Johnston 2022-08-15 13:55:17 Re: Can I get the number of results plus the results with a single query?
Previous Message Gaurav Daunde 2022-08-15 12:48:47 Help regarding Multi Tenancy with PostgreSQL