Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to do NULL value check before doing comparison on a nullable column in database?

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;
like image 307
VCD Avatar asked Jun 11 '26 12:06

VCD


1 Answers

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)

like image 86
UltraCommit Avatar answered Jun 14 '26 00:06

UltraCommit