skip to Main Content

I am trying to add a column to an existing table with a max() funtion to populate the column in postgresql.

EX:
Alter table stable
Add column max_veggie INTEGER;

–populate the column max_veggie—
Insert into stable (max_veggie)
Values(Max(veggie_id));
FROM stable;

–the code for the table would be max(veggie_id)
the error: cannot be referenced from this part of the query.column
Thank you in advance.

also I tried:
update stable
set max_veggie = MAX(veggie_id);

error at M on max()……

I expected to populate a column with a maximum from another column.

2

Answers


  1. To populate a new column with the maximum value from another column in PostgreSQL, you can use a combination of subqueries and update statements.

    1- Add a new column to the table:

    ALTER TABLE stable ADD COLUMN max_veggie INTEGER;
    

    2- Update the new column with the maximum value from another column:

    UPDATE stable
    SET max_veggie = (SELECT MAX(veggie_id) FROM stable);
    

    This query will set the value of the max_veggie column in all rows to the maximum value of the veggie_id column in the stable table.

    First make sure that the column veggie_id exists in the stable table and contains numerical values. If you encounter any errors, ensure that the column names and table names are correct and that the data types match.

    I hope it can help you

    Login or Signup to reply.
  2. Using CONCATENATE function in SQL: In PostgreSQL, you can use the CONCATENATE function or || to append a dollar sign to the values in a column. For example, if you want to add a dollar sign to the values in the "amount" column, you can use the following query:

    UPDATE table_name SET amount = amount || '$';
    

    Using CONCAT function in SQL: You can also use the CONCAT function to add a dollar sign to the values in a column. For example:

    UPDATE table_name SET amount = CONCAT(amount, '$');
    

    In both methods, the dollar sign will be added to the end of the existing values in the column. Please make sure to update your data carefully to ensure the changes are made correctly.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search