Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server NULLABLE column vs SQL COUNT() function

Could someone help me understand something? When I can, I usually avoid (*) in an SQL statement. Well, today was payback. Here is a scenario:

CREATE TABLE Tbl (Id INT IDENTITY(1, 1) PRIMARY KEY, Name NVARCHAR(16))

INSERT INTO Tbl VALUES (N'John')
INSERT INTO Tbl VALUES (N'Brett')
INSERT INTO Tbl VALUES (NULL)

I could count the number of records where Name is NULL as follows:

SELECT COUNT(*) FROM Tbl WHERE Name IS NULL

While avoiding the (*), I discovered that the following two statements give me two different results:

SELECT COUNT(Id) FROM Tbl WHERE Name IS NULL
SELECT COUNT(Name) FROM Tbl WHERE Name IS NULL

The first statement correctly return 1 while the second statement yields 0. Why or How?

like image 837
John Gathogo Avatar asked Apr 02 '26 16:04

John Gathogo


1 Answers

That's because

The COUNT(column_name) function returns the number of values (NULL values will not be counted) of the specified column

so when you count Id you get expected result, while counting Name no, but the answer provided by query is correct

like image 187
Marco Avatar answered Apr 04 '26 06:04

Marco