0

I have just uploaded my node.js app onto heroku and one of my sql queries is failing. The query is:

INSERT INTO countries (name, user_id, created_timestamp)
SELECT $1, $2, CURRENT_TIMESTAMP
WHERE NOT EXISTS (SELECT 1 FROM countries WHERE name = $1 FOR UPDATE)

It is failing with

error: SELECT FOR UPDATE/SHARE is not allowed in subqueries

Does anyone know why? Is there a work around I can use if I can't select for update?

2
  • What are you trying to accomplish? Commented Apr 5, 2012 at 17:13
  • I'm trying to insert into the table if the record doesn't exist, and not fail with a primary key violation if it does exist Commented Apr 5, 2012 at 22:09

1 Answer 1

1

This might work for you:

BEGIN;

LOCK TABLE countries IN SHARE MODE;

INSERT INTO countries (name, user_id, created_timestamp)
SELECT $1, $2, CURRENT_TIMESTAMP
WHERE NOT EXISTS (SELECT * FROM countries WHERE name = $1);

COMMIT;

Explanation and links in this closely related answer.

Sign up to request clarification or add additional context in comments.

Comments

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.