I have a table in PostgreSQL that I need to modify, the table looks like this:
name | value1 | value2 | date
--------+-------+--------+---------
Jonh | | 0.15 | 2021-12-23 00:00:00
Jonh | 0.14 | 0.76 | 2021-12-22 00:00:00
Jonh | 0.19 | 0.87 | 2021-12-21 00:00:00
Jonh | 0.13 | 0.11 | 2021-12-15 00:00:00
Bob | 0.12 | 0.23 | 2021-12-15 00:00:00
Having a name
, a date
and either value1
or value2
, I need to create a statement that:
- Checks if any row with
name
anddate
exists (there is a constraint key so there can only be one row both values) - Inserts the value
value1
orvalue2
in this row (update the row values, although initially this columns will be empty in the row).
I need to set value1
and value2
at different times, so I need to find a way of creating a new row or updating the current one, I was using this answer to create a create or update row statement, how'd you do this?
EDIT
Scenario 1, as input I will have the arguments:
name='Jonh'
value1 = 0.5
date = '2021-12-23 00:00:00'
In this case, a row with this name and date already exists, so it will only update the value of value1
.
Final table:
name | value1 | value2 | date
--------+-------+--------+---------
Jonh | 0.5 | 0.15 | 2021-12-23 00:00:00
Jonh | 0.14 | 0.76 | 2021-12-22 00:00:00
Jonh | 0.19 | 0.87 | 2021-12-21 00:00:00
Jonh | 0.13 | 0.11 | 2021-12-15 00:00:00
Bob | 0.12 | 0.23 | 2021-12-15 00:00:00
Scenario 2, as input I have:
name='Tim'
value2 = 1
date = '2021-12-23 00:00:00'
Because there are no rows with this name and date, it will create a new row, assign the value2
and set a NULL value for value1
.
Final table:
name | value1 | value2 | date
--------+-------+--------+---------
Tim | | 1 | 2021-12-23 00:00:00
Jonh | | 0.15 | 2021-12-23 00:00:00
Jonh | 0.14 | 0.76 | 2021-12-22 00:00:00
Jonh | 0.19 | 0.87 | 2021-12-21 00:00:00
Jonh | 0.13 | 0.11 | 2021-12-15 00:00:00
Bob | 0.12 | 0.23 | 2021-12-15 00:00:00