What is the use of DEFAULT constraint? How can it be applied to a column while creating a table?


DEFAULT constraint is used set a default value for a column in MySQL table. If it is applied on a column then it will take the default value of not giving any value for that column. Its syntax would be as follows −

Syntax

DEFAULT default_value

Here, default_value is the default value set for the column.

Example

The query below will create a table named workers where we assign the column id a DEFAULT value 1000.

mysql> Create table workers(Name Varchar(25), Id INT NOT NULL DEFAULT 1000);
Query OK, 0 rows affected (0.47 sec)

mysql> Insert into workers(Name, Id) values('Ram', 101);
Query OK, 1 row affected (0.04 sec)

mysql> Insert into workers(Name) values('Mohan');
Query OK, 1 row affected (0.10 sec)

mysql> Select * from Workers;

+-------+------+
| Name  | Id   |
+-------+------+
| Ram   | 101  |
| Mohan | 1000 |
+-------+------+

2 rows in set (0.00 sec)

The above result set stores the default value 1000 for id when we do not give any value for the same.

Updated on: 19-Jun-2020

54 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements