NULL & Aggregation
NULL คืออะไร?
Section titled “NULL คืออะไร?”NULL ไม่ใช่ 0, ไม่ใช่ string ว่าง, ไม่ใช่ FALSE — NULL หมายถึง “ไม่ทราบค่า” หรือ “ไม่มีข้อมูล”
เหมือนช่องว่าง — ถ้าช่องว่าง SUM/COUNT จะข้ามไปเอง
// C ใช้ NULL pointer// ไม่มี concept ของ "ค่าไม่ทราบ" ใน primitive typeschar *email = NULL; // ไม่มี email# Python ใช้ Noneemail = Noneif email is None: # ใช้ is ไม่ใช่ == print("ไม่มี email")-- ข้อมูลตัวอย่าง: STD005 มี email = NULLSELECT student_id, name, email FROM students;
-- IS NULL / IS NOT NULLSELECT name FROM students WHERE email IS NULL;-- ผลลัพธ์: กมล
SELECT name FROM students WHERE email IS NOT NULL;-- ผลลัพธ์: สมชาย, สมหญิง, วิชัย, มานี, ปรีชาNULL กับ Aggregate Functions
Section titled “NULL กับ Aggregate Functions”กฎสำคัญ: aggregate functions ข้าม NULL ไปเสมอ (ยกเว้น COUNT(*))
-- สมมติ students มี 6 แถว, email NULL 1 แถวSELECT COUNT(*) AS count_all, -- 6 (นับทุกแถว) COUNT(email) AS count_email -- 5 (ข้าม NULL)FROM students;SUM และ AVG กับ NULL
Section titled “SUM และ AVG กับ NULL”-- สมมติ price มีค่า: 4500, 3200, 7800, 4500, NULL, 9500-- (ถ้า STD005 มี price = NULL)
SELECT SUM(price) AS total, -- 29500 (ข้าม NULL) AVG(price) AS average -- 5900 (29500 / 5 ไม่ใช่ / 6)FROM students;COALESCE() — แทนที่ NULL ด้วยค่าอื่น
Section titled “COALESCE() — แทนที่ NULL ด้วยค่าอื่น”COALESCE(value, fallback) คืนค่า value ถ้าไม่ใช่ NULL มิฉะนั้นคืน fallback
-- แสดง email หรือ 'ไม่มีข้อมูล' ถ้าเป็น NULLSELECT name, COALESCE(email, 'ไม่มีข้อมูล') AS email_displayFROM students;| name | email_display |
|---|---|
| สมชาย | somchai@mail.com |
| กมล | ไม่มีข้อมูล |
COALESCE กับ Aggregate
Section titled “COALESCE กับ Aggregate”-- ถ้าต้องการให้ NULL นับเป็น 0 ใน AVGSELECT AVG(COALESCE(price, 0)) AS avg_with_null_as_zeroFROM students;-- ตอนนี้หาร 6 แทน 5COALESCE หลายค่า
Section titled “COALESCE หลายค่า”COALESCE รับหลาย argument — คืนค่าตัวแรกที่ไม่ใช่ NULL
SELECT COALESCE(email, phone, 'ไม่มีช่องทางติดต่อ') AS contactFROM students;-- ลอง email ก่อน ถ้า NULL ลอง phone ถ้า NULL ทั้งคู่ใช้ fallbackNULL ใน GROUP BY
Section titled “NULL ใน GROUP BY”NULL ถือเป็นกลุ่มเดียวกันใน GROUP BY:
SELECT email IS NOT NULL AS has_email, COUNT(*) AS num_studentsFROM studentsGROUP BY email IS NOT NULL;| has_email | num_students |
|---|---|
| TRUE | 5 |
| FALSE | 1 |