Tutorialspoint

1 Answer
karthikeya Boyini

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;

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;

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)

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.