Add an Auto Incrementing Primary Key

Опубликовано: 08 Август 2019
на канале: PG Casts by Hashrocket
2,875
14

How to add an auto incrementing 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 users, with no primary key currently set.

We can inspect this table using the "\d" command.

```
\d users
```

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

```sql
select * from users;
```

To add an autoincrementing id as the primary key to our table, we can use the "alter table" command, passing our users table in, and then specifying that we want to add a column called id with the type "serial" and set it as our primary key.

```sql
alter table users add column id serial primary key;
```

The serial type is a Postgres shorthand for allowing us to create columns with an autoincrementing integer.

Now if we inspect our users table, we can see that there is a new column of type integer with a sequence that was generated for us by Postgres.

```
\d users
```

If we select from our users again, we can see that our existing users have already had their id populated.

```sql
select * from users;
```

Finally, let's add a new user to our table.

```sql
insert into users values ('Jamie', 'EM3456');
```

By selecting from the users table again, we can see that the new row has had the id populated appropriately.

```sql
select * from users;
```

Thanks for watching!


Смотрите видео Add an Auto Incrementing Primary Key онлайн без регистрации, длительностью часов минут секунд в хорошем качестве. Это видео добавил пользователь PG Casts by Hashrocket 08 Август 2019, не забудьте поделиться им ссылкой с друзьями и знакомыми, на нашем сайте его посмотрели 2,875 раз и оно понравилось 14 людям.