Home >Database >Mysql Tutorial >How to Add a NOT NULL Constraint to an Existing Column in MySQL?
Adding NOT NULL Constraint to an Existing MySQL Column
You have a table named "Person" with columns P_Id (int), LastName (varchar), and FirstName (varchar). You realize that you omitted a NOT NULL constraint on the P_Id column and attempt to add it using the queries provided, but encounter a syntax error.
The correct syntax for adding a NOT NULL constraint to an existing column in MySQL is through the ALTER TABLE... MODIFY... statement. Here's the modified query:
<code class="sql">ALTER TABLE Person MODIFY P_Id INT(11) NOT NULL;</code>
Note that you need to specify the full column definition, including the data type and any existing attributes, such as a DEFAULT value or column comment. This prevents potential loss of data or column metadata.
The safest way to retrieve the complete column definition is to use the SHOW CREATE TABLE query:
<code class="sql">SHOW CREATE TABLE Person;</code>
Then, modify the output to include the NOT NULL constraint and paste it into your ALTER TABLE... MODIFY... query. This ensures that you do not inadvertently remove any existing column definitions.
The above is the detailed content of How to Add a NOT NULL Constraint to an Existing Column in MySQL?. For more information, please follow other related articles on the PHP Chinese website!