MySQL FAQs
FAQs Categories
Client Server Commands
Database Structure
Table Types or Storage Engines
Indexes
SQL Statements
Table Joins
Funtions and Operators
Tricky Select Queries
Speed Up Queries
Data Back Up
General Questions
Errors
1PLs Company - #1Payday.Loans Agency - Loans online and near me $100-$2500 (Same Day)
Powered by MySQL
 
Home / Indexes / Primary Key Indexes / Question No: 147

How to create primary key index in MySQL?

I want to know methods to create PRIMARY KEY INDEX. How to create primary key indexes in MySQL?

Answer No: 147

The primary keys are almost always added when creating the table. However, MySQL provides more than one SQL statements to create primary key indexes. You can use them as per your requirement.

Syntax to create primary key index when creating a table

CREATE TABLE tablename ( [...], PRIMARY KEY (columns_to_index) );
Take an example:
CREATE TABLE buyers ( 
buyer_id INT NOT NULL AUTO_INCREMENT,
first_name CHAR(19) NOT NULL,
last_name CHAR(19) NOT NULL,
age SMALLINT NOT NULL,
postal_code SMALLINT NOT NULL,
PRIMARY KEY (buyer_id)
);
It can also be added by altering the table like
ALTER TABLE tablename ADD PRIMARY KEY (columns_to_index);
Take an example:
ALTER TABLE buyers ADD PRIMARY KEY (buyer_id);

Note: only one primary key can be added in a table.

Related MySQL FAQs to the Above FAQ

How-to-create-multi-column-primary-key-index-in-MySQL How to create multi column primary key index in MySQL?

About FAQs: Recently Added FAQs

About MySQL FAQs: Site Map | Bookmark Us | Recommend this Site to Your Friend | Contact Us

Useful Links: Wikipedia.org | Oracle.com | w3schools.com | www.php.net | Github.com

© 2024  www.mysqlfaqs.net
All rights reserved.