Syntax error Get count of zeros for columns values declared with INT type in MySQL

Get count of zeros for columns values declared with INT type in MySQL



For this, you can use LENGTH() along with REPLACE(). Let us first create a table −

mysql> create table DemoTable
(
   Value int
);
Query OK, 0 rows affected (1.22 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(10002000);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values(00000);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(400560);
Query OK, 1 row affected (0.19 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----------+
| Value    |
+----------+
| 10002000 |
|        0 |
|   400560 |
+----------+
3 rows in set (0.00 sec)

Following is the query to get the count of zeros −

mysql> select (length(Value)-length(replace(Value,'0',''))) AS NumberOfZeros from DemoTable;

This will produce the following output −

+---------------+
| NumberOfZeros |
+---------------+
|             6 |
|             1 |
|             3 |
+---------------+
3 rows in set (0.00 sec)
Updated on: 2019-09-30T06:52:26+05:30

253 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements