Home > Database > Mysql Tutorial > body text

What is MySQL NOT NULL constraint and how can we declare a field NOT NULL while creating a table?

王林
Release: 2023-09-04 10:05:02
forward
831 people have browsed it

什么是 MySQL NOT NULL 约束以及我们如何在创建表时声明字段 NOT NULL?

In fact, the MySQL NOT NULL constraint restricts a column of the table to have a NULL value. Once we apply NOT NULL constraint on a column, then we cannot pass null values ​​to that column. It cannot be declared on the entire table, in other words we can say NOT NULL is a column level constraint.

In order to declare a field NOT NULL, we must use the NOT NULL keyword when defining the column in the CREATE TABLE statement.

Example

mysql> Create table Employee(ID Int NOT NULL, First_Name Varchar(20), Last_name Varchar(20), Designation Varchar(15));
Query OK, 0 rows affected (0.59 sec)
Copy after login

In the above query, we have applied NOT NULL constraint on the "ID" field of the "Employee" table. The 'ID' column cannot now take NULL values. You can also check from the DESCRIBE statement that the ID field cannot accept NULL values.

mysql> DESCRIBE Employee123\G
*************************** 1. row ***************************
  Field: ID
   Type: int(11)
   Null: NO
    Key:
Default: NULL
  Extra:
*************************** 2. row ***************************
  Field: First_Name
   Type: varchar(20)
   Null: YES
    Key:
Default: NULL
  Extra:
*************************** 3. row ***************************
  Field: Last_name
   Type: varchar(20)
   Null: YES
    Key:
Default: NULL
  Extra:
*************************** 4. row ***************************
  Field: Designation
   Type: varchar(15)
   Null: YES
    Key:
Default: NULL
  Extra:
4 rows in set (0.03 sec)
Copy after login

The above is the detailed content of What is MySQL NOT NULL constraint and how can we declare a field NOT NULL while creating a table?. 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!