EN
MySQL - count rows in column
0 points
In this article, we would like to show you how to count rows in a column in MySQL.
Quick solution:
xxxxxxxxxx
1
SELECT COUNT(`column_name`)
2
FROM `table_name`;
To show how to count distinct values, we will use the following table:

Note:
At the end of this article you can find database preparation SQL queries.
In this example, we will count the number of unique countries in users
table.
Query:
xxxxxxxxxx
1
SELECT COUNT(DISTINCT(`country`)) AS `unique_countries`
2
FROM `users`;
Output:

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
`email` VARCHAR(50),
6
PRIMARY KEY (`id`)
7
);
8
insert_data.sql
file:
xxxxxxxxxx
1
INSERT INTO `users`
2
( `name`, `surname`, `email`)
3
VALUES
4
('John', 'Stewart', 'john@email.com'),
5
('Chris', 'Brown', NULL),
6
('Kate', 'Lewis', NULL),
7
('Ailisa', 'Gomez', 'ailisa@email.com'),
8
('Gwendolyn', 'James', NULL),
9
('Simon', 'Collins', NULL),
10
('Taylor', 'Martin', NULL),
11
('Andrew', 'Thompson', 'andrew@email.com');