Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can we insert into two tables with single sql statement?

Tags:

sql

mysql

Will it be possible to insert into two tables with same insert command?

like image 320
rosan Avatar asked Feb 03 '10 23:02

rosan


People also ask

How do you insert the same data into two tables in SQL?

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.

Can you insert into multiple tables?

No, you can't insert into multiple tables in one MySQL command. You can however use transactions. BEGIN; INSERT INTO users (username, password) VALUES('test', 'test'); INSERT INTO profiles (userid, bio, homepage) VALUES(LAST_INSERT_ID(),'Hello world!

Can we insert data in two tables using single query in Oracle?

Because you can actually add data to multiple tables with a single insert statement.

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.


2 Answers

No you cannot perform multiple inserts into two tables in one query.

like image 186
Anthony Forloney Avatar answered Oct 21 '22 14:10

Anthony Forloney


No you can't.

If you want to ensure the atomicity of an operation that requires data to be inserted into 2 tables, you should protect it in a transaction. You either use the SQL statements BEGIN TRAN and COMMIT TRAN, or you use a transaction boundary in whatever language you're using to develop the db access layer. E.g. something like Connection.StartTransaction and Connection.Commit (or Connection.Rollback on an error).

like image 22
Disillusioned Avatar answered Oct 21 '22 14:10

Disillusioned