5

What I'm Trying To Achieve

I'm trying to insert a record from one table into another, but also add additional data that isn't sourced from the second table.

Example Problem

I'm trying to put insert field1, field2 and field3 into tableA. field1 and field2 are sourced from tableB. However, field3 is some additional arbitrary data that I will populate using my application.

The Query So Far

INSERT INTO tableA (field1, field2, field3) SELECT (field1, field2) FROM tableB WHERE id='1'

The Issue

Field3 is not being inserted at the moment as the above query doesn't have the field in the query. I've tried:

INSERT INTO tableA (field1, field2, field3) (SELECT (field1, field2) FROM tableB WHERE id='1'), 'somevalue';

but that doesn't seem to work.

I don't want field3 to be set to NULL or an empty string. I need to populate that column, however I need it to be populated with data from outside of the scope of the INSERT. In the example above, it should be 'somevalue'.

1
  • 1
    INSERT INTO tableA (field1, field2, field3) (SELECT (field1, field2, 'somevalue') FROM tableB WHERE id='1'); Commented Dec 23, 2014 at 12:17

2 Answers 2

14

You would just include the constant in the select list:

INSERT INTO tableA(field1, field2, field3)
    SELECT field1, field2, 'somevalue'
    FROM tableB
    WHERE id = '1';

Also, don't surround the columns in a select in parentheses.

Sign up to request clarification or add additional context in comments.

1 Comment

Great, worked perfectly simple
-1

Number of Insert statement columns should match with select columns when you insert data from another table In Your case this thing possible

INSERT INTO tableA (field1, field2, field3) 
SELECT (field1, field2,Null or 'Somevalue') FROM tableB WHERE id='1' // You have to pass some value or null or ''

5 Comments

Perhaps my question wasn't clear. I don't want field3 to be a NULL or empty value. I need to set it, but outside of the scope of the INSERT.
can you please tell me what somevalue should be in field3?
Exactly that, 'somevalue'. It doesn't matter what it is, but it just isn't a value that is held or returned from tableB.
kk done one thing pass null right now than update null with you somevalue whenever you want..@BigPun
That would result in multiple queries which is exactly what this sort of sub querying is intended to avoid. See the marked answer.

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.