For example, using the answer for this question:
How to select all users who made more than 10 submissions "How to select all users who made more than 10 submissions."
select userId
from submission
group by userId
having count(submissionGuid) > 10
Let's say now I want to know many rows this sql statement outputted. How scalable is the solution for counting the rows of counting the rows?
To count the number of rows, use the id column which stores unique values (in our example we use COUNT(id) ). Next, use the GROUP BY clause to group records according to columns (the GROUP BY category above). After using GROUP BY to filter records with aggregate functions like COUNT, use the HAVING clause.
The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.
The use of COUNT() function in conjunction with GROUP BY is useful for characterizing our data under various groupings. A combination of same values (on a column) will be treated as an individual group.
Using COUNT, without GROUP BY clause will return a total count of a number of rows present in the table. Adding GROUP BY, we can COUNT total occurrences for each unique value present in the column.
Slight error in previously posted example, need an alias for a table name for the subquery:
select count(*) from
(select userId
from submission
group by userId
having count(submissionGuid) > 10) t
I'm not sure about scalability, but this is the solution. If this isn't scaling well enough for you, you need to consider major design changes, like perhaps tracking those who submitted more than 10 submissions in a separate table that you update through applications that populate the submissions. Or many other possible solutions.
Nested queries:
select count(*) from
(select userId
from submission
group by userId
having count(submissionGuid) > 10) n
Edited to incorporate mbrierst's comment about needing an alias (the "n" at the end) for the nested subquery. Oracle does not require this, but SQL Server does. Feel free to add a comment regarding usage on other database platforms.
In SQL Server you could do
select @@ROWCOUNT
immediately following the query you posted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With