postgres on heroku sql statement fails

Go To StackoverFlow.com

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?

2012-04-05 16:58
by dan
What are you trying to accomplish - Milen A. Radev 2012-04-05 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 exis - dan 2012-04-05 22:09


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.

2012-04-05 17:31
by Erwin Brandstetter
Ads