How to insert multiple rows of data, say five rows of data, using insert into command?

    Requires Free Membership to View

You can do this in two ways. The first is with one statement:

 insert into daTable ( col1, col2, ... coln ) values ( '21', 9, ... 'oh' ) ,( '22', 37, ... 'my' ) ,( '23', 42, ... 'we' ) ,( '24', 11, ... 'be' ) ,( '25', 77, ... 'at' );

That's one call to the database, with a single SQL statement, inserting five rows.

Note: this does not work in Oracle. I think it does in DB2, I know it does not in SQL Server, but it does in MySQL. If your database doesn't support it, please choose the next method.

The second method uses five SQL statements:

 insert into daTable ( col1, col2, ... coln ) values ( '21', 9, ... 'oh' ) ; insert into daTable ( col1, col2, ... coln ) values ( '22', 37, ... 'my' ) ; insert into daTable ( col1, col2, ... coln ) values ( '23', 42, ... 'we' ) ; insert into daTable ( col1, col2, ... coln ) values ( '24', 11, ... 'is' ) ; insert into daTable ( col1, col2, ... coln ) values ( '25', 77, ... 'at' ) ;

This might still be just one call to the database, provided that the interface will allow concatenated SQL statements (note the semicolons) in one call. If your interface does not, then you have no choice but to call the database five times. If the number of insertions increases much higher than five, consider uploading a file to a holding table and using INSERT SELECT syntax to load your target table.

 

This was first published in March 2007

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: