3

I'm conditionally inserting a row into the a PostgreSQL table and manually specifying the ID:

INSERT INTO foo (foo_id, foo_name)
SELECT 4, 'My Name'
WHERE NOT EXISTS (
    SELECT * FROM foo WHERE foo_id = 4
);

This won't increase the sequence that generates the next foo_id.

How can I run SELECT nextval('foo_foo_id_seq'::regclass); only if a row is actually inserted in the above query?

2
  • Do you want the sequence to continue with that number or do you want to increase the sequence regarding what the current value is? (But in both case you risk unique key violations later) Commented Feb 4, 2016 at 11:29
  • Continuing with that number will work. For example, in this case, If a row is inserted, I want the sequence's next value to be 5. Commented Feb 4, 2016 at 11:32

1 Answer 1

2

You can supply a new value for the sequence using setval()

If you want to change the sequence to continue with the "forced" value, you can use setval() inside the select:

INSERT INTO foo (id, foo_name)
select *
from (
  VALUES (setval('foo_id_seq', 42), 'My Name')
) as t (id, foo_name)
WHERE NOT EXISTS (
    SELECT * FROM foo WHERE id = 42
);

If a row is inserted the sequence will continue with 43.

If the current sequence value is already bigger than 43 this will give you problems later if other transactions insert into the table and rely on the sequence.


If you want to advance the sequence from whatever value it currently has, you can use something like this:

INSERT INTO foo (id, foo_name)
select id, foo_name
from (
  VALUES (42, 'My Name', nextval('foo_id_seq'))
) as t (id, foo_name, nextval)
WHERE NOT EXISTS (
    SELECT * FROM foo WHERE id = 42
);
Sign up to request clarification or add additional context in comments.

5 Comments

Hmmm, that'll kind of work but I'm keen to make sure 'My Name''s ID is 1 (in my case, it's actually not 1 - so it's not necessarily the first insert that happens in the table).
@s16h: why would you need that? You shouldn't rely on specific ID values.
I understand and agree with you. But, I need to do that in this case.
Absolutely right about the insert statement, I don't know why I typed it that way. I've edited to reflect what I actually have.
This is good enough for my use case; nailed it! Thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.