I am wondering if it is necessary or a good practice to perform null value check before doing comparison in database, especially on MySQL and MSSQL as I am working on those. Is there any performance impact if null check is performed?
In short, what is the difference between version 1 and version 2 in the following SQL for MySQL, in terms of the result produced and performance?
DROP TABLE IF EXISTS t1;
CREATE TABLE t1 (
id INT AUTO_INCREMENT PRIMARY KEY,
intval INT NULL DEFAULT NULL,
strval VARCHAR(32) NULL DEFAULT NULL,
KEY idx_intval (intval),
KEY idx_strval (strval)
);
INSERT INTO t1 (intval, strval) VALUES
(2, 'B'),
(1, 'A'),
(NULL, 'C'),
(4, NULL);
-- Version 1
SELECT * FROM t1 WHERE intval IS NOT NULL AND intval > 1;
SELECT * FROM t1 WHERE strval IS NOT NULL AND strval IN ('A', 'C');
-- Version 2
SELECT * FROM t1 WHERE intval > 1;
SELECT * FROM t1 WHERE strval IN ('A', 'C');
DROP TABLE t1;
Every comparison with NULL fails, if you don't use IS NULL / IS NOT NULL.
So:
NULL > 1 fails (==> it isn't necessary to specify INTVAL IS NOT NULL)
NULL IN ('A', 'C') fails (==> it isn't necessary to specify STRVAL IS NOT NULL)
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