Skip to content
🛠️ToolsShed

CSV to SQL INSERT Generator

Convert CSV data to SQL INSERT statements. Optionally generate CREATE TABLE DDL with auto-detected column types.

About this tool

The CSV to SQL INSERT Generator is a browser-based tool that converts spreadsheet data into executable SQL INSERT statements. This utility is essential for developers and database administrators who need to migrate data from CSV files into SQL databases, populate test databases quickly, or share data in a format that can be directly executed against any SQL database system.

To use this tool, paste or upload your CSV data, and it automatically detects the column headers and data types. You can then generate either plain INSERT statements for existing tables or include a CREATE TABLE statement with inferred column definitions. The tool supports customization options such as specifying the table name, handling NULL values, and choosing between different SQL dialects or quote styles.

This tool handles edge cases like quoted fields with commas, newlines within cells, and special characters gracefully. It's particularly useful for one-time data imports, seeding development databases, or preparing datasets for backup and restoration workflows without requiring command-line tools or database client software.

Frequently Asked Questions

Code Implementation

import csv
import io

def csv_to_sql(csv_text, table_name="my_table", include_create=True):
    reader = csv.reader(io.StringIO(csv_text.strip()))
    rows = list(reader)
    if len(rows) < 2:
        return ""

    headers = rows[0]
    data_rows = rows[1:]

    def infer_type(values):
        for v in values:
            v = v.strip()
            if v == "":
                continue
            try:
                int(v)
                return "INT"
            except ValueError:
                try:
                    float(v)
                    return "FLOAT"
                except ValueError:
                    return "VARCHAR(255)"
        return "VARCHAR(255)"

    types = [infer_type([r[i] for r in data_rows if i < len(r)])
             for i in range(len(headers))]

    sql = []
    if include_create:
        cols = ", ".join(f"{h} {t}" for h, t in zip(headers, types))
        sql.append(f"CREATE TABLE {table_name} ({cols});")

    for row in data_rows:
        values = []
        for i, val in enumerate(row):
            if types[i] == "VARCHAR(255)":
                values.append(f"'{val.replace(chr(39), chr(39)*2)}'")
            else:
                values.append(val if val.strip() else "NULL")
        cols_str = ", ".join(headers)
        vals_str = ", ".join(values)
        sql.append(f"INSERT INTO {table_name} ({cols_str}) VALUES ({vals_str});")

    return "\n".join(sql)

csv_data = """id,name,score
1,Alice,95.5
2,Bob,87"""

print(csv_to_sql(csv_data))

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.