Loading a spreadsheet into a database
Every database has a bulk import — LOAD DATA, COPY, .import, BULK INSERT — and each one needs file access on the server, the right permissions and a table that already exists. For a few hundred or a few thousand rows it is often simpler to generate plain SQL and run it in whatever client you have open. That is what this converter produces.
Column types
Each column is scanned: whole numbers become INT or BIGINT, decimals DECIMAL, true/false a boolean, ISO dates DATE or a timestamp, and the rest VARCHAR sized to the data, or TEXT.
NULL and NOT NULL
Empty cells are inserted as NULL. A column with no empty cells is declared NOT NULL.
Escaping
Single quotes in values are doubled — O'Brien becomes 'O''Brien' — so names and free text cannot break the statement.
Dialects
Identifiers are quoted the right way for each database: backticks for MySQL, double quotes for PostgreSQL and SQLite, brackets for SQL Server. Boolean and date types differ too.
Before you run it
Read the CREATE TABLE first. Types are inferred from the rows you supplied, so a column that happens to contain only numbers in this sample will be numeric even if next month's file has text in it. Add a primary key, indexes and any constraints yourself — a CSV cannot say which column is the key.
The multi-row INSERT is much faster than one statement per row, and rows are grouped in batches of 500 to stay within packet and parameter limits. Wrap the script in a transaction, so a failure half-way leaves the table empty rather than partly loaded. For hundreds of thousands of rows, use the database's native bulk loader instead.
Frequently asked questions
How do I import a CSV file into MySQL or PostgreSQL?
For small files, convert it here and run the generated SQL. For large ones use the native loader: LOAD DATA INFILE in MySQL, or \copy in psql for PostgreSQL.
How are column types chosen?
From the values in each column. If every non-empty value is a whole number the column is an integer, and so on. Mixed or textual content becomes VARCHAR or TEXT. Always review the result.
Is the generated SQL safe from injection?
Values are written as string literals with single quotes doubled, which is the standard SQL escape. The script is meant to be run by you against your own database, not built from untrusted input in an application.
What happens to empty cells?
They are inserted as NULL, and the column is created as nullable.