I have a table of users and a table of values which have a foreign key to the users table. I want to insert values into the values table which either reference an existing user or create one. I’m using PostgreSQL 12.
The tables are:
CREATE TABLE users (
id SERIAL NOT NULL,
tenant TEXT NOT NULL,
name TEXT NOT NULL,
PRIMARY KEY (id),
UNIQUE (tenant, name),
)
CREATE TABLE values (
user_id INTEGER NOT NULL,
value TEXT NOT NULL,
UNIQUE (user_id, value),
FOREIGN KEY(user_id) REFERENCES users (id) ON DELETE CASCADE
)
Given a tenant
, name
and value
, how can I insert that into the values table in ideally a single query or at least in an atomic way?
3
Answers
I think you in this situation you should insert the user first into the users tables ,then insert a value of it like that
insert into users (1,'me','sohaib')
insert into values (1,'sohaib is the my first name')
Because you can’t do it in one query .
To do this atomically, you need to wrap your insert statements in a transaction block.
You do not need to know the generated
users.id
, You can obtain it by selecting given thetenant
andname
. Additionally, Postgres provideson conflict
clause to handle existingusers
. The following procedure provides what is needed to create bothusers
andvalues
in a single call. (see demo)NOTE:
Values
andvalue
are very poor choices for a table and column name. Both a SQL Standard reserved words andvalues
a restricted use in Postgres. About the best you can expect is confusion.