How to set default value to NULL in MySQL?

MySQLMySQLi Database

Use DEFAULT keyword in MySQL to set default value to NULL. Let us first create a −

mysql> create table DemoTable1440
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(20) DEFAULT NULL,
   -> StudentAge int DEFAULT NULL
   -> );
Query OK, 0 rows affected (0.55 sec)

Insert some records in the table using insert command. For values left blank, the default gets inserted −

mysql> insert into DemoTable1440(StudentName,StudentAge) values('Chris',21);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1440 values();
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1440(StudentName) values('David');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1440(StudentAge) values(24);
Query OK, 1 row affected (0.09 sec)

Display all records from the table using select −

mysql> select * from DemoTable1440;

This will produce the following output −

+-----------+-------------+------------+
| StudentId | StudentName | StudentAge |
+-----------+-------------+------------+
|         1 | Chris       |         21 |
|         2 | NULL        |       NULL |
|         3 | David       |       NULL |
|         4 | NULL        |         24 |
+-----------+-------------+------------+
4 rows in set (0.00 sec)
raja
Published on 12-Nov-2019 06:55:43
Advertisements