SQL Primary Key Tutorial
Example Table
We will create a table named employees
to demonstrate the SQL Primary Key constraint:
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
department VARCHAR(50)
);
Creating the Table
To create the table, use the following SQL command:
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
department VARCHAR(50)
);
Result:
Command | CREATE TABLE employees (employee_id INT PRIMARY KEY, first_name VARCHAR(50), last_name VARCHAR(50), department VARCHAR(50)); |
---|---|
Result |
|
Inserting Data
To insert data into the table, use the following SQL command:
INSERT INTO employees (employee_id, first_name, last_name, department)
VALUES (1, 'John', 'Doe', 'HR');
Result:
Command | INSERT INTO employees (employee_id, first_name, last_name, department) VALUES (1, 'John', 'Doe', 'HR'); |
---|---|
Result |
|
Attempting to Insert Duplicate Primary Key
If you try to insert a duplicate value into the primary key column, you will get an error:
INSERT INTO employees (employee_id, first_name, last_name, department)
VALUES (1, 'Jane', 'Smith', 'Finance');
Result:
Command | INSERT INTO employees (employee_id, first_name, last_name, department) VALUES (1, 'Jane', 'Smith', 'Finance'); |
---|---|
Result |
|
Important Considerations
When using the Primary Key constraint, consider the following:
- Primary keys must contain unique values.
- A table can have only one primary key, which may consist of single or multiple columns.
- Primary keys ensure that each record in the table is unique and can be identified uniquely.