I’ve a table provider which has id|provider_name|url
I’ve another table user which has id|name|provider_id
I want to create a function create_user(name,provider_name) that checks whether there exists any provider with that provider name. if exists insert the row and return last row id. other wise return 0. I’ve set up foreign key integrity on provider_id -> user.id. and both id fields are pkey and serial
insert into users
(name, provider_id)
values($1, (
select id from provider where name = $2
)) returning id
Is that Okay ?
Your statement
will work if you make users.provider_id
NOT NULL. Without that you would enter aNULLvalue for a non-existent provider_id. A foreign key constraint does not prohibit this!(I assume you meant:
provider_id -> provider.id, not-> user.id.)You may or may not want to make
users.name UNIQUEto prohibit duplicate names.With unique names, a surrogate primary key (
user.id) would still makes sense in most cases. Handling of an integer is faster than handling of a (longer) text. Especially if you have multiple other tables referencing the primary key of theusertable which is normally the case. Using an integer for the foreign keys and accompanying indexes is considerably faster and needs less space on disk and in RAM. It is also easier to make changes later, like splitting thenameintofirstnameandsurname.