0

I am trying to query a db using some limit and offsets for pagination along with some WHERE clause. I also needs the number of total rows that matches the WHERE clause.

I have used "count OVER" in PostgreSQL like this:

SELECT
    user_id,
    created_on,
    COUNT(user_id) OVER() AS full_count
FROM 
    user_info
WHERE 
    user_info.user_id = ANY(unlocked_ids)
ORDER BY 
    created_on DESC
LIMIT p_limit OFFSET p_offset

Now it returns me the number of rows that matches there WHERE clause in the last column. When the offset is too high, it returns empty table as expected. But I need the the number of matches rows all the times, even when the offset is too high.

Currently the solution i tried is making another query with LIMIT 1 and offset 0 which will always return me one result if there is something that matches the WHERE clause. But is it possible to do it without the additional query?

1 Answer 1

1

Why not just get the count first, once before doing the pagination?

SELECT count(*) as full_count
FROM user_info
WHERE user_info.user_id = ANY(unlocked_ids);

You can then use this count for the rest of the pagination.

This will also save the calculation of the full_count in the query itself. So, the overhead of doing the count first offsets the overhead in the query.

Sign up to request clarification or add additional context in comments.

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.