Add constraints to the fields in the data table

Add unique constraint

The unique constraint (Unique Constraint)requires the column to be unique and it is allowed to be empty, but there can only be one null value. The unique constraint can ensure that there are no duplicate values ​​in one or several columns.

The department name that defines the department table is unique, and the SQLsentence is as follows: keyword UNIQUE.

CREATE TABLE t_dept(    id INT PRIMARY KEY,    name VARCHAR(22) UNIQUE,    location VARCHAR(50))

Add non-empty constraint

Keywords:NOT NULL ;

E.g:

CREATE TABLE t_dept(    id INT PRIMARY KEY,    name VARCHAR(22) NOT NULL,    location VARCHAR(50))

Add default constraints

Default constraint: Give the field a default value. Keywords:DEFAULT ;

E.g:

CREATE TABLE t_emp(    id INT PRIMARY KEY,    name VARCHAR(22),    sex VARCHAR(2) DEFAULT '男') DEFAULT CHARSET=utf8;

note:

  • If it is to add a string type default value, use single quotation marks, if it is an integer type, you do not need to add any symbols;
  • If you want to add the Chinese default value, you need to add DEFAULT CHARSET=utf8;English characters, but you don’t need it.

Set the attribute value of the table to increase automatically

In database applications, there is often a requirement that every time a new record is inserted, the system automatically generates the primary key value of the field, namely:

id name
1 Zhang San
2 Li Si
ID automatically increases by one every time Name
XXX
10 XXX

Keywords:, the AUTO_INCREMENTinitial value and increment are both by default 1.

E.g:

CREATE TABLE t_tmp(    id int PRIMARY KEY AUTO_INCREMENT,    name VARCHAR(32))

Guess you like

Origin blog.csdn.net/qq_45783660/article/details/114704345