I am wondering which is faster?
SELECT * FROM `table` WHERE `is_deleted` = false;
or
SELECT * FROM `table` WHERE NOT `is_deleted`
Thank you
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.
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 |
+----+-------------+-------+------+---------------+------+---------+-------+---------+-------------+
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With