Ask Your Question
0

How can columns be created for every row in a different table in PostgreSQL, with the values determined by the outcome of a function?

asked 2023-07-06 13:04:06 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-07-06 13:33:02 +0000

huitzilopochtli gravatar image

To create columns for every row in a different table in PostgreSQL, with the values determined by the outcome of a function, follow these steps:

  1. Define the function that will generate the values for the new columns.

  2. Use the ALTER TABLE statement to add the new columns to the table.

  3. Use the UPDATE statement to populate the new columns with the result of the function for each row in the table.

Here is an example:

Suppose we have a table called "employees" with columns "id", "name", and "salary". We want to add two new columns called "bonus" and "totalsalary", where "bonus" is 10% of "salary" and "totalsalary" is the sum of "salary" and "bonus" for each employee.

Step 1: Define the function to calculate the bonus and total_salary:

CREATE OR REPLACE FUNCTION calculate_bonus_salary(salary NUMERIC)
RETURNS TABLE (bonus NUMERIC, total_salary NUMERIC) AS $$
BEGIN
  bonus := salary * 0.1;
  total_salary := salary + bonus;
  RETURN NEXT;
END;
$$ LANGUAGE plpgsql;

Step 2: Use ALTER TABLE to add the new columns:

ALTER TABLE employees
ADD COLUMN bonus NUMERIC,
ADD COLUMN total_salary NUMERIC;

Step 3: Use UPDATE to populate the new columns with the function result for each row:

UPDATE employees
SET (bonus, total_salary) = calculate_bonus_salary(salary);

After running these commands, the "employees" table will have two new columns with the bonus and total_salary values for each employee.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-06 13:04:06 +0000

Seen: 14 times

Last updated: Jul 06 '23