How do I set the default value for a column in MySQL?


To set the default value, use the DEFAULT keyword.

Let us first create a table −

mysql> create table DemoTable758 (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   FirstName varchar(100)
);
Query OK, 0 rows affected (0.66 sec)

Following is the query to set default value for a column −

mysql> alter table DemoTable758 add column Colors ENUM('RED','GREEN','BLUE','ORANGE','YELLOW') DEFAULT 'YELLOW';
Query OK, 0 rows affected (0.44 sec)
Records: 0 Duplicates: 0 Warnings: 0

Let us check the description of table once again −

mysql> desc DemoTable758;

This will produce the following output -

+-----------+----------------------------------------------+------+-----+---------+----------------+
| Field     | Type                                         | Null | Key | Default | Extra          |
+-----------+----------------------------------------------+------+-----+---------+----------------+
| Id        | int(11)                                      | NO   | PRI | NULL    | auto_increment |
| FirstName | varchar(100)                                 | YES  |     | NULL    |                |
| Colors    | enum('RED','GREEN','BLUE','ORANGE','YELLOW') | YES  |     | YELLOW  |                |
+-----------+----------------------------------------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

Insert some records in the table using insert command. Here, we haven’t inserted the value for 2nd column with FirstName “John”. The default value “YELLOW” will get placed there −

mysql> insert into DemoTable758(FirstName) values('John');
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable758(FirstName,Colors) values('Carol','RED');
Query OK, 1 row affected (0.17 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable758;

This will produce the following output -

+----+-----------+--------+
| Id | FirstName | Colors |
+----+-----------+--------+
|  1 | John      | YELLOW |
|  2 | Carol     | RED    |
+----+-----------+--------+
2 rows in set (0.00 sec)

Updated on: 03-Sep-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements