I got a question last week How to Count the Total Number of Rows Across Multiple Tables.
CREATE TABLE #t1 ([c1] [nchar](10) NULL) ON [PRIMARY]
CREATE TABLE #t2 ([c1] [nchar](10) NULL) ON [PRIMARY]
CREATE TABLE #t3 ([c1] [nchar](10) NULL) ON [PRIMARY]
DECLARE @i INT
SET @i = 1
WHILE @i & lt;= 13
BEGIN
INSERT INTO #t1 (c1)
VALUES ('x')
SET @i = @i + 1
END
DECLARE @x INT
SET @x = 1
WHILE @x & lt;= 12
BEGIN
INSERT INTO #t2 (c1)
VALUES ('x')
INSERT INTO #t3 (c1)
VALUES ('x')
SET @x = @x + 1
END
The questions seems like a simple one. We can use the aggregate functions in SQL to help do the maths in terms of counting the rows However the solution needs to two steps.
Using the COUNT Aggregate function we can quickly count the rows in one table. The first query counts all the rows in table t1
So we have a starting point. Next we need count all the rows in the second table
SELECT COUNT(*)
FROM #t2
We need to repeat this for all the tables that we want to include in the final total row number.
When we have counted rows in all the necessary tables individually we then need to combine the individual results into one result set.
We can do this with a UNION ALL. This will combine the counts for each table into a single result set.
Tables t2 and t3 each have 12 rows each. If we build our table row count table with a UNION it will do implicit distinct and remove duplicates. therefore we have two rows in the result set that have the value 12 so only one is included with the UNION. Therefore our next calculation of adding all the counts together will be wrong
So we have a result that is giving us the count of the rows in each table. Now we need to add the row totals together. We can do that by putting our UNION ALL query into a derived table or common table expression (CTE). An inline view if you prefer. The CTE or derived table will allow us to include the result set of our UNION ALL statement in the FROM clause and the SELECT from it to sum the total rows.
In this example I will use a CTE
I use in SUM in the outer query to add the number of rows of each table in the final result set. Giving us 37 rows across the 3 tables t1, t2 and t3
If you are looking to do this yourself. You need to do the following:
- Use SELECT COUNT (*) on each table to have its rowed total
- Use UNION ALL to build a result of the row count of each table
- Wrap that result set in CTE or derived table
- Select from the CTE or derived table SUMing the row count column