I need to insert data into a table with columns names as column1 and column2. I want to insert data in column2 based on the value of the column1.
For example values of column1 will be values in column2 minus 5
I tried this :
INSERT INTO Table(column2) VALUES (column1-5)
How can i implement this example?
Thank you.
If you want UPDATE value from one column table to another column table you must use UPDATE statement, instead for create new row use statement INSERT.
Here you can find the answer: https://www.techonthenet.com/oracle/insert.php
INSERT INTO table
(column1, column2, ... column_n )
SELECT expression1, expression2, ... expression_n
FROM source_table
[WHERE conditions];
(You can use subquery in expressions) For UPDATE instead
UPDATE
table_name
SET
column1 = SELECT expression1,
column2 = SELECT expression2,
column3 = SELECT expression3,
...
WHERE
condition;
lets say we want to add 3 rows for column2
insert into table (column2) values
((select column1 from table where id=1)-5),
((select column1 from table where id=2)-5),
((select column1 from table where id=3)-5)
In relational databases, having another column which can be computed easily from an existing column is a waste of resources.
Starting from Oracle 11g, we have a feature called Virtual Columns . When queried, virtual columns appear to be normal table columns, but their values are derived rather than being stored on disc.
So, based on your comment,
I want to create the new column2 and insert values in it based on the column1(already full with data)
what you may do is add a virtual column column2
like this,
ALTER TABLE yourtable ADD (
column2 NUMBER AS ( column1 - 5 )
);
You may not be able to modify the column2
directly and it won't contain any data. But, when queried, it will return the computed value.
select * from yourtable;
column1 column2
------- -------
10 5
20 15
Even after telling you this, if you still want to have a real column column2
, you may do an update
operation after adding the column using ALTER TABLE ADD COLUMN ..
and running an update query as
update table1 set column2 = column1 -5 where ..
But this is going to expensive and not recommended for this use case.
Based on your description, what you want to do is:
ALTER YOUR_TABLE
ADD (COLUMN2 NUMBER);
then
UPDATE YOUR_TABLE
SET COLUMN2 = COLUMN1 - 5;
COMMIT;
The first statement adds COLUMN2
as a new column on the table YOUR_TABLE
. The second statement sets the value of the new column COLUMN2
to be COLUMN1
minus 5.
Best of luck.
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.