Junior
What is a primary key in databases?
sobes.tech AI
Answer from AI
A primary key is a column or a set of columns in a database table that uniquely identifies each row in that table.
Main characteristics:
- Uniqueness: Each value of the primary key must be unique within the table.
- Not null (NOT NULL): The primary key cannot contain a
NULLvalue. - Stability: It is desirable that the primary key values do not change.
Purpose:
- Ensuring data integrity (entity integrity).
- Establishing relationships between tables (foreign keys reference primary keys).
- Query optimization (often used for indexing).
Example of creating a table with a primary key in SQL:
CREATE TABLE Customers (
CustomerID int NOT NULL, -- Column for primary key
LastName varchar(255) NOT NULL,
FirstName varchar(255),
CONSTRAINT PK_Customer PRIMARY KEY (CustomerID) -- Defining primary key
);
A primary key can be composite, consisting of multiple columns:
CREATE TABLE OrderItems (
OrderID int NOT NULL,
ProductID int NOT NULL,
Quantity int,
CONSTRAINT PK_OrderItem PRIMARY KEY (OrderID, ProductID) -- Composite primary key
);
Auto-incrementing values for primary keys are often used (for example, auto-increment).
CREATE TABLE Products (
ProductID int NOT NULL IDENTITY(1,1), -- Auto-increment primary key
ProductName varchar(255) NOT NULL,
CONSTRAINT PK_Product PRIMARY KEY (ProductID)
);