# DuckDB read_csv, with stock data examples

Originally published on [Stock Data Archive](https://stockdataarchive.com/guides/duckdb-read-csv/).

read_csv loads a CSV file into DuckDB and works out the delimiter, the header and the column types by itself. Every example here runs on a free file of real AAPL trades and 1-minute bars.

## Get a CSV file to practise on

DuckDB reads files over HTTPS. These two statements turn the free sample files into a CSV of 1-minute bars and a gzipped CSV of trades.

```sql
COPY (FROM 'https://stockdataarchive.com/samples/AAPL_2026-11-09_1min.parquet')
  TO 'aapl_1min.csv';
COPY (FROM 'https://stockdataarchive.com/samples/AAPL_2026-11-09_trades.parquet')
  TO 'aapl_trades.csv.gz';
```

The first file has 846 rows. The second has 750k+ rows, one for every AAPL trade of the day.

## Read a CSV file with read_csv

```sql
SELECT * FROM read_csv('aapl_1min.csv') LIMIT 3;
```

`FROM 'aapl_1min.csv'` reads the same file without the function name. Older examples call `read_csv_auto`, which is the same function.

## Check the types DuckDB detected

DuckDB reads the first 20,480 rows and picks a type for each column. `DESCRIBE` shows what it picked.

```sql
DESCRIBE FROM read_csv('aapl_trades.csv.gz');
```

| Column | Type |
| --- | --- |
| `symbol` | VARCHAR |
| `ts_event` | BIGINT |
| `ts_sip` | BIGINT |
| `price` | DOUBLE |
| `size` | DOUBLE |
| `exchange` | BIGINT |
| `sequence_number` | BIGINT |
| `trade_id` | BIGINT |
| `conditions` | VARCHAR |
| `correction` | BIGINT |
| `tape` | BIGINT |
| `trf_id` | BIGINT |
| `ts_trf` | BIGINT |

Two picks need a second look. `trade_id` is an identifier and became a number. `ts_event` is a time, written as nanoseconds since 1970, and stays a number until you convert it.

## Set column types yourself

`types` changes the columns you name and leaves the others to detection. Prices read as DOUBLE unless you ask for DECIMAL, which keeps them exact.

```sql
SELECT *
FROM read_csv('aapl_trades.csv.gz',
    types = {'trade_id': 'VARCHAR', 'price': 'DECIMAL(18,6)'});
```

`columns` names every column and its type, in file order. DuckDB then detects no types at all.

```sql
SELECT *
FROM read_csv('aapl_1min.csv',
    columns = {
        'symbol': 'VARCHAR', 'timestamp': 'BIGINT',
        'open': 'DECIMAL(18,6)', 'high': 'DECIMAL(18,6)',
        'low': 'DECIMAL(18,6)', 'close': 'DECIMAL(18,6)',
        'volume': 'DOUBLE', 'trade_count': 'INTEGER'
    });
```

## Convert timestamps

The bars carry their start time as integer nanoseconds in UTC. `to_timestamp` takes seconds, and `AT TIME ZONE` gives the time in New York.

```sql
SELECT
    to_timestamp("timestamp" / 1e9) AT TIME ZONE 'America/New_York' AS bar_start,
    close
FROM read_csv('aapl_1min.csv')
LIMIT 3;
```

For tick data, `make_timestamp_ns(ts_event)` keeps all nine decimal places.

Text timestamps such as 2026-11-09 09:30:00 are detected without help. A layout such as 11/09/2026 09:30 is read as text until you pass its format.

```sql
SELECT * FROM read_csv('fills.csv', timestampformat = '%m/%d/%Y %H:%M');
```

## Read many CSV files at once

A pattern reads every matching file as one table. `filename = true` adds a column that says which file each row came from. `union_by_name = true` lines columns up by name when the files differ.

```sql
SELECT symbol, count(*) AS bars
FROM read_csv('bars/*.csv', filename = true, union_by_name = true)
GROUP BY symbol;
```

Gzipped files need nothing extra. DuckDB reads `.csv.gz` files as they are.

## read_csv options you will use most

| Option | What it does | Example |
| --- | --- | --- |
| `header` | Says whether the first row holds column names. | `header = false` |
| `names` | Names the columns of a file that has no header. | `names = ['symbol', 'price']` |
| `delim` | Sets the character between values. | `delim = ';'` |
| `skip` | Skips lines at the top of the file. | `skip = 2` |
| `nullstr` | Reads a marker as NULL. | `nullstr = 'n/a'` |
| `decimal_separator` | Reads 346,20 as a number. | `decimal_separator = ','` |
| `dateformat` | Parses dates written another way. | `dateformat = '%d.%m.%Y'` |
| `timestampformat` | Parses timestamps written another way. | `timestampformat = '%m/%d/%Y %H:%M'` |
| `sample_size` | Sets how many rows decide the types. -1 reads the whole file. | `sample_size = -1` |
| `all_varchar` | Reads every column as text. | `all_varchar = true` |
| `ignore_errors` | Skips rows that do not fit. | `ignore_errors = true` |
| `compression` | Names the compression when the file name does not show it. | `compression = 'gzip'` |

## Fix “Could not convert string” errors

The error means a value further down the file does not fit the type picked from the first rows. There are three ways out.

- `sample_size = -1` reads the whole file before it picks the types.
- `types` sets the right type for that column.
- `store_rejects = true` loads the rows that fit and saves the others in a table named `reject_errors`.

```sql
CREATE TABLE bars AS
FROM read_csv('bars.csv', types = {'timestamp': 'BIGINT'}, store_rejects = true);

SELECT line, column_name, csv_line FROM reject_errors;
```

## Save the CSV as Parquet

Parquet keeps the column types, so the next query detects nothing and reads only the columns it needs.

```sql
COPY (FROM read_csv('aapl_trades.csv.gz', types = {'trade_id': 'VARCHAR'}))
  TO 'aapl_trades.parquet' (FORMAT parquet, COMPRESSION zstd);
```

This day of AAPL trades takes 74 MB as CSV, 18 MB gzipped and 12 MB as Parquet.

## Use read_csv from Python

The same SQL runs from the `duckdb` package, and `.df()` returns a pandas DataFrame.

```python
import duckdb

bars = duckdb.sql("""
    SELECT
        to_timestamp("timestamp" / 1e9) AT TIME ZONE 'America/New_York' AS bar_start,
        close
    FROM read_csv('aapl_1min.csv')
""").df()
```

Explore the [free sample files](https://stockdataarchive.com/free-intraday-data/) and [Stock Data Archive](https://stockdataarchive.com).
