Home >Database >Mysql Tutorial >What is MySQL NOT NULL constraint and how can we declare a field NOT NULL while creating a table?

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

王林
王林forward
2023-09-04 10:05:02900browse

什么是 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)

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)

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete