A PRIMARY KEY uniquely identifies each row in a table. It enforces both NOT NULL
and UNIQUE
constraints on the column(s) itβs defined on.
You can declare a primary key when creating a table or add it later:
-- Inline definition during CREATE CREATE TABLE users ( user_id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50) NOT NULL, email VARCHAR(100) ); -- Separate constraint declaration CREATE TABLE orders ( order_id INT AUTO_INCREMENT, customer_id INT, order_date DATE, PRIMARY KEY (order_id) );
A composite key uses multiple columns to ensure uniqueness:
CREATE TABLE enrollment ( student_id INT, course_id INT, enrolled_on DATE, PRIMARY KEY (student_id, course_id) );
Add or drop a primary key on an existing table:
-- Add primary key ALTER TABLE products ADD PRIMARY KEY (sku); -- Drop primary key ALTER TABLE products DROP PRIMARY KEY;
AUTO_INCREMENT
integer for simple, single-column keys.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!