I need to count a table's rows but I was prompt with an unusual behavior of count(*).
count(*) does not return results when I use a multi column select on an empty table. But returns expected results (0 rows) if I remove the other columns from the select statement (Single column Select).
In the code below you will find multiple tests to show you what I'm talking about.
The structure of the code bellow is:
1) Creation of a table
2) Multi column select on empty table tests, which returns unexpected results
3) Single column select on empty table test, which returns the expected result
4) Multi column select on filled table test, which returns the expected result
Question
Given this results my question is:
Why does the a multi column select on empty table doesn't return 0, and a single column select returns it?
Expected Results definition
Expected results to me means:
if a table is empty, count(*) returns 0.
If a table is not empty count returns the row count
--CREATE TEST TABLE
CREATE TABLE #EMPTY_TABLE(
ID INT
)
DECLARE @ID INT
DECLARE @ROWS INT
--MULTI COLUMN SELECT WITH EMPTY TABLE
--assignment attempt (Multi-column SELECT)
SELECT @ID = ID, @ROWS = COUNT(*)
FROM #EMPTY_TABLE
--return Null instead of 0
SELECT @ROWS Test_01 , ISNULL(@ROWS, 1 )'IS NULL'
--Set variable with random value, just to show that not even the assignment is happening
SET @ROWS = 29
--assignment attempt (Multi-column SELECT)
SELECT @ID = ID, @ROWS = COUNT(*)
FROM #EMPTY_TABLE
--return 29 instead of 0
SELECT @ROWS Test_02
--SINGLE COLUMN SELECT WITH EMPTY TABLE
--assignment attempt (Single-column SELECT)
SELECT @ROWS = COUNT(*)
FROM #EMPTY_TABLE
--returns 0 the expected result
SELECT @ROWS Test_03
--MULTI COLUMN SELECT WITH FILLED TABLE
--insert a row
INSERT INTO #EMPTY_TABLE(ID)
SELECT 1
--assignment attempt
SELECT @ID = ID, @ROWS = COUNT(*)
FROM #EMPTY_TABLE
--Returns 1
SELECT @ROWS Test_04