Populating column B with calculated values based on column A with single statement
I need to take the value from column A, calculate something and insert the result into column B. The rows in column A contain a lot of duplicates. So maybe this can be used to an advantage. If possible this should be done in a single statement.
Example:
This is what the table1
looks like in the beginning:
columnA columnB
-------------------------
' apple'
' melon '
' apple'
' melon '
The strings in columnA
do have unnecessary whitespaces and the rows in columnB
are empty.
And this is what table1
should look like in the end:
columnA columnB
-------------------------
' apple' 'apple'
' melon ' 'melon'
' apple' 'apple'
' melon ' 'melon'
The rows in columnB
are populated with the trimmed versions of the strings in columnA
.
Is it possible to do this in one statement?
Answer: The answer from @Ergest Basha made it clear, that this can be done with a simple statement:
UPDATE table1 SET columnB = TRIM(columnA);
Thanks!
You can create the newcolumn
and if you do not have an id autoincrement you can add it ,too.
CREATE TABLE fruitamount(
id INT,
name varchar(10),
amount int);
insert into fruitamount values
(1,' apple',2),
(2,' melon ',5),
(3,' apple',1),
(4,' melon ',4);
alter table fruitamount add column newcolumn varchar(10) ;
update fruitamount set newcolumn = TRIM(name) ;
After update you can drop the column:
alter table fruitamount drop column name ;