1

I have a query with a limit and an offset. For example:

select * from tbl
limit 10 offset 100;

How to keep track of the count of the records, without running a second query like:

select count(*) from tbl;

I think this answers my question, but I need it for PostgreSQL. Any ideas?

4
  • I need something with one query only, because my query is very slow (about 1 second) and I cannot run it twice due to performance issues (my query runs a full-text-search on a very large table). Commented Aug 25, 2011 at 7:04
  • 1
    It's also meaningless unless you specify an ORDER BY clause. Commented Aug 25, 2011 at 7:07
  • @Дамян Станчев: So it's a performance issue and there's really no reason why you can't use a second, count query? Commented Aug 25, 2011 at 7:07
  • There is - to select the count(*) I must re-fetch the full-text-search reuslts again along with the other limitations and the query is quite slow... Commented Aug 25, 2011 at 7:15

3 Answers 3

4

I have found a solution and I want to share it. What I do is - I create a temp table from my real table with the filters applied, then I select from the temp table with a limit and offset (no limitations, so the performance is good), then select count(*) from the temp table (again no filters), then the other stuff I need and last - I drop the temp table.

select * into tmp_tbl from tbl where [limitations];
select * from tmp_tbl offset 10 limit 10;
select count(*) from tmp_tbl;
select other_stuff from tmp_tbl;
drop table tmp_tbl;
Sign up to request clarification or add additional context in comments.

Comments

0

I haven't tried this, but from the section titled Obtaining the Result Status in the documentation you can use the GET DIAGNOSTICS command to determine the effect of a command.

GET DIAGNOSTICS number_of_rows = ROW_COUNT;

From the documentation:

This command allows retrieval of system status indicators. Each item is a key word identifying a state value to be assigned to the specified variable (which should be of the right data type to receive it). The currently available status items are ROW_COUNT, the number of rows processed by the last SQL command sent down to the SQL engine, and RESULT_OID, the OID of the last row inserted by the most recent SQL command. Note that RESULT_OID is only useful after an INSERT command into a table containing OIDs.

Comments

-3

Depends if you need it from the psql CLI or if you're accessing the database from something like an HTTP server. I am using postgres from my Node server with node-postgres. The result set is returned as an array called 'rows' on the result object so I can just do

console.log(results.rows.length)

To get the row count.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.