
204 views
MySQL Primary Key
The MySQL primary key is a database constraint that enforces the uniqueness and integrity of data in a table. The primary key uniquely identifies each row (record) in a table and ensures that there are no duplicate values. Here are the key characteristics and guidelines for using primary keys in MySQL:
- Uniqueness: A primary key column (or combination of columns) must contain unique values across all rows in the table. This means that no two rows can have the same primary key value.
- Uniqueness Enforcement: MySQL enforces the uniqueness of the primary key values automatically. If you attempt to insert or update a row with a primary key value that already exists in the table, MySQL will generate an error.
- Null Values: A primary key column cannot contain
NULL
values. Each row in the table must have a non-null value in the primary key column. - Data Integrity: The primary key is used to establish relationships between tables through foreign keys. This relationship ensures data integrity and maintains referential integrity in the database.
- Physical Storage: MySQL uses the primary key to physically store and retrieve data efficiently. Rows in a table are stored and organized based on the primary key values.
- Primary Key Declaration: You can define a primary key when creating a table by using the
PRIMARY KEY
keyword. For example:
CREATE TABLE your_table (
id INT PRIMARY KEY,
name VARCHAR(255),
-- other columns
);
In this example, the id
column is defined as the primary key.
- Composite Primary Key: You can have a composite primary key by specifying multiple columns as the primary key. This enforces uniqueness based on the combination of values in these columns. For example:
CREATE TABLE your_table (
user_id INT,
product_id INT,
PRIMARY KEY (user_id, product_id),
-- other columns
);
- Auto-Increment Primary Key: You can define an auto-increment primary key, which generates unique values automatically as new rows are inserted. This is common for tables that require a unique identifier for each row, such as an ID or order number.
CREATE TABLE your_table (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
-- other columns
);
- Adding a Primary Key to an Existing Table: You can add a primary key to an existing table using the
ALTER TABLE
statement. For example:
ALTER TABLE your_table
ADD PRIMARY KEY (column_name);
Replace your_table
with the name of your table and column_name
with the name of the column you want to make the primary key.
Primary keys play a critical role in database design and ensure data integrity. They are essential for creating relationships between tables through foreign keys and for efficiently retrieving and organizing data.