CSV to SQL Converter
Generate SQL INSERT statements from CSV data, ready to run against your database.
Was this tool helpful?
Thanks for the feedback!
Paste CSV data with a header row, type a table name, and this converter writes one SQL INSERT statement per data row, using the header values as column names. It saves developers and analysts from hand-writing inserts when loading a small spreadsheet into MySQL, MariaDB or SQLite.
Worked example
Table name: employees. CSV:
name,age,city,emp_code Asef,28,Mumbai,00457 Anita D'Souza,,Pune,00458
Output:
INSERT INTO `employees` (`name`, `age`, `city`, `emp_code`) VALUES ('Asef', 28, 'Mumbai', 00457);
INSERT INTO `employees` (`name`, `age`, `city`, `emp_code`) VALUES ('Anita D''Souza', NULL, 'Pune', 00458);
A Rows counter under the result shows how many statements were generated.
The rules each value goes through
- Empty cell: written as
NULL, as with Anita's age. Missing values at the end of a short row are also treated as NULL. - Whole or decimal number (an optional minus sign, digits, and optionally a dot and more digits): left unquoted, like 28 or -3.5.
- Anything else: wrapped in single quotes, with any apostrophe doubled, which is the standard SQL way to escape it. That is why D'Souza becomes
'Anita D''Souza'. - Table name: reduced to letters, digits and underscores, so
my-table 2becomesmytable2. If you leave it blank,my_tableis used. - Column names: taken from the header, trimmed of spaces, and wrapped in backticks.
Watch the emp_code column
Look again at the example: 00457 matched the number rule, so it was written without quotes. If emp_code is a text column, the database converts the number and stores 457, losing the zeros. The same applies to phone numbers such as 09876543210. Before running the SQL, find those values and wrap them in quotes, or add a non-numeric prefix in the CSV.
Using the output with different databases
Backticks around identifiers are MySQL and MariaDB syntax, and SQLite accepts them too. PostgreSQL and SQL Server do not; for those, replace every backtick with a double quote, the SQL-standard identifier quote, using a find-and-replace. Also note that the tool does not escape backslashes. In MySQL's default mode a backslash inside a string starts an escape sequence, so a value like C:\new needs its backslash doubled.
Running a batch safely
- Create the table first with column types that match the data; the converter writes inserts only, not
CREATE TABLE. - Wrap the statements between
BEGIN;andCOMMIT;(orSTART TRANSACTION;in MySQL) so a failing row does not leave half the data inserted. - Test on a copy of the database, and tidy the script with the SQL Formatter if you want to review it line by line.
For thousands of rows, a bulk loader such as MySQL's LOAD DATA INFILE or PostgreSQL's COPY is far faster than individual inserts. The statements are generated in your browser, so the CSV is never transmitted to a server.