TestingDocs.com
Software Testing website
  • Automation
    • Selenium
    • JBehave Framework
  • Tutorials
    • MySQL Tutorials
    • Testlink
    • Maven
    • Git
  • IDEs
    • IntelliJ IDEA
    • Eclipse
  • Flowcharts
    • Flowgorithm
    • Raptor
  • About

MySQL

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

 

ADD PRIMARY KEY

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)

ADD PRIMARY KEY Example

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/

Related Posts

DataGrip Desktop Shortcut

MySQL /

Launch DataGrip on Windows

DataGrip Download

MySQL /

Install DataGrip IDE on Windows 11

MySQL Workbench Windows 11

MySQL /

New MySQL Connection in Workbench

MySQL Command-line Client

MySQL /

Command-Line MySQL Client

Start MySQL Client

MySQL /

Start MySQL Client on Windows 11

‹ MySQL DROP INDEX Statement› MySQL SHOW CREATE VIEW Statement

Recent Posts

  • MS Access Data Types
  • Install RAPTOR Avalonia on CentOS
  • Download RAPTOR Avalonia Edition on Windows
  • npm doctor command
  • Build & Run CLion Project
  • Create New CLion C Project on Windows
  • Configure CLion Toolchains on Windows
  • Launch CLion IDE on Windows
  • Activate CLion IDE
  • CLion IDE for C/C++ Development

Back to Top

Links

  • Contact
  • Privacy Policy
  • Cookie Policy

www.TestingDocs.com

Go to mobile version