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!
Смотрите видео Make an Existing Column the Primary Key онлайн без регистрации, длительностью часов минут секунд в хорошем качестве. Это видео добавил пользователь PG Casts by Hashrocket 22 Август 2019, не забудьте поделиться им ссылкой с друзьями и знакомыми, на нашем сайте его посмотрели 3,711 раз и оно понравилось 16 людям.