There are several types of keys that you can use to define relationships between tables and optimize database performance.
1. Primary Key:
A primary key uniquely identifies each record in a table. It must contain unique values and cannot be NULL.
2. Foreign Key:
A foreign key is a field in one table that refers to the primary key in another table. It establishes a relationship between two tables.
3. Unique Key:
A unique key ensures that all values in a column or a set of columns are unique.
A table can have multiple unique keys.
4. Composite Key:
A composite key is a combination of two or more columns that uniquely identify a record in a table.
CREATE TABLE orders (
order_id INT,
product_id INT,
customer_id INT,
PRIMARY KEY (order_id, product_id)
);
In this example, the orders table has a composite primary key consisting of two columns: order_id and product_id. This means that each combination of order_id and product_id must be unique within the table.
CREATE TABLE sales (
sale_id INT,
product_id INT,
store_id INT,
sale_date DATE,
UNIQUE KEY (product_id, store_id)
);
In this example, the sales table has a composite unique key consisting of product_id and store_id. This ensures that each combination of product_id and store_id is unique in the table, but it's not the primary key.
5. Super Key:
A super key refers to either a single key or a combination of multiple keys that have the capability to uniquely identify tuples within a table.
6. Candidate Key:
A candidate key is a column or a combination of columns that uniquely identifies each row in a table.
7. Alternate keys:
Alternate keys are those candidate keys which are not the Primary key.