-3

There is table Departments

CREATE TABLE Departments
(
    id int NOT NULL IDENTITY(1, 1) PRIMARY KEY,
    name  nvarchar(100) NOT NULL,
    parentDepId int
);

enter image description here

I need to count the rows where parentDepId = NULL, but my query returns zero every time.

SELECT COUNT(id) as DepartmentsCount
from Departments
WHERE parentDepId = NULL;

What's wrong with it?

jarlh
  • 42,561
  • 8
  • 45
  • 63
hronikata
  • 107
  • 10

3 Answers3

6

You need to use IS NULL.

SELECT COUNT(id) AS DepartmentsCount FROM Departments 
 WHERE parentDepId IS NULL

That is the only way to compare to NULL (other operators do not work).

Thilo
  • 257,207
  • 101
  • 511
  • 656
1
SELECT COUNT(Isnull(id,1)) AS DepartmentsCount
 FROM Departments 
 WHERE parentDepId IS NULL
koushik veldanda
  • 1,079
  • 10
  • 23
1

I use syntax where Column is null. Comparison with equals sign seems wrong

Jacek Cz
  • 1,872
  • 1
  • 15
  • 22