EN
MySQL - COUNT IF example
0 points
In this article, we would like to show you COUNT IF
statement example in MySQL.
Quick solution:
xxxxxxxxxx
1
SELECT COUNT(IF(condition, 1, NULL)) AS 'alias_name';
Note:
Go to this article to read more about
IF()
function and its parameters.
To show you how IF()
function works, 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 users whose salary is high, average or low.
Query
xxxxxxxxxx
1
SELECT
2
COUNT(IF(`salary` = 6000, 1, NULL)) AS 'high_salary',
3
COUNT(IF(`salary` = 4000, 1, NULL)) AS 'average_salary',
4
COUNT(IF(`salary` = 2000, 1, NULL)) AS 'low_salary'
5
FROM
6
`users`;
Result:

create_tables.sql
file:
xxxxxxxxxx
1
CREATE TABLE `users` (
2
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
3
`name` VARCHAR(50) NOT NULL,
4
`surname` VARCHAR(50) NOT NULL,
5
`department_id` INT(10) UNSIGNED,
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', 2, '4000'),
9
('Simon', 'Collins', 4, '4000'),
10
('Taylor', 'Martin', 2, '2000'),
11
('Andrew', 'Thompson', NULL, '2000');