Merge Multiple INSERT Statements into One CSV
Combine rows from multiple separate INSERT INTO statements targeting the same table into a single CSV output with unified headers.
Detailed Explanation
Merging Separate INSERT Statements
Database exports and seed files often contain multiple INSERT INTO statements for the same table rather than a single multi-row insert. This commonly happens when tools generate one INSERT per batch of rows or when data is appended incrementally.
Example SQL
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name VARCHAR(100),
department VARCHAR(50),
salary DECIMAL(10,2)
);
INSERT INTO employees (id, name, department, salary)
VALUES (1, 'Alice', 'Engineering', 95000.00);
INSERT INTO employees (id, name, department, salary)
VALUES (2, 'Bob', 'Marketing', 82000.00);
INSERT INTO employees (id, name, department, salary)
VALUES (3, 'Charlie', 'Engineering', 105000.00);
Generated CSV
id,name,department,salary
1,Alice,Engineering,95000.00
2,Bob,Marketing,82000.00
3,Charlie,Engineering,105000.00
How Merging Works
The tool processes all INSERT INTO statements sequentially. When multiple statements target the same table:
- Column names are determined by the first
INSERTor theCREATE TABLEdefinition - All subsequent
INSERTrows are appended to the same result set - If a later
INSERTintroduces new columns not seen before, they are added to the column list - Rows missing values for newly added columns get empty strings
This makes it trivial to consolidate fragmented database exports into a single, clean CSV file without manual editing.
Use Case
Consolidating fragmented database export files where a tool outputs individual INSERT statements for each record, such as mysqldump with --skip-extended-insert.