Reputation: 15435
I have a table that i had to ALTER in Postgres. I would now like to insert some values for the rows that exists in the table based on a condition. I'm looking at using CASE blocks!
Here is what I have:
INSERT INTO MyTable (value1, value2) values
(1, SELECT t.name,
CASE WHEN t.name IN ('MyName') THEN 1
ELSE 2
END AS value2
FROM MyTable t);
I get an error:
ERROR: syntax error at or near "select"
SQL state: 42601
Character: 71
Any clues what it is?
Upvotes: 1
Views: 24387
Reputation: 3118
OK, this is the insert query with the syntax fixed
INSERT INTO MyTable (value1, value2)
SELECT t.name,
CASE WHEN t.name IN ('MyName') THEN 1
ELSE 2
END AS value2
FROM MyTable;
If you're trying to change existing rows, you need an update query, e.g.
-- first update, set value1 to 1 and value2 for all rows
UPDATE MyTable set value1 = 1,value2 = 2;
-- next query. Set value2 = 1 for only those rows matching your criteria
UPDATE MyTable
SET value2 = 1 WHERE name IN ('MyName');
Upvotes: 8