แนวคิด
COALESCE() คืนค่า NON-NULL แรก จากรายการ arguments ใช้รวมคอลัมน์ที่อาจมี NULL ปนอยู่
รูปแบบคำสั่ง
SELECT COALESCE(column1, column2, column3, ...) FROM table;
ตัวอย่างครบถ้วน
1. สร้างตาราง
mysql> create table combineTwoColumnsDemo
-> (
-> UserId int,
-> UserName varchar(20),
-> UserAge int
-> );
Query OK, 0 rows affected (1.12 sec)
2. เพิ่มข้อมูล (มี NULL ปน)
mysql> insert into combineTwoColumnsDemo values(101,'John',23); Query OK, 1 row affected (0.16 sec) mysql> insert into combineTwoColumnsDemo values(102,'Carol',20); Query OK, 1 row affected (0.14 sec) mysql> insert into combineTwoColumnsDemo values(103,'Bob',25); Query OK, 1 row affected (0.13 sec) mysql> insert into combineTwoColumnsDemo values(104,'Mike',26); Query OK, 1 row affected (0.18 sec) mysql> insert into combineTwoColumnsDemo values(105,NULL,23); Query OK, 1 row affected (0.22 sec) mysql> insert into combineTwoColumnsDemo values(105,'Maxwell',NULL); Query OK, 1 row affected (0.15 sec)
3. ดูข้อมูลดิบ
mysql> select * from combineTwoColumnsDemo;
+--------+----------+---------+ | UserId | UserName | UserAge | +--------+----------+---------+ | 101 | John | 23 | | 102 | Carol | 20 | | 103 | Bob | 25 | | 104 | Mike | 26 | | 105 | NULL | 23 | | 105 | Maxwell | NULL | +--------+----------+---------+
4. COALESCE(UserName, UserAge) - เอาค่าแรกที่ไม่ NULL
mysql> SELECT UserName, UserAge,
-> COALESCE(UserName, UserAge) AS Combine_UserName_UserAge
-> FROM combineTwoColumnsDemo;
+----------+---------+--------------------------+ | UserName | UserAge | Combine_UserName_UserAge | +----------+---------+--------------------------+ | John | 23 | John | | Carol | 20 | Carol | | Bob | 25 | Bob | | Mike | 26 | Mike | | NULL | 23 | 23 | | Maxwell | NULL | Maxwell | +----------+---------+--------------------------+
COALESCE vs IFNULL vs NULLIF
| Function | Arguments | คืนค่า |
|---|---|---|
| COALESCE(a,b,c...) | 2+ | Non-NULL แรก |
| IFNULL(a,b) | 2 | a ถ้าไม่ NULL ไม่งั้น b (MySQL only) |
| NULLIF(a,b) | 2 | NULL ถ้า a=b ไม่งั้น a |
กรณีใช้งานจริง
1. Fallback ค่า: ใช้คอลัมน์สำรองเมื่อหลักเป็น NULL
SELECT COALESCE(phone, mobile, email, 'N/A') AS contact FROM users;
2. รวม first_name + last_name (จัดการ NULL)
SELECT CONCAT(COALESCE(first_name,''), ' ', COALESCE(last_name,'')) AS full_name FROM users;
3. Default value ในคำนวณ
SELECT COALESCE(discount, 0) * price FROM products;
สรุป: COALESCE มาตรฐาน ANSI SQL ใช้ได้ทุก DB ยืดหยุ่นกว่า IFNULL