Skip to Main Content
  • Questions
  • Insert data into a table using the data from another table

Breadcrumb

XMAS_TREE

The AskTOM team is taking a break over the holiday season, so we're not taking questions or responding to comments, but we might still sneak in a few Office Hours sessions! Thanks for being a member of the AskTOM community.

Question and Answer

Chris Saxon

Thanks for the question, Mukti.

Asked: September 16, 2015 - 1:31 pm UTC

Last updated: September 18, 2015 - 4:00 am UTC

Version: Oracle 10

Viewed 50K+ times! This question is

You Asked

Hi,

I have a question.

I need to insert data into a table Student with columns names as Student_id, batch_id and student_name, but I have another table with name batch_job and in this table I have a column batch_id.
The value of the column batch_id in table student should be based on the values of the column batch_id of the table batch_job and on the where clause of the batch_job

somewhat Like this
INSERT INTO Student VALUES ('student_id',job_id,student_name)(
where Student.job_id in (SELECT job_id FROM batch_job WHERE BATCH_STATUS = 'SUCCESS'))

how can we implement such a scenario?

Thanks in advance.

and Chris said...

To insert values from another table there's two methods:

For a single row insert, you can put the select statement directly in the where clause:

create table t (x integer);

insert into t values ((select 1 from dual));

1 row inserted.

select * from t;

         X
----------
         1


to insert multiple rows, use a select statement instead of a values clause:
delete t;

insert into t
  select rownum
  from   dual 
  connect by level <= 5;

5 rows inserted.
  
select * from t;

         X
----------
         1
         2
         3
         4
         5


I'm guessing you want something along the lines of:

insert into student 
  select 'student_id', job_id , 'student name'
  from   batch_job 
  where  batch_status = 'SUCCESS';


You'll need to post create table statements with example before and after data for us to verify this though.

Rating

  (1 rating)

We're not taking comments currently, so please try again later if you want to add a comment.

Comments

Insert option

Rajeshwaran, Jeyabal, September 16, 2015 - 2:35 pm UTC

The value of the column batch_id in table student should be based on the values of the column batch_id of the table batch_job

insert into student(c1,c2,c3..)
select c1,c2,c3...
from batch_job b
where b.batch_id in (select s.batch_id from student s)