Ask Your Question

Revision history [back]

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.