Adding a column whose value is not null by default in MySQL?

MySQLMySQLi Database

For this, you need to remove the default keyword. The syntax is as follows:

ALTER TABLE yourTableName ADD COLUMN yourColumnName dataType NOT NULL AFTER yourColumnName;

To understand the above syntax, let us create a table. The query to create a table is as follows:

mysql> create table AddingColumnDefaultValueNOTNULL
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> FirstName varchar(20),
   -> LastName varchar(20),
   -> Age int,
   -> Address varchar(100),
   -> Salary int,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.58 sec)

Now check the description of table. The query is as follows:

mysql> desc AddingColumnDefaultValueNOTNULL;

The following is the output:

+-----------+--------------+------+-----+---------+----------------+
| Field     | Type         | Null | Key | Default | Extra          |
+-----------+--------------+------+-----+---------+----------------+
| Id        | int(11)      | NO   | PRI | NULL    | auto_increment |
| FirstName | varchar(20)  | YES  |     | NULL    |                |
| LastName  | varchar(20)  | YES  |     | NULL    |                |
| Age       | int(11)      | YES  |     | NULL    |                |
| Address   | varchar(100) | YES  |     | NULL    |                |
| Salary    | int(11)      | YES  |     | NULL    |                |
+-----------+--------------+------+-----+---------+----------------+
6 rows in set (0.11 sec)

Here is the query to add a column whose value is NOT NULL by default:

mysql> alter table AddingColumnDefaultValueNOTNULL add column City varchar(20) NOT NULL after Age;
Query OK, 0 rows affected (2.17 sec)
Records: 0 Duplicates: 0 Warnings: 0

Now you can check the description of the table once again. The table will have one new column which has the name ‘City’, whose default value NOT NULL by default.

The query to check the description of table is as follows:

mysql> desc AddingColumnDefaultValueNOTNULL;

The following is the output:

+-----------+--------------+------+-----+---------+----------------+
| Field     | Type         | Null | Key | Default | Extra          |
+-----------+--------------+------+-----+---------+----------------+
| Id        | int(11)      | NO   | PRI | NULL    | auto_increment |
| FirstName | varchar(20)  | YES  |     | NULL    |                |
| LastName  | varchar(20)  | YES  |     | NULL    |                |
| Age       | int(11)      | YES  |     | NULL    |                |
| City      | varchar(20)  | NO   |     | NULL    |                |
| Address   | varchar(100) | YES  |     | NULL    |                |
| Salary    | int(11)      | YES  |     | NULL    |                |
+-----------+--------------+------+-----+---------+----------------+
7 rows in set (0.02 sec)

Look at the City field. In NULL column the value is NO. This itself says that we cannot set NULL value to City field.

raja
Published on 27-Feb-2019 07:00:22
Advertisements