[mysql] How to add not null constraint to existing column in MySQL

I have table name called "Person" with following column names

P_Id(int),
LastName(varchar),
FirstName (varchar).

I forgot to give NOT NULL Constraint to P_Id.

Now I tried with following query to add NOT NULL Constraint to existing column called P_Id,

1. ALTER TABLE  Person MODIFY  (P_Id NOT  NULL);
2. ALTER TABLE Person ADD CONSTRAINT NOT  NULL NOT NULL (P_Id);

I am getting syntax error....

This question is related to mysql constraints

The answer is


Try this, you will know the difference between change and modify,

ALTER TABLE table_name CHANGE curr_column_name new_column_name new_column_datatype [constraints]

ALTER TABLE table_name MODIFY column_name new_column_datatype [constraints]
  • You can change name and datatype of the particular column using CHANGE.
  • You can modify the particular column datatype using MODIFY. You cannot change the name of the column using this statement.

Hope, I explained well in detail.


Would like to add:

After update, such as

ALTER TABLE table_name modify column_name tinyint(4) NOT NULL;

If you get

ERROR 1138 (22004): Invalid use of NULL value

Make sure you update the table first to have values in the related column (so it's not null)