11

I have two tables and want the total number of rows in each. The actual query is more complex as there will be where... clauses for each count

How do I do the following in t-sql (neither of which works)?

select count(*) from table1 + count(*) from table2

or

select sum(count(*) from table1,count(*) from table2)

2 Answers 2

11
select SUM(cnt) from
(
    select COUNT(*) as cnt from table1 where /* where conditions */
    union all
    select COUNT(*) from table2 where /* where conditions */
) t

Would seem to do the trick, keep the queries of the different tables separate, and extend to more tables easily.

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

2 Comments

This query is invalid for T-SQL syntax since the FROM clause of the outer SELECT statements cannot operate on the COUNT subselects
@Mr.Mountain - it was missing an alias after the final ) but other than that, it's perfectly valid.
8
select  (select count(PrimaryKeyID) from  FirstTable) 
      + (select COUNT(PrimaryKeyID) from TableSecond)

So I think we should avoid the star usage in below query. As it can cause performance degradation in your query

select  (select count(*) from  FirstTable) 
      + (select COUNT(*) from TableSecond)

6 Comments

I've made a quick test on my DB with 3 forms of counting records by primary key column: SELECT COUNT(*) FROM table; SELECT COUNT(pk_col) FROM table; SELECT COUNT(1) FROM table;. All 3 return the same results and have the same query plan. I've test two tables over 15 million records one and over 50 millions second one). So, probably, any form of COUNT by PK column doesn't make difference in MS SQL. However it makes difference for counting records by nullable columns -- which I also tested -- in that case COUNT(*) affects performance (in my test).
:) I actually wanted to say that few columns that are not indexed and and using select count(*) should slow down the access time. Don't know why it it does not make difference at your side. But it was my past experience to choose that column which is indexed.
@Grzrgorz - for nullable columns, COUNT(<column>) gives a different answer - it's not a matter of performance, it's a matter of which answer is correct in that case.
Yes Damien. I will definitely give different results. That's why should I prefer to use Primary Key ID to count the rows correctly ?
@SQL - If you wish to count the number of non-null values in a nullable column, you should use COUNT(column). But a PK column isn't nullable, so that's moot. BOL says "COUNT(*) does not require an expression parameter because, by definition, it does not use information about any particular column" (emphasis added)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.