Posts Tagged ‘SQL’

Database specific bulk inserts (MySQL, PostgreSQL and SQL Server)

Monday, November 19th, 2007

As running multiple INSERT statements is usually not the best way of pushing large amounts of data into a database, you might want to use various database-specific SQL extensions in order to achieve the goal. Here’s what I do on MySQL and SQL Server:

MySQL

INSERT INTO table (field1, field2)
VALUES (value1, value2), (another_value1, another_value2), [and so on];

PostgreSQL

PREPARE PgSQLInserter (int, int) AS
INSERT INTO table (field_1, field_2) VALUES ($1, $2);
EXECUTE PgSQLInserter (1, 234);
EXECUTE PgSQLInserter (2, 5678);
EXECUTE PgSQLInserter (3, 234);
DEALLOCATE PgSQLInserter;

SQL Server:

INSERT INTO table (field1, field2)
SELECT (value1, value2) UNION
SELECT (value1, value2) UNION
SELECT (value1, value2) UNION [and so on];