Sử dụng từ khóa DEFAULT trong định nghĩa cột khi CREATE TABLE.
Tạo bảng có DEFAULT
mysql> CREATE TABLE DemoTable803(
UserId INT DEFAULT 101,
UserName VARCHAR(100) DEFAULT 'Chris'
);
Query OK, 0 rows affected (1.18 sec)
Chèn dữ liệu với các trường hợp khác nhau
mysql> INSERT INTO DemoTable803 VALUES(102, 'Chris');
Query OK, 1 row affected (0.34 sec)
mysql> INSERT INTO DemoTable803(UserName) VALUES('Mike');
Query OK, 1 row affected (0.48 sec) -- UserId lấy DEFAULT 101
mysql> INSERT INTO DemoTable803(UserId) VALUES(103);
Query OK, 1 row affected (0.21 sec) -- UserName lấy DEFAULT 'Chris'
mysql> INSERT INTO DemoTable803 VALUES();
Query OK, 1 row affected (0.22 sec) -- Cả hai đều lấy DEFAULT
mysql> INSERT INTO DemoTable803 VALUES(110, 'Robert');
Query OK, 1 row affected (0.33 sec)
Kết quả
+--------+----------+ | UserId | UserName | +--------+----------+ | 102 | Chris | | 101 | Mike | | 103 | Chris | | 101 | Chris | | 110 | Robert | +--------+----------+
Xem giá trị DEFAULT của bảng
mysql> SELECT DEFAULT(UserId), DEFAULT(UserName) FROM DemoTable803 LIMIT 1;
+-----------------+-------------------+ | DEFAULT(UserId) | DEFAULT(UserName) | +-----------------+-------------------+ | 101 | Chris | +-----------------+-------------------+
Lưu ý: DEFAULT chỉ áp dụng khi cột không được nhắc đến trong INSERT hoặc dùng DEFAULT từ khóa: INSERT INTO t VALUES(DEFAULT, 'abc').