บทความนี้สาธิตการค้นหาแถวที่มีค่าว่าง ('') หรือ NULL ในคอลัมน์ข้อความ โดยใช้ IS NULL และเปรียบเทียบกับสตริงว่าง
สร้างตารางและข้อมูลทดสอบ (มีค่าว่างและ NULL)
mysql> CREATE TABLE DemoTable691(
PlayerId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
PlayerName VARCHAR(100),
PlayerScore INT
);
Query OK, 0 rows affected (0.56 sec)
mysql> INSERT INTO DemoTable691(PlayerName, PlayerScore) VALUES('Robert', 56);
mysql> INSERT INTO DemoTable691(PlayerName, PlayerScore) VALUES('David', 89);
mysql> INSERT INTO DemoTable691(PlayerName, PlayerScore) VALUES('', 98);
mysql> INSERT INTO DemoTable691(PlayerName, PlayerScore) VALUES(NULL, 71);
คิวรีค้นหาค่าว่างหรือ NULL
mysql> SELECT * FROM DemoTable691
WHERE PlayerName IS NULL OR PlayerName = '';
ผลลัพธ์
+----------+------------+-------------+
| PlayerId | PlayerName | PlayerScore |
+----------+------------+-------------+
| 3 | | 98 |
| 4 | NULL | 71 |
+----------+------------+-------------+
คำอธิบาย:
IS NULL- ตรวจสอบค่า NULL (ต้องใช้ IS ไม่ใช่ =)= ''- ตรวจสอบสตริงว่าง (Empty String)- สองเงื่อนไขนี้แยกกัน เพราะ
NULL = ''เป็น UNKNOWN ไม่ใช่ TRUE - แนะนำ: ใช้
COALESCE(PlayerName, '') = ''หรือIFNULL(PlayerName, '') = ''รวมเป็นเงื่อนไขเดียวได้