How to set default Field Value in MySQL?


To set default field value, use the “default”. Let us first create a table −

mysql> create table DemoTable
-> (
-> Age int
-> );
Query OK, 0 rows affected (0.58 sec)

Here is the query to set default field value in MySQL −

mysql> alter table DemoTable MODIFY Age int default 18;
Query OK, 0 rows affected (0.25 sec)
Records: 0 Duplicates: 0 Warnings: 0

Now you can check the table description −

mysql> desc DemoTable;

Output

This will produce the following output −

+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| Age   | int(11) | YES  |     | 18      |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)

Insert some records in the table using insert command. We have left two of the fields without any value. Therefore, it would be set as the default field value −

mysql> insert into DemoTable values(19);
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable values();
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable values(20);
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable values();
Query OK, 1 row affected (0.11 sec)

Display all records from the table using select statement −

mysql>select *from DemoTable;

Output

This will produce the following output. As you can see two of the values are set 18, since we have set the same as default above −

+------+
| Age  |
+------+
| 19   |
| 18   |
| 20   |
| 18   |
+------+
4 rows in set (0.00 sec)

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jun-2020

494 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements