I have the following two tables:
CREATE TABLE employee
(
id serial NOT NULL,
name character(32) NOT NULL,
CONSTRAINT employee_id_pkey PRIMARY KEY (id),
CONSTRAINT employee_name_ukey UNIQUE (name)
)
WITH (
OIDS=FALSE
);
ALTER TABLE employee
OWNER TO postgres;
CREATE TABLE worklog
(
id serial NOT NULL,
activity character(32),
employee integer NOT NULL,
"time" timestamp without time zone NOT NULL DEFAULT now(),
CONSTRAINT log_id_pkey PRIMARY KEY (id),
CONSTRAINT fk_employee FOREIGN KEY (employee)
REFERENCES employee (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
);
ALTER TABLE worklog
OWNER TO postgres;
-- Index: fki_employee
-- DROP INDEX fki_employee;
CREATE INDEX fki_employee
ON worklog
USING btree
(employee);
I would like to do something like this:
insert into
worklog (activity, employee)
values
('work in progress',
coalesce(
(select id from employee where name = 'jonathan'),
(insert into employee (name) values ('jonathan') returning id)
)
);
However, this returns the error:
ERROR: syntax error at or near "into"
LINE 8: (insert into employee (name) values ('jonathan') returning...)
I have read somewhere, that I could just insert the 'name' in employee
beforehand and ignore a possible duplicate key error by utilizing the ON CONFLICT ...
mechanism. However, there are two issues for me with that approach:
- I am using postgres 9.4 and AFAIK the ON CONFLICT construct requires 9.5
- More importantly, the situation where an employee would not be in the database is exremely rare. So most of the time a leading insert would just be a waste of time.
Is what I have in mind possible with postgres 9.4?