Home > Database > Mysql Tutorial > body text

How to modify a MySQL column to allow NULL?

王林
Release: 2023-08-25 16:13:16
forward
1532 people have browsed it

如何修改 MySQL 列以允许 NULL?

For our example, let's create a table with a NOT NULL constraint. After that, we'll modify a column to allow NULL.

The following is the query to create a table with NOT NULL constraints.

mysql> create table AllowNullDemo
   -> (
   -> id int not null
   -> );
Query OK, 0 rows affected (0.48 sec)=
Copy after login

Use the INSERT command to insert records. The query is as follows.

mysql> insert into AllowNullDemo values();
Query OK, 1 row affected, 1 warning (0.19 sec)

mysql> insert into AllowNullDemo values();
Query OK, 1 row affected, 1 warning (0.15 sec)
Copy after login

Display recorded query.

mysql> select *from AllowNullDemo;
Copy after login
Copy after login

This is the output result. Since we did not add any value when using the INSERT command above, the value 0 is displayed.

+----+
| id |
+----+
|  0 |
|  0 |
+----+
2 rows in set (0.00 sec)
Copy after login

This is the syntax that allows NULL values.

alter table yourTableName  modify column yourColumnName datatype;
Copy after login

Apply the above syntax to modify the column to allow NULL. The query is as follows.

mysql> alter table AllowNullDemo modify column id int;
Query OK, 0 rows affected (1.59 sec)
Records: 0  Duplicates: 0  Warnings: 0
Copy after login

After executing the above query, you can insert a NULL value into the column because the column has been successfully modified in the above operation.

mysql>  insert into AllowNullDemo values();
Query OK, 1 row affected (0.15 sec)
Copy after login

Display records to check if the last inserted value is NULL.

mysql> select *from AllowNullDemo;
Copy after login
Copy after login

The following is the output, where NULL values ​​are now visible.

+------+
| id   |
+------+
|    0 |
|    0 |
| NULL |
+------+
3 rows in set (0.00 sec)
Copy after login

Using the above method, we can easily modify the MySQL column to allow NULL.

The above is the detailed content of How to modify a MySQL column to allow NULL?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
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
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!