Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql boolean on where clause

I am wondering which is faster?

SELECT * FROM `table` WHERE `is_deleted` = false;

or

SELECT * FROM `table` WHERE NOT `is_deleted`

Thank you

like image 893
zer09 Avatar asked Dec 08 '15 05:12

zer09


1 Answers

Schema

create table t123
(
    id int auto_increment primary key,
    x boolean not null,
    key(x)
);
truncate table t123;
insert t123(x) values (false),(true),(false),(true),(false),(true),(false),(true),(false),(true),(false),(true);
insert t123(x) select (x) from t123;
insert t123(x) select (x) from t123;
insert t123(x) select (x) from t123;
insert t123(x) select (x) from t123;
insert t123(x) select (x) from t123;
insert t123(x) select (x) from t123;
insert t123(x) select (x) from t123;
insert t123(x) select (x) from t123;
insert t123(x) select (x) from t123;
insert t123(x) select (x) from t123;
insert t123(x) select (x) from t123;
insert t123(x) select (x) from t123;
insert t123(x) select (x) from t123;
insert t123(x) select (x) from t123;
insert t123(x) select (x) from t123;
insert t123(x) select (x) from t123;
insert t123(x) select (x) from t123;
insert t123(x) select (x) from t123;

select count(*) as rowCount from t123;
+----------+
| rowCount |
+----------+
|  3145728 |
+----------+

We now have 3.1M rows.

A

explain SELECT * FROM t123 WHERE x=false;

+----+-------------+-------+------+---------------+------+---------+-------+---------+-------------+
| id | select_type | table | type | possible_keys | key  | key_len | ref   | rows    | Extra       |
+----+-------------+-------+------+---------------+------+---------+-------+---------+-------------+
|  1 | SIMPLE      | t123  | ref  | x             | x    | 1       | const | 1570707 | Using index |
+----+-------------+-------+------+---------------+------+---------+-------+---------+-------------+

B

explain SELECT * FROM t123 WHERE NOT `x`;

+----+-------------+-------+-------+---------------+------+---------+------+---------+--------------------------+
| id | select_type | table | type  | possible_keys | key  | key_len | ref  | rows    | Extra                    |
+----+-------------+-------+-------+---------------+------+---------+------+---------+--------------------------+
|  1 | SIMPLE      | t123  | index | NULL          | x    | 1       | NULL | 3141414 | Using where; Using index |
+----+-------------+-------+-------+---------------+------+---------+------+---------+--------------------------+

So A is faster, because it is able to use the native datatype (as seen in an index that has it), and does not force a table scan due to the way B deals with the data conversion (and does cause a table scan)

The proof of it is in the explain output, with the number of rows required to determine the answer, and the lack of a use of an index (the ref column) even on the column for both queries.

Mysql manual page for Explain Syntax.

like image 88
Drew Avatar answered Oct 07 '22 12:10

Drew