I want to add a new column in my table and fill it with the last 3 characters from another column, both are varchar, the source column should stay invariate. I would like to avoid creating temporary columns, instead I would like to learn how to do it in a single query. thank you.
It is preferable to use virtual columns
create table t2( col_name varchar2(10) );
insert into t2(col_name) values('hsaJDadkD');
ALTER TABLE t2 ADD (col_name2 GENERATED ALWAYS AS (SUBSTR(col_name,-3))); --virtual column
Select * from T2;
COL_NAME COL_NAME
---------- --------
hsaJDadkD dkD
I would recommend to use @Kushik Nayak's solution of a virtual column.
If you solve it with a real column, the data will not stay in sync. (That is, if someone changes the old column or inserts new data, your new column will not be correct).
And the real column cannot done in one step, the structure change (DDL) and the data change (DML) are two steps:
ALTER TABLE t ADD col2 VARCHAR2(3);
UPDATE t SET col2 = substr(col1,-3);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With