0

I need to create a PostgreSQL function that will use the values from two columns - "column1" and "column2" - to update data in "column3".

The data in "column1" and "column2" already exists. I just need to use the data included in those two columns (with some kind of loop) to update "column3" (like "column1" space "column2").

All columns are part of the same table and they are VARCHAR. Any help would be greatly appreciated.

2 Answers 2

3

PostgreSQL uses || for string concatenation (joining). So you can use a single update statement that will affect multiple rows at the same time

update tbl
set column3 = column1 || ' ' || column2
where ... (optional clause to identify records to update)
Sign up to request clarification or add additional context in comments.

4 Comments

Do I just use the column1 and column2 names? How does it know I'm referring to the columns form the same table and not some other values?
It knows which table to update because you are writing UPDATE tbl - which specifies the table. You should really go through a good SQL tutorial first before proceeding any further. The one in the PostgreSQL manual is a good start.
To add to that, it is updating, for each row found (all, if not limited by the WHERE clause), the column3 value with the values of column1+space+column2 of the same row.
I was getting an error that's why I asked. I think the problem is related to something else.
2

This will update column3 in all rows.

update your_table
set column3 = column1 || ' ' || column2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.