Home >Database >Mysql Tutorial >How to set primary key constraints in mysql

How to set primary key constraints in mysql

WBOY
WBOYforward
2023-05-31 18:34:061850browse

Instructions

1. Use the UNIQUE keyword to specify unique constraints directly after defining the column.

The difference between UNIQUE and PRIMARY KEY: A table can have multiple fields declared as UNIQUE, but there can only be one PRIMARY KEY declaration.

2. Columns declared as PRIMAY KEY do not allow null values, but fields declared as UNIQUE allow null values.

Example

mysql> CREATE TABLE demo_department
    -> (
    -> id INT(11) PRIMARY KEY,
    -> name VARCHAR(22) UNIQUE,
    -> location VARCHAR(50)
    -> );
Query OK, 0 rows affected (0.37 sec)
mysql> DESC demo_department;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| id       | int(11)     | NO   | PRI | NULL    |       |
| name     | varchar(40) | YES  | UNI | NULL    |       |
| location | varchar(50) | YES  |     | NULL    |       |
+----------+-------------+------+-----+---------+-------+
3 rows in set (0.08 sec)

The above is the detailed content of How to set primary key constraints in mysql. For more information, please follow other related articles on the PHP Chinese website!

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