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

How to set primary key constraints in mysql

WBOY
Release: 2023-05-31 18:34:06
forward
1849 people have browsed it

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)
Copy after login

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!

Related labels:
source:yisu.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