Inserting multiple rows in a single SQL query? [duplicate]
Asked Answered
U

4

2016

I have multiple set of data to insert at once, say 4 rows. My table has three columns: Person, Id and Office.

INSERT INTO MyTable VALUES ("John", 123, "Lloyds Office");
INSERT INTO MyTable VALUES ("Jane", 124, "Lloyds Office");
INSERT INTO MyTable VALUES ("Billy", 125, "London Office");
INSERT INTO MyTable VALUES ("Miranda", 126, "Bristol Office");

Can I insert all 4 rows in a single SQL statement?

Unformed answered 17/1, 2009 at 5:55 Comment(15)
Moderator Note: Please take all discussion about the merits of this question to this meta post.Staurolite
For oracle sql see https://mcmap.net/q/45765/-best-way-to-do-multi-row-insert-in-oracleRosio
To insert multiple record in one line you can try this also Example: insert into tablename (col1 ,col2) select uid,uname from usertable;Leaflet
you can also use this query for inserting multiple rows in a single SQL query. here is the query : INSERT into tablename1(Person, Id, Office) SELECT 'John', 1,'Lloyds Office' UNION SELECT 'Jane', 2,'Lloyds Office' UNION SELECT 'Billy', 3,'Lloyds Office' UNION SELECT 'Miranda', 4,'Lloyds Office'Buchalter
As far as I can tell, the name for this technique is nothing specific, just insert multiple rows , for those wishing to be able to refer to the technique conceptually. Ref: dev.mysql.com/doc/refman/5.5/en/insert.htmlImmortelle
@Kzqai, what about insert set col1='val1', col2='val2 (?) col1='val3', col2=val2' in/for mysql ? I mean inserting multiple rows with mysql-specific insert set syntax; is it possible?Popularity
@Chinggis6 Yes, trivially possible, just use a select for the column values:Immortelle
@Immortelle could you provide an example please?Popularity
@Chinggis6 insert into profiles (name, description) select first, 'Auto-generated' from users You seem to be confusing insert and update statement, which are different beasts.Immortelle
@Immortelle No. Please recheck the link you provided above. MySQL, unlike other DBs, let you use insert in the update fashion with set keyword rather than values. It is very MySQL specific non-standard SQL statement.Popularity
@Chinggis6 Ah I see. Well, I just recommend using standard insert ... select syntax, it'll get you everything you need and is as flexible as can be wished for. dev.mysql.com/doc/refman/5.5/en/insert.htmlImmortelle
INSERT INTO MyTable VALUES ("John", 123, "Lloyds Office"),("Jane", 124, "Lloyds Office"),("Billy", 125, "London Office"),("Miranda", 126, "Bristol Office");Catawba
@GeorgeStocker, it's interesting that this question has been closed as a duplicate of a lower quality question (in terms of views, and upvotes) that was asked over a year after this question. Isn't the convention that the question asked first is the one that is kept open?Scopas
Is there any performance difference between these two methods if we take 5000 rows?Lenlena
You can insert multiple values into the table by using - 1. comma separated hardcoded set of values 2. stored procedure as input to insert 3. CTE as input to insert 4. select query as input to insert. Check Query Details hereHonig
D
2688

In SQL Server 2008 you can insert multiple rows using a single SQL INSERT statement.

INSERT INTO MyTable ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )

For reference to this have a look at MOC Course 2778A - Writing SQL Queries in SQL Server 2008.

For example:

INSERT INTO MyTable
  ( Column1, Column2, Column3 )
VALUES
  ('John', 123, 'Lloyds Office'), 
  ('Jane', 124, 'Lloyds Office'), 
  ('Billy', 125, 'London Office'),
  ('Miranda', 126, 'Bristol Office');
Detention answered 17/1, 2009 at 7:14 Comment(15)
And please note that the maximum number of rows in one insert statement is 1000.Vanover
That should be phrased "the maximum number of rows in one VALUES clause is 1000". It's not the INSERT statement that is limited to 1000 rows.Dorree
@Dorree Thanks for clearing up ChrisJ's very misleading comment. Saved me from some painful debugging. :)Onionskin
I know this question and answer are old, but I like to mention that there is a functional difference between using the method mentioned in the question and in this answer. The first executes triggers X amount of times with 1 record in the inserted table. The second executes triggers 1 time with x amount of records in the inserted table. Making the second method the best choice for performance assuming you made your triggers work correctly with batch inserts.Prolongate
This doesn't work with SQL Server 2005, see #2625213Deibel
you don't have a semicolon at the end of the statement, whereas other answers do. do you need it or no?Ommatidium
@Ommatidium Semicolons in T-sql are USUALLY optional, but they are reported to be required in the future. You should get yourself in the habit of using them to terminate each statement--your code will look nicer too IMO.Orogeny
@Orogeny I was absolutely not aware of that. I actually proceeded to look it up. For reference, here is a link to the t-sql syntax conventions in the microsoft library. I am also adding a link to an interesting article on the subject. Thanks !Opportunist
This is also slower than what he is currently doing: #8636318Reminiscent
@Dorree If you need more than 1000 rows you could union multiple 1000-row VALUES constructors in a CTE for your insert. Still counts as one query!Orogeny
do you know in which sql specification was introduced? (multiple VALUES)Swearword
Maximum number of rows is 1000, BUT the optimum number is anything between 10 and 100 (depending on columns count). Read this articleCareless
Can anyone answer this? #51763704 Basically same question but with update if existingSulfamerazine
Another important difference: If you would try to insert records where the type of values aren't the same, it will not work using only one insert. When multiple inserts are used, the RDBMS is able to convert them to the target type one by one. But if the first record contain integer, the second a date, and the target type is string, automatic conversion is not applied. This sucks when the table is used as general parameter storage, and value could be anything.Borst
this multiple insert is not applicable in OracleTherefrom
E
889

If you are inserting into a single table, you can write your query like this (maybe only in MySQL):

INSERT INTO table1 (First, Last)
VALUES
    ('Fred', 'Smith'),
    ('John', 'Smith'),
    ('Michael', 'Smith'),
    ('Robert', 'Smith');
Elvieelvin answered 17/1, 2009 at 6:10 Comment(10)
As of SQL Server 2008, this will work if you replace the double quotes with single ones.Muhammadan
Also works with postgres v9.0Prospective
And with SQLiteCollyrium
Only SQLite 3.7.11 onwards. If you cannot guarantee that, use the UNION method shown here: https://mcmap.net/q/40717/-how-to-insert-multiple-rows-in-sqliteGuessrope
is there any limit on values? like if i have many records then how to deal with this situaton?Osmious
Doesn't work in MS SQL DataWarehouseBurgrave
It worked in SQL Server 2012 just fine.New
Muneem, the limit is 1,000 VALUE lines per INSERT statement.New
@too It's also working Well on SQL SERVER 2014Confirmed
What about this question? #51763704 Basically same concern but has the function of updating in case of duplicate recordSulfamerazine
A
157

NOTE: This answer is for SQL Server 2005. For SQL Server 2008 and later, there are much better methods as seen in the other answers.

You can use INSERT with SELECT UNION ALL:

INSERT INTO MyTable  (FirstCol, SecondCol)
    SELECT  'First' ,1
    UNION ALL
SELECT  'Second' ,2
    UNION ALL
SELECT  'Third' ,3
...

Only for small datasets though, which should be fine for your 4 records.

Alexandria answered 17/1, 2009 at 6:16 Comment(2)
Worked at first try, thanks! I could even add extra stuff like: 'Before date: ' + date2str(GETDATE()) + ' after date.' I know it is a bit of a strange comand date2str but is special syntax in my database.Marentic
Starting from Oracle version 23c, Oracle now supports Value constructors as well.Oscan
B
93

INSERT statements that use VALUES syntax can insert multiple rows. To do this, include multiple lists of column values, each enclosed within parentheses and separated by commas.

Example:

INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
Bactericide answered 1/4, 2009 at 14:7 Comment(5)
A better question is why would you want to? Why not just run the cleaner 4 commands all together in one batch. If one row fails your batch fails. if you do them individually grouped together 3 of 4 succeed.Teryn
@m-t-head I have an example of why I want to, and will give you 2 reasons. I am inserting into a table which has a data integrity checking trigger. Reason 1 - inserting values separately would violate the integrity check thus rolling back the transaction and returning an error. I am using SQL Server which does not support deferred constraints, so even if instead of a trigger it was a regular constraint, it would still not work. Reason 2 - integrity check is an expensive procedure and I'd rather have it executed once instead of 1000's of times per transaction. I'm still looking for solutions.Allanson
you can create one CTE and use insert into YourTable (ID,Name) From select ID,Name From CTEArriaga
What about this question? #51763704 Basically same concern but has the function of updating in case of duplicate recordSulfamerazine
@m-t-e-head The main reason is performance, actually. Inserting thousands or millions of rows would be much faster when you bundle them together into reasonably sized batches and using a single INSERT per batch.Gaol

© 2022 - 2024 — McMap. All rights reserved.