How to make an existing column the primary key to a table in Postgres. This episode is brought to you by Hashrocket, expert consultants in PostgreSQL - learn more at https://hashrocket.com and www.pgcasts.com
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:
```sql
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.
```sql
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!
Watch video Make an Existing Column the Primary Key online without registration, duration hours minute second in high quality. This video was added by user PG Casts by Hashrocket 22 August 2019, don't forget to share it with your friends and acquaintances, it has been viewed on our site 3,711 once and liked it 16 people.