Let us first create a table −
mysql> create table DemoTable ( isValidUser boolean ); Query OK, 0 rows affected (0.70 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(true); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values(false); Query OK, 1 row affected (0.07 sec) mysql> insert into DemoTable values(false); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(true); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values(true); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(true); Query OK, 1 row affected (0.28 sec) mysql> insert into DemoTable values(false); Query OK, 1 row affected (0.09 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------------+ | isValidUser | +-------------+ | 1 | | 0 | | 0 | | 1 | | 1 | | 1 | | 0 | +-------------+ 7 rows in set (0.00 sec)
Let us now see the query to use COUNT() and IF() in a single MySQL query −
mysql> select count(if(isValidUser=1,1,NULL)) AS TOTAL_NUMBER_OF_ONE from DemoTable;
This will produce the following output −
+---------------------+ | TOTAL_NUMBER_OF_ONE | +---------------------+ | 4 | +---------------------+ 1 row in set (0.06 sec)