Primary Key in SQL

sql primary key guide
01 December 2024

In the world of databases, data management as a unique entity is of great importance. One of the fundamental concepts that helps us ensure our data is organized and that we can easily access it is the Primary Key. The Primary Key is a design element that ensures each row in our database table is unique and there are no duplicates in them.

The Primary Key is typically composed of one or several columns so that each record can be identified uniquely. For example, if you have a table that stores information about employees of a company, there could be an employee number that uniquely identifies each employee based on a specific attribute that acts as the Primary Key.

It is essential that the columns chosen as the Primary Key must have non-duplicate and non-null values. This means that there shouldn't be a case where the value of these columns is empty (or Null) and no two rows should have the same value in these columns.

Using Primary Keys in data tables helps us prevent duplicate entries and protects against redundant data. Moreover, this feature is useful in improving the speed of data queries and accessing data efficiently, as the database management system can retrieve records based on the Primary Key.

Now let’s take a simple example of how to define a Primary Key in SQL:


CREATE TABLE Employees (
    EmployeeID INT PRIMARY KEY,
    FirstName VARCHAR(50),
    LastName VARCHAR(50),
    DateOfBirth DATE
);

Line One: Using the CREATE TABLE statement to create a new table named Employees.
Line Two: Defining the column EmployeeID with a data type of INT and designating it as PRIMARY KEY which prevents duplicates.
Line Three: Adding the column FirstName with a data type of VARCHAR and a length of 50 characters for storing first names.
Line Four: Adding the column LastName with a data type of VARCHAR and a length of 50 characters for storing family names.
Line Five: Defining the column DateOfBirth with a data type of DATE to record individuals' birth dates.

FAQ

?

What is the purpose of the Primary Key in SQL?

?

Can there be more than one Primary Key in a table?

?

Can a Primary Key have a Null value?