There’s a simple table with columns a
,b
,c
,d
. I want value in d
to be a+b
if c>0
and a-b
if c<=0
. How can I do this?
I tried this code and it doesn’t work. How can I dynamically insert data in a table?
INSERT INTO my_table VALUES(1,2,3,
CASE
WHEN c<0
THEN a+b
ELSE a-b
END
)
2
Answers
You can’t reference columns in values. Instead, you need to repeat the values. Assuming you’re issuing the query in a programming language using bind parameters…
You can also write a function.
Demonstration.
Working with literal values, you can achieve the same with a subquery:
This works without explicit type casts for basic types like
integer
ortext
as the assumed default types for the literals happen to match. You may need explicit data type casts for other data types in a separateVALUES
expression. See:More fundamentally, avoid the problem by not storing redundant data in the table to begin with.
INSERT
is back to basics:The additional column
d
can cheaply be computed on the fly. Typically much cheaper than reading more data pages due to increased storage:You might persist the logic in a
VIEW
:If you positively need the computed value stored (like when computation is relatively expensive, or you do other things with the column), use a
STORED
generated column (Postgres 12+):fiddle
See: