SQL CREATE TABLE Generator · Tutorial

How to create a SQL table for a CSV file

7 min readbeginnerUpdated

You have a CSV export from a shop and want it in a database. Before importing, the table must exist with the right column types. You will generate the table from the CSV, check the types and load the rows.

What you need

Steps

  1. Paste or open the CSV

    Load the example product list. Headers like Product Name become product_name, so they are easy to use in queries.

  2. Check the detected columns

    The table under the editor shows price as a decimal, stock as a whole number and launch_date as a date. sku has unique values, so it gets a UNIQUE constraint.

  3. Choose the key

    Detect finds no id column here, so set Primary key to sku, or choose Add an id column to give every product a numeric id.

    CREATE TABLE "products" (
      "sku" VARCHAR(20) NOT NULL PRIMARY KEY,
      "product_name" VARCHAR(50) NOT NULL,
      "price" DECIMAL(10, 2) NOT NULL,
      ...
    );
  4. Create the table and import

    Run the statement, then import the file. In PostgreSQL use \copy products FROM 'products.csv' CSV HEADER; in SQLite use .import --csv --skip 1 products.csv products. Or generate INSERT statements with CSV to SQL.

Try it yourself

Opens the SQL CREATE TABLE Generator with this tutorial's sample loaded.

Try it now

Common mistakes

Using a tiny sample
If your sample has no empty values, every column becomes NOT NULL and real data with blanks fails to import. Paste a few hundred representative rows.
Column order differs from the file
Import commands match columns by position. If you add an id column, list the CSV columns in the import command.

Next steps

Go back to the SQL CREATE TABLE Generator, or keep going with one of these: