Import a CSV file
This recipe loads a CSV file into a table. The examples use this file, customers.csv:
id,name,city1,Ada,London2,Grace,New York3,Linus,HelsinkiInto DuckDB
Section titled “Into DuckDB”DuckDB reads a CSV file with its function read_csv. One statement makes the table and loads the rows:
usql -c "create table customers as select * from read_csv('customers.csv')" dk:shop.duckdbDuckDB 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').
Into another database
Section titled “Into another database”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.
-
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 -
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.
With the csvq driver
Section titled “With the csvq driver”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:
mkdir csvcp customers.csv csv/usql -c 'select * from customers' csvq:csvcsvq reads every value as text. To load the rows into another database, give csvq:csv as the source of \copy.