Home > Database > Mysql Tutorial > How can we apply PRIMARY KEY constraints to fields of existing MySQL table?

How can we apply PRIMARY KEY constraints to fields of existing MySQL table?

WBOY
Release: 2023-09-04 23:33:10
forward
1393 people have browsed it

我们如何将 PRIMARY KEY 约束应用于现有 MySQL 表的字段?

We can apply PRIMARY KEY constraints to columns of existing MySQL tables with the help of ALTER TABLE statement.

Syntax

ALTER TABLE table_name MODIFY colum_name datatype PRIMARY KEY;
                 OR
ALTER TABLE table_name ADD PRIMARY KEY (colum_name); 
Copy after login

Suppose we have a table named 'Player', and we want to add PRIMARY KEY constraints to the column 'ID', then this can be achieved through the ALTER TABLE command, as follows Shown:

mysql> DESCRIBE Player;

+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| ID    |  int(11)    | YES  |     | NULL    |       |
| Name  | varchar(20) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+

2 rows in set (0.04 sec)
mysql> ALTER TABLE Player MODIFY ID INT PRIMARY KEY;
Query OK, 0 rows affected (0.22 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> DESCRIBE Player;

+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| ID    |  int(11)    | NO   | PRI | NULL    |       |
| Name  | varchar(20) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+

2 rows in set (0.04 sec) 
Copy after login

As can be observed from the above result set, MySQL adds a PRIMARY KEY constraint to the field 'ID'. We can also add PRIMARY KEY constraints using the following query statement:

 Alter table Player ADD PRIMARY KEY(ID);
Copy after login

The above is the detailed content of How can we apply PRIMARY KEY constraints to fields of existing MySQL 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