How can we apply a NOT NULL constraint to a column of an existing MySQL table?



We can apply the NOT NULL constraint to a column of an existing MySQL table with the help of ALTER TABLE statement. 

Syntax

ALTER TABLE table_name MODIFY colum_name datatype NOT NULL; 

Example

mysql> Create table test123(ID INT, Date DATE); Query OK, 0 rows affected (0.19 sec) mysql> Describe test123; +-------+---------+------+-----+---------+-------+ | Field | Type    | Null | Key | Default | Extra | +-------+---------+------+-----+---------+-------+ | ID    | int(11) | YES  |     | NULL    |       | | Date  | date    | YES  |     | NULL    |       | +-------+---------+------+-----+---------+-------+ 2 rows in set (0.04 sec) mysql> ALTER TABLE test123 MODIFY ID INT NOT NULL; Query OK, 0 rows affected (0.54 sec) Records: 0  Duplicates: 0  Warnings: 0 mysql> Describe test123; +-------+---------+------+-----+---------+-------+ | Field | Type    | Null | Key | Default | Extra | +-------+---------+------+-----+---------+-------+ | ID    | int(11) | NO   |     | NULL    |       | | Date  | date    | YES  |     | NULL    |       | +-------+---------+------+-----+---------+-------+ 2 rows in set (0.06 sec)
Updated on: 2020-06-19T11:27:51+05:30

452 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements