Get count of values that only appear once in a MySQL column?



To get number of values that only appear once in a column, use GROUP BY HAVING. Let us first create a table:

mysql> create table DemoTable (    Name varchar(20) ); Query OK, 0 rows affected (0.55 sec)

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

mysql> insert into DemoTable values('Larry'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('Larry'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values('Sam'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('Chris'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('Sam'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('Mike'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('Sam'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values('Larry'); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable values('Mike'); Query OK, 1 row affected (0.32 sec) mysql> insert into DemoTable values('Mike'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('Carol'); Query OK, 1 row affected (0.27 sec) mysql> insert into DemoTable values('Robert'); Query OK, 1 row affected (0.27 sec)

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

mysql> select *from DemoTable;

This will produce the following output

+--------+ | Name | +--------+ | Larry | | Larry | | Sam | | Chris | | Sam | | Mike | | Sam | | Larry | | Mike | | Mike | | Carol | | Robert | +--------+ 12 rows in set (0.00 sec)

Following is the query to count the values that only appear once in a column i.e. the count of the names that appears only once in the “Name” column:

mysql> SELECT COUNT(Name) FROM (    SELECT Name    FROM DemoTable    GROUP BY Name    HAVING COUNT(*) = 1 ) AS APPEAR_FIRST_TIME;

This will produce the following output

+-------------+ | COUNT(Name) | +-------------+ | 3 | +-------------+ 1 row in set (0.00 sec)
Updated on: 2019-07-30T22:30:25+05:30

685 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements