22

I'm trying to insert additional rows into a table which requires a value to be retrieved from another table. Below is an example query:

insert into a.grades (rollno, grade)
values(select rollno from b.students where ssn=12345, 'A');

Structure of b.students table is rollno, ssn, name.

I knew the above query is wrong. Is there a way to retrieve 1 value from other table while inserting a row?

1
  • i tried it without paranthesis around select statement. Now i got it by adding ( ). Commented Jun 12, 2012 at 19:42

3 Answers 3

53
INSERT INTO a.grades (rollno, grade)
    SELECT rollno, 'A' FROM b.students WHERE ssn = 12345;

Some DBMS would accept the following, with an extra set of parenthesis around the SELECT statement:

INSERT INTO a.grades (rollno, grade)
   VALUES((SELECT rollno FROM b.students WHERE ssn = 12345), 'A');
Sign up to request clarification or add additional context in comments.

Comments

4

Columns in insert into and select must be equal

INSERT INTO grades (field1, field2)
  SELECT field1, field2 from students where ssn=12345;

Comments

2

Tables from two different databases!

Database1 - person

Database2 - order

  • Table - per_details
  • Table - or_details

Here the insert query used under Database 2!

INSERT INTO `or_details`(`per_name`) VALUES ( (SELECT person.per_details.per_name from person.per_details WHERE person.per_details.id=1001) );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.