Primary Key in SQL
A primary key is a column or a set of columns in a database table that uniquely identifies each row in that table. It serves as a unique identifier for each record, ensuring that no duplicate values exist within the column(s).
The primary key has the following characteristics:
Uniqueness: The values in the primary key column(s) must be unique for each row in the table. No two rows can have the same value for the primary key.
Non-null: The primary key column(s) cannot contain NULL values. Every row must have a valid value for the primary key.
Immutable: The values in the primary key column(s) should not change over time. Once a primary key is assigned to a row, it should remain constant.
Primary keys are used for several purposes:
Uniquely identify each row in a table
Enforce data integrity by preventing duplicate values
Improve query performance by providing an efficient way to locate specific rows
Serve as a reference for foreign keys in other tables
The primary key is crucial for the integrity and efficient management of the database. It allows for fast searching, indexing, and ensuring that there are no duplicate records in the table.
In summary:
Primary keys uniquely identify each row in a table and cannot contain duplicate or NULL values.
Unique keys prevent duplicate values and allow NULL values, making them suitable for situations where NULL values are permitted.
Here’s an example of creating a primary key in SQL:
CREATE TABLE Artist (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
In this example, the id
column is defined as the primary key, ensuring that it uniquely identifies each row in the Artist
table and does not allow NULL values. The name
column is defined as NOT NULL, but it’s not the primary key, so it can still contain NULL values if necessary.