How to increment primary and foreign keys in Postgresql using SERIAL

Asked

Viewed 42 times

-2

I can’t automatically increment primary and foreign keys of my tables using SERIAL, because error happens and always have to enter the key value.

create table cliente(
    cd_cliente serial primary key not null,
    nome varchar(50),
    endereco varchar(50),
    cidade varchar(50)
)

create table telefone(
    cd_telefone serial primary key not null,
    cd_cliente serial,
    numero_telefone varchar(20),
    foreign key(cd_cliente) references cliente (cd_cliente)
)

insert into cliente
values
(1, 'Pessoa1', 'Algum lugar', 'Cidade'),
(2, 'Pesso2', 'Algum lugar', 'Cidade'),
(3, 'Pessoa3', 'Algum lugar', 'Cidade')

insert into telefone
values
(1, 1, '01 1111-1111'),
(2, 2, '02 2222-2222'),
(3, 3, '03 3333-3333')
  • If you set the field cd_telefoneas serial then do not enter a value for this field or inform DEFAULT to take into account the value generated by sequence. As has already been said it makes no sense to define telefone.cd_cliente as serialsince you should always inform which aware is associated with the phone.

1 answer

0

In the table 'client' should work, in the table 'phone' I think it is wrong to classify cd_client as serial, it should be integer, after all it is the client code that should be in INSERT, it should not be an automatically generated number.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.