Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a mix of explicit values and data retrieved from another table

Tags:

sql

sql-server

I know two ways to insert data into a table

Method 1 : explicit values

INSERT INTO table
('field1', 'field2', 'field3')
VALUES ('value1', 'value2', 'value3')

Method 2 : copying data from another table

INSERT INTO table
SELECT 'field1', 'field2', 'field3'
FROM otherTable

Both work only if all the fields are populated the same way. I need to insert in the same row a mix of explicit values and copied data. Is this possible?

like image 563
Thibault Witzig Avatar asked Jan 04 '11 10:01

Thibault Witzig


People also ask

How do you insert values from a table in two different tables?

To insert records from multiple tables, use INSERT INTO SELECT statement. Here, we will insert records from 2 tables.

How do I retrieve data from one table to another?

The SQL INSERT INTO SELECT Statement The INSERT INTO SELECT statement copies data from one table and inserts it into another table. The INSERT INTO SELECT statement requires that the data types in source and target tables match. Note: The existing records in the target table are unaffected.

What are two methods that can be used to populate tables with data?

Populating the Database After a database has been created, there are two ways of populating the tables – either from existing data or through the use of the user applications developed for the database.

How do I insert values in tables which are related to each other by foreign key?

If you are inserting data into a dependent table with foreign keys: Each non-null value you insert into a foreign key column must be equal to some value in the corresponding parent key of the parent table. If any column in the foreign key is null, the entire foreign key is considered null.


1 Answers

Yes, it is. (Note that in your Method 2 example, that would actually insert explicit values, and not data from the other table)

e.g.

INSERT SomeTable(FieldA, FieldB, FieldC)
SELECT FieldA, FieldB, 'Explicit Value'
FROM SomeOtherTable
like image 133
AdaTheDev Avatar answered Oct 06 '22 04:10

AdaTheDev