In MySQL, a primary key is a constraint that uniquely identifies each record (row) in a table. It ensures that the values in the Primary key are unique and not null.
The primary key constraint is crucial for maintaining data integrity and allows for efficient querying and indexing of the table.
CREATE TABLE tableName ( columnName1 data_type PRIMARY KEY, columnName2 data_type, );
CREATE TABLE tableName ( columnName1 data_type, columnName2 data_type, PRIMARY KEY (columnName1, columnName2) );
we can modify the table column ADD PRIMARY KEY using the ALTER TABLE Command.
ALTER TABLE tableName ADD PRIMARY KEY (columnName);
we can remove a primary key from an existing table using the DROP PRIMARY KEY statement.
ALTER TABLE products DROP PRIMARY KEY;
In the below example, we have created the `products` table using CREATE TABLE command.
CREATE TABLE products ( product_id INT PRIMARY KEY, product_name VARCHAR(50), product_added_date DATE, product_code INT, product_description VARCHAR(200), product_price INT );
The `products` table is created with columns `product_id`, `product_name`, `product_code`, `product_description`, `product_price` and `product_added_date`.
The `product_id` column is declared as the primary key for the table using the PRIMARY KEY constraint in the Table.
The primary key constraint ensures that each `product_id` value must be unique across all rows in the table and can not be a NULL value.
We can also create a composite primary key using multiple columns in Table.
CREATE TABLE catalog ( catalog_id INT, product_id INT, PRIMARY KEY (catalog_id, product_id) );
The above combination of "catalog_id" and "product_id" forms the composite primary key, and each combination of these two values must be unique in the table.
The below command will fail because the primary key value cannot be a NULL value.
INSERT INTO products (product_id, product_name, product_description, product_added_date, product_code, product_price) VALUES (NULL, 'Ipad', 'Newly Arrival Smart iPad', '2023-01-01', 123, 400);
The below command will get succeed because we have added a unique value in Primary Key.
INSERT INTO products (product_id, product_name, product_description, product_added_date, product_code, product_price) VALUES ("A101", 'Ipad', 'Newly Arrival Smart iPad', '2023-01-01', 123, 400);
The below command will fail because we are adding a duplicate value in the Primary Key.
INSERT INTO products (product_id, product_name, product_description, product_added_date, product_code, product_price) VALUES ("A101", 'Ipad', 'Newly Arrival Smart iPad', '2023-01-01', 123, 400);