SQL ค่า NULL

ค่า NULL คือข้อมูลที่ขาดหายและไม่ทราบ

โดยมาตรฐาน คอลัมน์ในตารางสามารถเก็บค่า NULL

บทบาทนี้มีเนื้อหาเกี่ยวกับการใช้ประกาศ IS NULL และ IS NOT NULL

SQL ค่า NULL

ถ้าคอลัมน์ในตารางเป็นค่าเลือกได้ พวกเราสามารถเพิ่มบันทึกใหม่หรือปรับปรุงบันทึกที่มีอยู่โดยไม่ต้องเพิ่มค่าในคอลัมน์นั้น ซึ่งหมายความว่า คอลัมน์นั้นจะเก็บค่า NULL

NULL ค่าจัดการแตกต่างจากค่าอื่นๆ

NULL is used as a placeholder for unknown or inapplicable values.

Note:NULL cannot be compared with 0; they are not equivalent.

SQL NULL Value Handling

Please see the following 'Persons' table:

Id LastName FirstName Address City
1 Adams John   London
2 Bush George Fifth Avenue New York
3 Carter Thomas   Beijing

Suppose the 'Address' column in the 'Persons' table is optional. This means that if a record without a value is inserted into the 'Address' column, the 'Address' column will use the NULL value to save it.

So how do we test NULL values?

Comparison operators cannot be used to test NULL values, such as =, <, or <>.

We must use the IS NULL and IS NOT NULL operators.

SQL IS NULL

How do we only select records that have NULL values in the 'Address' column?

We must use the IS NULL operator:

SELECT LastName,FirstName,Address FROM Persons
WHERE Address IS NULL

Result Set:

LastName FirstName Address
Adams John  
Carter Thomas  

Tip:Always use IS NULL to find NULL values.

SQL IS NOT NULL

How do we select records that do not have NULL values in the 'Address' column?

We must use the IS NOT NULL operator:

SELECT LastName,FirstName,Address FROM Persons
WHERE Address IS NOT NULL

Result Set:

LastName FirstName Address
Bush George Fifth Avenue

In the next section, we will learn about the ISNULL(), NVL(), IFNULL(), and COALESCE() functions.