Skip to content

Import a CSV file

This recipe loads a CSV file into a table. The examples use this file, customers.csv:

id,name,city
1,Ada,London
2,Grace,New York
3,Linus,Helsinki

DuckDB reads a CSV file with its function read_csv. One statement makes the table and loads the rows:

Terminal window
usql -c "create table customers as select * from read_csv('customers.csv')" dk:shop.duckdb

DuckDB finds the types of the columns from the values. \d customers shows them:

Table "main.customers"
Column | Type | Nullable | Default
--------+---------+----------+---------
id | BIGINT | |
name | VARCHAR | |
city | VARCHAR | |

To choose the types and the constraints, make the table first, then insert the rows with insert into customers select * from read_csv('customers.csv').

To load the file into SQLite or another database, let DuckDB read the file, and copy its rows with \copy. dk: with no file name is a DuckDB database in memory.

  1. Make the table in the destination database:

    Terminal window
    usql -c 'create table customers (id integer primary key, name text not null, city text)' sq:shop.db
  2. Copy the rows of the file into the table:

    Terminal window
    usql -c "\copy dk: sq:shop.db \"select * from read_csv('customers.csv')\" customers"

usql prints COPY 3. The query of \copy must return one column for each column of the table, or name the columns after the table. Copy data between databases explains \copy.

The csvq driver reads each CSV file of a directory as a table, by the name of the file. Put the file in a directory of its own, and open the directory:

Terminal window
mkdir csv
cp customers.csv csv/
usql -c 'select * from customers' csvq:csv

csvq reads every value as text. To load the rows into another database, give csvq:csv as the source of \copy.