3

I've got a query that looks like this:

SELECT t1.id, t1.name, t1.description
FROM t1
LEFT JOIN t2 ON (t2.id = t1.id)
WHERE condition
GROUP BY t1.id
LIMIT 100

I would like to count the total number of rows that satisfy this query past the limit in addition to returning the specified columns (id, name, description). The problem is that due to the GROUP BY, if I were to do a count(*), I just get a bunch of rows with 1.

So my question is: how can I count the number of rows returned by this query? And how can I do so disregarding the limit?

Also is it possible to return both the row count AND the column data in a single query? Or would I need to use two queries?

1 Answer 1

1

You could use subquery:

SELECT COUNT(*)
FROM (
  SELECT t1.id
  FROM t1
  LEFT JOIN t2 ON (t2.id = t1.id)
  WHERE condition
  GROUP BY t1.id) sub

EDIT:

Also is it possible to return both the row count AND the column data in a single query? Or would I need to use two queries?

Yes, using windowed COUNT:

SELECT t1.id, COUNT(*) OVER() AS num_of_r0ws
FROM t1
LEFT JOIN t2 ON (t2.id = t1.id)
WHERE condition
GROUP BY t1.id
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for quick answer. But wouldn't your first solution only count 100 rows? I'm looking to count ALL rows that exist disregarding the limit. For example if I had 1000 rows, but the inner query contains a limit 100, I'd still like the count to return 1000
@Andrew You could remove that limit, I do not see the point of using it at all
The limit was for pagination, but I see that your second suggestion actually accomplishes what I want. Thanks for the fast response!

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.