Site icon TestingDocs.com

MySQL ADD PRIMARY KEY clause

Overview

In this tutorial, we will learn about ADD PRIMARY KEY clause in MySQL. A primary key or just key is a column or set of columns in a table that can uniquely identify a row within the table. To add a primary key a table, we can use the ALTER TABLE with the clause, and the name of the columns.

Syntax

The general syntax for the statement is a follows:

ALTER TABLE <table_name> ADD PRIMARY KEY <index_name> (index_columns)

Example

Let’s look the primary key constraint to a sample demo table.  The table structure is shown below:

mysql> DESC keydemo;
+——-+————-+——+—–+———+——-+
| Field | Type | Null | Key | Default | Extra |
+——-+————-+——+—–+———+——-+
| ID | int | NO | | NULL | |
| FName | varchar(50) | NO | | | |
| LName | varchar(50) | NO | | | |
+——-+————-+——+—–+———+——-+
3 rows in set (0.00 sec)

 

mysql> ALTER TABLE keydemo ADD PRIMARY KEY pri_key (ID);

Query OK, 0 rows affected (0.22 sec)
Records: 0 Duplicates: 0 Warnings: 0

 

Issue the DESCRIBE statement on the table.

mysql> DESC keydemo;

+——-+————-+——+—–+———+——-+
| Field | Type | Null | Key | Default | Extra |
+——-+————-+——+—–+———+——-+
| ID | int | NO | PRI | NULL | |
| FName | varchar(50) | NO | | | |
| LName | varchar(50) | NO | | | |
+——-+————-+——+—–+———+——-+
3 rows in set (0.03 sec)

Notice that the ID is the primary key for the table.

MySQL Tutorials

MySQL Tutorials on this website:

https://www.testingdocs.com/mysql-tutorials-for-beginners/

For more information on MySQL Database:

https://www.mysql.com/

Exit mobile version