Table of Contents
ToggleA Primary Key in SQL is a column (or combination of columns) that uniquely identifies each record in a database table. It ensures that no two rows in the table have the same value for this column, which guarantees data integrity and supports efficient data retrieval.
Below is an example of how to create a table with a Primary Key constraint on a column in SQL:
CREATE TABLE CUSTOMERS (
ID INT NOT NULL,
NAME VARCHAR(20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(25),
SALARY DECIMAL(18, 2),
PRIMARY KEY (ID)
);
When we try to insert a duplicate value into the Primary Key column, SQL will prevent it:
INSERT INTO CUSTOMERS VALUES (3, 'Kaushik', 23, 'Kota', 2000.00); -- This works
INSERT INTO CUSTOMERS VALUES (3, 'Chaitali', 25, 'Mumbai', 6500.00); -- This generates an error
| ID | Name | Age | Address | Salary |
|---|---|---|---|---|
| 3 | Kaushik | 23 | Kota | 2000.00 |
| 3 | Chaitali | 25 | Mumbai | 6500.00 |
If you need to drop the Primary Key constraint from a column, you can use the following SQL statement:
ALTER TABLE CUSTOMERS DROP PRIMARY KEY;
Once the Primary Key is dropped, duplicate values are allowed in the column, as shown below:
INSERT INTO CUSTOMERS VALUES
(3, 'Chaitali', 25, 'Mumbai', 6500.00),
(3, 'Hardik', 27, 'Bhopal', 8500.00),
(3, 'Komal', 22, 'Hyderabad', 4500.00),
(3, 'Muffy', 24, 'Indore', 10000.00);
