Given the following table in PostgreSQL, how do I insert a record which refers to itself?
CREATE TABLE refers (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
parent_id INTEGER NOT NULL,
FOREIGN KEY (parent_id) REFERENCES refers(id)
);
The examples I’m finding on the Web have been allowed the parent_id to be NULL and then use a trigger to update it. I’d rather update in one shot, if possible.
You can select last_value from the sequence, that is automatically created when you use type serial:
And the following even simpler seems to work as well:
Though I don’t know how this would work when using multiple sequences… I looked it up; lastval() returns the last value returned or set with the last nextval or setval call to any sequence, so the following would get you in trouble:
However the following would be okay: