EN
PostgreSQL - count rows with NULL values
0 points
In this article, we would like to show you how to count rows with NULL
values in PostgreSQL.
Quick solution:
xxxxxxxxxx
1
SELECT COUNT(*) AS "alias_name"
2
FROM "table_name"
3
WHERE "column_name" IS NULL;
To show you how to count rows with NULL
values, we will use the following users
table:

Note:
At the end of this article you can find database preparation SQL queries.
In this example, we will count the number of rows with NULL
values in department_id
column.
Query
xxxxxxxxxx
1
SELECT COUNT(*) AS "NULL_values_in_column"
2
FROM "users"
3
WHERE "department_id" IS NULL;
Result:

create_tables.sql
file:
xxxxxxxxxx
1
CREATE TABLE "users" (
2
"id" SERIAL,
3
"name" VARCHAR(50) NOT NULL,
4
"surname" VARCHAR(50) NOT NULL,
5
"department_id" INTEGER,
6
"salary" DECIMAL(15,2) NOT NULL,
7
PRIMARY KEY ("id")
8
);
insert_data.sql
file:
xxxxxxxxxx
1
INSERT INTO "users"
2
( "name", "surname", "department_id", "salary")
3
VALUES
4
('John', 'Stewart', 1, '6000'),
5
('Chris', 'Brown', 2, '6000'),
6
('Kate', 'Lewis', 3, '4000'),
7
('Ailisa', 'Gomez', NULL, '4000'),
8
('Gwendolyn', 'James', NULL, '4000'),
9
('Simon', 'Collins', 4, '4000'),
10
('Taylor', 'Martin', 2, '2000'),
11
('Andrew', 'Thompson', NULL, '2000');