Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

oracle

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.

like image 352
pixelatedCat Avatar asked Jan 27 '23 19:01

pixelatedCat


2 Answers

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     
like image 153
Kaushik Nayak Avatar answered Jan 31 '23 23:01

Kaushik Nayak


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);
like image 30
wolφi Avatar answered Jan 31 '23 23:01

wolφi