What are the different types of keys in MySQL?
1. Primary Key: A primary key is a field in a table which uniquely identifies each row/record in a database table. Primary keys must contain unique values. For example:
CREATE TABLE Persons (
PersonID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (PersonID)
);
2. Unique Key: A unique key is a set of one or more than one fields/columns of a table that uniquely identify a record in a database table. Unique keys can accept only one null value and it cannot have duplicate values. For example:
CREATE TABLE Persons (
PersonID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
EmailID varchar(255) UNIQUE,
PRIMARY KEY (PersonID)
);
3. Foreign Key: A foreign key is a field in a table that is used to establish a link between two tables. It is used to reference the primary key of another table. For example:
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);
4. Composite Key: A composite key is a combination of two or more columns in a table that can be used to uniquely identify each row in the table. For example:
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int NOT NULL,
ProductID int NOT NULL,
PRIMARY KEY (OrderID, ProductID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);