Count items in a MySQL table with type ENUM involved?


You can use GROUP BY along with aggregate function COUNT(). Let us first create a table −

mysql> create table DemoTable
   ( 
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Size ENUM('S','M','L','XL')
   );
Query OK, 0 rows affected (0.69 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Size) values('L');
Query OK, 1 row affected (0.19 sec)

mysql> insert into DemoTable(Size) values('S');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable(Size) values('S');
Query OK, 1 row affected (0.30 sec)

mysql> insert into DemoTable(Size) values('M');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable(Size) values('XL');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable(Size) values('M');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable(Size) values('M');
Query OK, 1 row affected (0.10 sec)

mysql> insert into DemoTable(Size) values('M');
Query OK, 1 row affected (0.10 sec)

mysql> insert into DemoTable(Size) values('XL');
Query OK, 1 row affected (0.08 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+------+
| Id | Size |
+----+------+
|  1 | L    |
|  2 | S    |
|  3 | S    |
|  4 | M    |
|  5 | XL   |
|  6 | M    |
|  7 | M    |
|  8 | M    |
|  9 | XL   |
+----+------+
9 rows in set (0.00 sec)

Following is the query to count items in table with table filed as ENUM −

mysql> SELECT tbl.Size, COUNT(1) AS Frequency from DemoTable tbl group by tbl.Size;

This will produce the following output −

+------+-----------+
| Size | Frequency |
+------+-----------+
| L    |         1 |
| S    |         2 |
| M    |         4 |
| XL   |         2 |
+------+-----------+
4 rows in set (0.00 sec)
raja
Published on 17-May-2019 17:59:03
Advertisements