MySQL query to count where more than three columns values are true?

MySQLMySQLi Database

To count where more than three column values are true, you can use WHERE clause. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> isMarried boolean,
   -> isActive boolean,
   -> isMember boolean,
   -> isOn boolean
   -> );
Query OK, 0 rows affected (0.61 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(true,false,true,false);
Query OK, 1 row affected (0.14 sec)

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

mysql> insert into DemoTable values(true,true,true,true);
Query OK, 1 row affected (0.24 sec)

mysql> insert into DemoTable values(true,false,false,true);
Query OK, 1 row affected (0.55 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+-----------+----------+-----------+------+
| isMarried | isActive | isMember  | isOn |
+-----------+----------+-----------+------+
| 1         | 0        | 1         | 0    |
| 0         | 0        | 0         | 0    |
| 1         | 1        | 1         | 1    |
| 1         | 0        | 0         | 1    |
+-----------+----------+-----------+------+
4 rows in set (0.00 sec)

Following is the query to count where more than three column values are true −

mysql> select *from DemoTable where isMarried+isActive+isMember+isOn >=3;

Output

+-----------+----------+-----------+------+
| isMarried | isActive | isMember  | isOn |
+-----------+----------+-----------+------+
| 1         | 1        | 1         | 1    |
+-----------+----------+-----------+------+
1 row in set (0.00 sec)
raja
Published on 09-Jul-2019 16:00:41
Advertisements