Home > Database > Mysql Tutorial > body text

How to Add a NOT NULL Constraint to an Existing Column in MySQL?

Mary-Kate Olsen
Release: 2024-11-05 11:05:02
Original
726 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!