Can we ignore duplicate rows in COUNT?

MySQLMySQLi Database

Yes, we can ignore duplicate rows in COUNT using DISTINCT. Following is the syntax:

select count(distinct yourColumnName) from yourTableName;

In MySQL, COUNT() will display the number of rows. DISTINCT is used to ignore duplicate rows and get the count of only unique rows.

Let us first create a table:

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   FirstName varchar(10)
);
Query OK, 0 rows affected (0.47 sec)

Following is the query to insert some records in the table using insert command:

mysql> insert into DemoTable(FirstName) values('Larry');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable(FirstName) values('John');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable(FirstName) values('Sam');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(FirstName) values('John');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(FirstName) values('John');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(FirstName) values('Larry');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(FirstName) values('Mike');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable(FirstName) values('Robert');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(FirstName) values('Carol');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(FirstName) values('Mike');
Query OK, 1 row affected (0.12 sec)

Following is the query to display records from the table using select command:

mysql> select *from DemoTable;

This will produce the following output:

+----+-----------+
| Id | FirstName |
+----+-----------+
|  1 | Larry     |
|  2 | John      |
|  3 | Sam       |
|  4 | John      |
|  5 | John      |
|  6 | Larry     |
|  7 | Mike      |
|  8 | Robert    |
|  9 | Carol     |
| 10 | Mike      |
+----+-----------+
10 rows in set (0.00 sec)

Following is the query to ignore duplicate rows in COUNT and get the count of only unique rows:

mysql> select count(distinct FirstName) from DemoTable;

This will produce the following output:

+---------------------------+
| count(distinct FirstName) |
+---------------------------+
|                         6 |
+---------------------------+
1 row in set (0.03 sec)
raja
Published on 29-Apr-2019 14:16:05
Advertisements