Syntax error Distinct number of specific items in list with MySQL

Distinct number of specific items in list with MySQL



To find distinct number of specific items, use COUNT() along with GROUP BY clause. Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable1854 values('John-Smith');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1854 values('Chris-Brown');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1854 values('Adam-Smith');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1854 values('John-Doe');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1854 values('John-Smith');
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1854;

This will produce the following output −

+-------------+
| Name        |
+-------------+
| John-Smith  |
| Chris-Brown |
| Adam-Smith  |
| John-Doe    |
| John-Smith  |
+-------------+
5 rows in set (0.00 sec)

Here is the query to get the distinct number of specific items in list −

mysql> select Name,count(Name) from DemoTable1854
     where Name like 'John-%'
     group by Name;

This will produce the following output −

+------------+-------------+
| Name       | count(Name) |
+------------+-------------+
| John-Smith |           2 |
| John-Doe   |           1 |
+------------+-------------+
2 rows in set (0.00 sec)
Updated on: 2019-12-26T06:34:03+05:30

195 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements