Primary Key in SQL
Primary Key in SQL
A Primary Key is a column or a set of columns in a table that uniquely identifies each row in that table. It ensures uniqueness and non-nullability for the key columns.
Key Features of Primary Key:
Uniquely identifies each record.
Cannot contain NULL values.
Only one primary key per table.
Often used as a reference by foreign keys in other tables.
How to Define a Primary Key
1. While Creating a Table:
CREATE TABLE employees ( employee_id INT PRIMARY KEY, name VARCHAR(100), department VARCHAR(50));2. Using Composite Primary Key (multiple columns):
CREATE TABLE orders ( order_id INT, product_id INT, quantity INT, PRIMARY KEY (order_id, product_id));3. Add Primary Key to Existing Table:
ALTER TABLE employeesADD PRIMARY KEY (employee_id);Example
CREATE TABLE users ( user_id INT PRIMARY KEY, username VARCHAR(50) NOT NULL, email VARCHAR(100));Notes:
Primary key automatically creates a unique index.
You cannot insert duplicate or NULL values in the primary key column(s).
If you try to add a primary key on columns with duplicates or NULLs, it will fail.
Want help with foreign keys, or auto-increment primary keys?