PG Casts

Make an Existing Column the Primary Key

Episode #32 hosted by Mary Lee

Hey everyone, today we're going to look at how to make an existing column the primary key to a table in Postgres.

Postgres Version 11

Transcript

In this example, we're going to be dealing with a dummy database that has a table called users, with the columns name, and employee number.

We can select from this table and see that we already have data: 

select * from users;

We can also inspect the table to see the current columns and constraints.

\d users

As you can see we currently have one constraint, which is asserting that the employee number is unique.

To make an existing column the primary key, we can use the "alter table" command, passing the table we're dealing with, which for us is "users". We then specify our action, which is "add primary key", and we pass the name of the column we are making our new primary key.

alter table users add primary key (employee_number);

We can inspect our table again and see that in addition to the uniqueness constraint we already had, the employee number now has a not null constraint, and an index.

It is important to note that we can only make an existing column a primary key if that column has no null values and no duplicates. If the column fails either of those checks, the alter table command will fail.

Thanks for watching!

Setup

create table users (
  name varchar not null,
  employee_number varchar not null unique
);

insert into users
values ('Sam', 'EM1234'),
('Emily', 'EM2345');