Home  >  Article  >  Database  >  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
WBOYforward
2023-09-04 23:33:101321browse

我们如何将 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); 

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) 

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);

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!

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