简体   繁体   中英

Add a new column and fill it with a portion of another column in Oracle SQL

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM