เมื่อมีคอลัมน์ที่ยังเป็น NULL และต้องการคำนวณค่าแล้วอัปเดตเข้าไป สามารถใช้เงื่อนไข WHERE column IS NULL ร่วมกับ UPDATE
ตัวอย่างการสร้างตาราง
mysql> create table DemoTable (
ProductPrice int,
ProductQuantity int,
TotalAmount int );
Query OK, 0 rows affected (1.22 sec)
เพิ่มข้อมูล (TotalAmount ยังเป็น NULL)
mysql> insert into DemoTable(ProductPrice,ProductQuantity) values(100,2); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable(ProductPrice,ProductQuantity) values(500,4); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable(ProductPrice,ProductQuantity) values(1000,10); Query OK, 1 row affected (0.21 sec)
แสดงข้อมูลก่อนอัปเดต
mysql> select * from DemoTable;
+--------------+-----------------+-------------+ | ProductPrice | ProductQuantity | TotalAmount | +--------------+-----------------+-------------+ | 100 | 2 | NULL | | 500 | 4 | NULL | | 1000 | 10 | NULL | +--------------+-----------------+-------------+ 3 rows in set (0.00 sec)
คำสั่ง UPDATE คำนวณและเติมค่าเฉพาะแถวที่เป็น NULL
mysql> update DemoTable set TotalAmount = (ProductPrice * ProductQuantity) where TotalAmount IS NULL; Query OK, 3 rows affected (0.20 sec) Rows matched: 3 Changed: 3 Warnings: 0
ตรวจสอบข้อมูลหลังอัปเดต
mysql> select * from DemoTable;
+--------------+-----------------+-------------+ | ProductPrice | ProductQuantity | TotalAmount | +--------------+-----------------+-------------+ | 100 | 2 | 200 | | 500 | 4 | 2000 | | 1000 | 10 | 10000 | +--------------+-----------------+-------------+ 3 rows in set (0.00 sec)
คำอธิบาย: เงื่อนไข WHERE TotalAmount IS NULL ทำให้อัปเดตเฉพาะแถวที่ยังไม่มีค่า ไม่ทับซ้อนข้อมูลที่มีอยู่แล้ว วิธีนี้เหมาะสำหรับคำนวณค่าที่ขาดหายไป (backfill) หรือแก้ไขข้อมูลไม่ครบ