Tutorialspoint

1 Answer
Sharon Christine

To update the constraint, use the MODIFY command. Following is the syntax −

alter table yourTableName modify yourExistingColumnName yourExistingDataType NOT NULL;  

Let us first create a table −

mysql> create table DemoTable
   -> (
   -> UserId int NOT NULL AUTO_INCREMENT,
   -> UserFirstName varchar(100),
   -> UserLastName varchar(100),
   -> UserEmailId varchar(100),
   -> UserPassword varchar(100),
   -> PRIMARY KEY(UserId)
   -> );
Query OK, 0 rows affected (0.91 sec)

Following is the query to change the constraint of a column to NOT NULL −

mysql> alter table DemoTable modify UserFirstName varchar(100) NOT NULL;
Query OK, 0 rows affected (2.13 sec)
Records: 0 Duplicates: 0 Warnings: 0

Let us use the desc command to check whether the column has NOT NULL constraint or not −

mysql> desc DemoTable;

This will produce the following output. Now the UserFirstName column has NOT NULL constraint −

+---------------+--------------+------+-----+---------+----------------+
| Field         | Type         | Null | Key | Default | Extra          |
+---------------+--------------+------+-----+---------+----------------+
| UserId        | int(11)      | NO   | PRI | NULL    | auto_increment |
| UserFirstName | varchar(100) | NO   |     | NULL    |                |
| UserLastName  | varchar(100) | YES  |     | NULL    |                |
| UserEmailId   | varchar(100) | YES  |     | NULL    |                |
| UserPassword  | varchar(100) | YES  |     | NULL    |                |
+---------------+--------------+------+-----+---------+----------------+
5 rows in set (0.17 sec)

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.