So let's say I would like to write a function call...
# sql
u
So let's say I would like to write a function called
sum_values
that sums the values in a row and then puts them at the end. Let's say I have a table that looks like this:
Copy code
sql
id   value_1   value_2   result
1     600        300       0
2     400        100       0
3     100        200       0
-- etc.
The end result should look like this:
Copy code
sql
id   value_1   value_2   result
1     600        300      900
2     400        100      500
3     100        200      300
-- etc.
It could be done in
sql
or
plpgsql
, I guess.
Copy code
sql
create or replace function sum_values() returns void as $$
  -- 1. Select value_1 and value_2 for each row
  -- 2. Into each result insert the proper sum
$$ language sql; -- or plpgsql at this point
As a bonus, how could I make it accept the argument of a range and sum the values in that given range? Or for specific ids only? Thanks in advance, everyone!
e
I think it makes sense to use a generated column here. In this case you could define the table like:
Copy code
sql
create table values (
  id serial primary key,
  value_1 numeric,
  value_2 numeric,
  result generated always as (value_1 + value_2) stored
);
More info about generated columns here: https://www.postgresql.org/docs/12/ddl-generated-columns.html
Once you have that you can get an aggregate sum like this.
Copy code
sql
select sum(result) from values limit 10
From there you can play around with whatever filter condition you like.
u
I don't think I want to actually create a table 🤔
But rather change an existing one
e
Then you would do this.
Copy code
sql
alter table values
add column result generated always as (value_1 + value_2) stored;
You probably need to delete the
result
column first in that case. These are pretty basic postgresql operations, you should look it up if it's unclear.