MySQL Constraint – PRIMARY KEY
C# basic course click on: https://www.udemy.com/learn-csharp-with-sagar-jaybhay/
Web API 2-
.Net Core In depth In 5 Hours click on: https://www.udemy.com/web-api-2-net-core-in-depth-in-5-hrs-with-sagar-jaybhay/
Hello everyone
in the previous article we learn about MySQL Constraint – UNIQUE and in this
article, we will learn PRIMARY KEY constraint with example. Let’s go.
What is the
PRIMARY KEY?
MySQL
PRIMARY KEY constraint uniquely identifies each row in a table and also it
creates a unique index for accessing the table will access faster. The columns
of a Primary Key cannot have null values in MySQL and it must contain unique
values.
A
Primary key has only one on a table, if the primary key used with multiple
fields, then they are called a Composite Key.
Syntax 1 for creating PRIMARY KEY with CREATE
table statement.
CREATE
TABLE table_name (
column1_name data type ()
PRIMARY KEY,
column2_name data type () NOT NULL,
column3_name data type () NOT NULL
.
.
);
Syntax 2
CREATE
TABLE table_name (
column1_name data type (),
column2_name data type (),
PRIMARY KEY (column_name)
.
.
)
Example 1 for creating PRIMARY KEY with CREATE
table statement
CREATE
TABLE EMPLOYEE (
eID INT PRIMARY KEY,
eNAME VARCHAR (255) NOT NULL,
eAGE INT NOT NULL,
eADDRESS VARCHAR (255) NOT NULL
);
C# basic course click on: https://www.udemy.com/learn-csharp-with-sagar-jaybhay/
Web API 2-
.Net Core In depth In 5 Hours click on: https://www.udemy.com/web-api-2-net-core-in-depth-in-5-hrs-with-sagar-jaybhay/
Example 2
CREATE
TABLE EMPLOYEE (
eID INT AUTO_INCREMENT,
eNAME VARCHAR (255) NOT NULL,
eAGE INT NOT NULL,
eADDRESS VARCHAR (255) NOT NULL,
PRIMARY KEY (eID)
);
C# basic course click on: https://www.udemy.com/learn-csharp-with-sagar-jaybhay/
Web API 2-
.Net Core In depth In 5 Hours click on: https://www.udemy.com/web-api-2-net-core-in-depth-in-5-hrs-with-sagar-jaybhay/
You can add PRIMARY KEY
constraint when the table is already created using the ALTER TABLE statement.
Following is the syntax and example:
Syntax
ALTER TABLE table_name
ADD PRIMARY KEY (column_name)
Example
ALTER TABLE Employee
ADD PRIMARY KEY (eID);
If you want to drop created
a PRIMARY KEY constraint, then follow the steps:
Syntax
ALTER TABLE table_name
DROP PRIMARY KEY;
Example
ALTER TABLE Employee
DROP PRIMARY KEY;
C# basic course click on: https://www.udemy.com/learn-csharp-with-sagar-jaybhay/
Web API 2-
.Net Core In depth In 5 Hours click on: https://www.udemy.com/web-api-2-net-core-in-depth-in-5-hrs-with-sagar-jaybhay/
Comments
Post a Comment