ใน MySQL นิพจน์ column IS NULL คืนค่า 1 (TRUE) หากเป็น NULL, 0 (FALSE) หากไม่ใช่ NULL การใช้ใน ORDER BY จะทำให้ค่า NOT NULL (FALSE=0) อยู่ก่อน NULL (TRUE=1) เมื่อเรียง ASC
ตัวอย่างการใช้งาน
สร้างตารางและเพิ่มข้อมูล (มี NULL ในคอลัมน์ประเทศ):
mysql> create table DemoTable1357 (StudentName varchar(40), StudentCountryName varchar(30));
mysql> insert into DemoTable1357 values('Chris','US'),('David',NULL),('David','AUS'),('Carol',NULL),('Mike','UK');
ข้อมูลต้นฉบับ:
+-------------+--------------------+ | StudentName | StudentCountryName | +-------------+--------------------+ | Chris | US | | David | NULL | | David | AUS | | Carol | NULL | | Mike | UK | +-------------+--------------------+
คำสั่งเรียง NOT NULL ก่อน แล้วตามชื่อ
mysql> select * from DemoTable1357 order by (StudentCountryName IS NULL), StudentName;
ผลลัพธ์ (NOT NULL ก่อน: AUS, UK, US แล้วค่อย NULL)
+-------------+--------------------+ | StudentName | StudentCountryName | +-------------+--------------------+ | Chris | US | | David | AUS | | Mike | UK | | Carol | NULL | | David | NULL | +-------------+--------------------+
คำอธิบาย:
(StudentCountryName IS NULL)คืน 0 สำหรับ NOT NULL, 1 สำหรับ NULLORDER BY ... ASC(Default) เรียง 0 ก่อน 1 → NOT NULL ก่อน NULL- ระดับที่ 2:
StudentNameเรียงตามชื่อในแต่ละกลุ่ม - หากต้องการ NULL ก่อน:
ORDER BY (StudentCountryName IS NULL) DESCหรือORDER BY StudentCountryName IS NOT NULL - เทคนิคนี้ใช้ได้กับคอลัมน์ทุกชนิดที่รองรับ IS NULL