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


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

Updated on: 19-Jun-2020

161 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements