Set DEFAULT values for columns while creating a table in MySQL


To set default values for columns while creating a table, DEFAULT. Let us first see an example and create a table. As you can see below, while creating the table, we have set DEFAULT −

mysql> create table DemoTable803 (
   UserId int DEFAULT 101,
   UserName varchar(100) DEFAULT 'Chris'
);
Query OK, 0 rows affected (1.18 sec)

Insert some records in the table using insert command. For the values we are not inserting, the default values will get set automatically −

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)
mysql> insert into DemoTable803(UserId) values(103);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable803 values();
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable803 values(110,'Robert');
Query OK, 1 row affected (0.33 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable803;

This will produce the following output -

+--------+----------+
| UserId | UserName |
+--------+----------+
| 102    | Chris    |
| 101    | Mike     |
| 103    | Chris    |
| 101    | Chris    |
| 110    | Robert   |
+--------+----------+
5 rows in set (0.00 sec)

Following is the query to display the default values only −

mysql> select default(UserId),default(UserName) from DemoTable803 limit 1;

This will produce the following output -

+-----------------+-------------------+
| default(UserId) | default(UserName) |
+-----------------+-------------------+
| 101             | Chris             |
+-----------------+-------------------+
1 row in set (0.00 sec)
raja
Published on 09-Sep-2019 12:40:32
Advertisements