Databases

How do I set up a primary key?

Updated 2026-08-14

Quick answer

To set up a primary key, define the column(s) that will uniquely identify each row in your table using the appropriate SQL command or database management tool.

Setting up a primary key is essential for maintaining data integrity in relational databases.

Steps

  1. 1

    MySQL

    Use the command: ALTER TABLE table_name ADD PRIMARY KEY (column_name); or define it during table creation with CREATE TABLE table_name (column_name INT PRIMARY KEY);

  2. 2

    PostgreSQL

    Use: ALTER TABLE table_name ADD CONSTRAINT constraint_name PRIMARY KEY (column_name); or define it in the CREATE TABLE statement.

  3. 3

    SQL Server

    Use: ALTER TABLE table_name ADD CONSTRAINT constraint_name PRIMARY KEY (column_name); or specify PRIMARY KEY in the CREATE TABLE syntax.

  4. 4

    Oracle

    Use: ALTER TABLE table_name ADD CONSTRAINT constraint_name PRIMARY KEY (column_name); or define it in the CREATE TABLE statement.

Understanding Primary Keys

A primary key is a unique identifier for a record in a database table. It ensures that no two rows have the same key value.

Platform-Specific Steps

Steps to set up a primary key may vary depending on the database system you are using.

Common Issues

Ensure that the column(s) designated as primary keys do not contain NULL values and are unique.

Watch out for

  • Primary keys must always contain unique values and cannot be NULL.
  • Changing a primary key can affect foreign key relationships.

FAQ

Can a primary key be composed of multiple columns?

Yes, a primary key can consist of multiple columns, known as a composite key, to uniquely identify a record.

What happens if I try to insert a duplicate key?

Inserting a duplicate key will result in an error, as primary keys must be unique.

Is it possible to change a primary key after it's set?

Yes, you can drop an existing primary key and create a new one, but ensure that the new key maintains uniqueness.