What happens when we apply NOT NULL constraint, with ALTER TABLE statement, to a column contains NULL values?

MySQLMySQLi Database

In this case, MySQL will return an error message regarding data truncated for the column. Following is an example of demonstrating it −

Example

Suppose we have a table ‘test2’ which contains a NULL value in column ‘ID’ at 2nd row. Now, if we will try to declare the column ID to NOT NULL then MySQL will return the error as follows −

mysql> Select * from test2;
+------+--------+
| ID   | Name   |
+------+--------+
| 1    | Gaurav |
| NULL | Rahul  |
+------+--------+
2 rows in set (0.00 sec)
mysql> ALTER TABLE TEST2 MODIFY ID INT NOT NULL;
ERROR 1265 (01000): Data truncated for column 'ID' at row 2
raja
Published on 16-Feb-2018 11:54:58
Advertisements