Skip to main content

Data analysis · Beginner · 14 min

Query CSV and Parquet files with SQL in DuckDB

By Padding · Updated 18 Nov 2026
Python 3.15 · DuckDB 2.0.1 (CLI and Python package) · pandas 3.1.1 · uv 0.13 (checked on python:3.15-slim)

You will query three monthly sales CSV files in place with DuckDB 2.0 SQL, pin the type of a code column so detection cannot change it, save the cleaned result as Parquet, join it to a pandas DataFrame from Python and keep the data in a persistent .duckdb file.

On this page

DuckDB is a database that runs inside the program you are already using: a command-line tool, a Python script or a notebook. There is no server to install or keep running. Point it at a CSV or Parquet file and it reads the file where it is, works out the column types and answers SQL against it. That makes it a good fit for the files analysts get every week: exports from a sales system, a folder of monthly reports, a Parquet file from a data engineer.

In this tutorial you build a small sales analysis for a shop chain with branches in Lagos, Nairobi, Accra and São Tomé. You query three monthly CSV files, check the types DuckDB detects and pin the one that matters, combine the files with one glob, save a clean copy as Parquet, compare it with targets held in pandas, and keep everything in a database file you can reopen later.

This tutorial uses SQL but does not teach it. If SELECT, GROUP BY or joins are new to you, work through query a table with SELECT, WHERE and ORDER BY and combine tables with SQL joins first.

Everything lives in ~/duckdb-demo, so you can delete it in one go afterwards.

Step 1 · Create a project with DuckDB and pandas

DuckDB comes in two parts here: the duckdb Python package, and duckdb-cli, which puts the duckdb command-line tool in the same project. pandas is for the Python step later. The version ranges allow patch releases and nothing newer:

Bash
mkdir -p ~/duckdb-demo
cd ~/duckdb-demo
uv init --no-package --python 3.15
uv add "duckdb>=2.0,<2.1" "duckdb-cli>=2.0,<2.1" "pandas>=3.1,<3.2"

Check it worked

Bash
cd ~/duckdb-demo
uv run duckdb --version
uv run python -c "import duckdb, pandas; print(duckdb.__version__, pandas.__version__)"

The first line starts with v2.0.1 (or a later 2.0 release) followed by a build hash. The second reads 2.0.1 3.1.1, or later patch releases of each.

Step 2 · Create three monthly sales files

Real exports arrive one file per month. Create a folder with January, February and March 2026. Each row is one order: the store code, the city, the product, how many were sold and the price per unit in US dollars.

Bash
cd ~/duckdb-demo
mkdir -p data/sales
cat > data/sales/2026-01.csv <<'CSV'
order_id,order_date,store_code,city,product,quantity,unit_price
1001,2026-01-04,014,Lagos,Rice 5kg,3,12.50
1002,2026-01-09,027,Nairobi,Cooking oil 2L,2,6.75
1003,2026-01-15,014,Lagos,Cooking oil 2L,5,6.75
1004,2026-01-21,031,Accra,Rice 5kg,1,12.50
1005,2026-01-28,045,São Tomé,Sugar 1kg,4,1.80
CSV
cat > data/sales/2026-02.csv <<'CSV'
order_id,order_date,store_code,city,product,quantity,unit_price
1006,2026-02-02,027,Nairobi,Rice 5kg,2,12.50
1007,2026-02-11,014,Lagos,Sugar 1kg,10,1.80
1008,2026-02-17,031,Accra,Cooking oil 2L,3,6.75
1009,2026-02-25,045,São Tomé,Rice 5kg,2,12.50
CSV
cat > data/sales/2026-03.csv <<'CSV'
order_id,order_date,store_code,city,product,quantity,unit_price
1010,2026-03-03,014,Lagos,Rice 5kg,4,12.50
1011,2026-03-10,031,Accra,Sugar 1kg,6,1.80
1012,2026-03-18,027,Nairobi,Cooking oil 2L,4,6.75
1013,2026-03-24,014,Lagos,Cooking oil 2L,2,6.75
1014,2026-03-30,045,São Tomé,Sugar 1kg,5,1.80
CSV
ls data/sales

The store codes have leading zeros on purpose. Codes, phone numbers and postcodes often look like numbers but are really labels, and they are a common way for a CSV import to go quietly wrong.

Check it worked

ls lists 2026-01.csv 2026-02.csv 2026-03.csv. Open one in a text editor and check that São Tomé shows its accents. The files are UTF-8, which is what DuckDB expects.

Step 3 · Query a CSV file in place

Ask the January file a question straight from the command line. -c runs the SQL and exits; nothing is imported or copied first:

Bash
cd ~/duckdb-demo
uv run duckdb -c "
SELECT city, round(sum(quantity * unit_price), 2) AS revenue
FROM read_csv('data/sales/2026-01.csv')
GROUP BY city
ORDER BY revenue DESC;
"

read_csv reads the header row, guesses the delimiter and the type of each column, then streams the rows into the query. You can also write FROM 'data/sales/2026-01.csv' and let DuckDB pick the reader from the file extension, but the explicit function is where you add options, as the next step shows.

To explore by hand, run uv run duckdb with no arguments. It opens an interactive shell where you type SQL statements ending in ;, and .quit leaves it.

Check it worked

DuckDB prints a boxed table with four rows: Lagos at 71.25, Nairobi at 13.5, Accra at 12.5 and São Tomé at 7.2.

Step 4 · Check the detected types with DESCRIBE

Type detection is right most of the time, and the times it is wrong matter. Put DESCRIBE in front of a query to see the column names and types DuckDB chose:

Bash
cd ~/duckdb-demo
uv run duckdb -c "DESCRIBE SELECT * FROM read_csv('data/sales/2026-01.csv');"
uv run duckdb -c "SELECT DISTINCT store_code, city FROM read_csv('data/sales/2026-01.csv') ORDER BY store_code;"

order_date came through as DATE, unit_price as DOUBLE and store_code as VARCHAR, which is what you want. DuckDB 2.0 keeps numbers with leading zeros as text, so the second query lists 014, not 14. Do not count on that for every file. Detection decides from the values each file happens to contain: a month in which every store code is something like 114 or 127 comes through as BIGINT, and a code such as 1E05 is read as the number 100000. When a column is a label, say so. Tell read_csv the type of that one column and leave the rest to detection:

Bash
cd ~/duckdb-demo
uv run duckdb -c "
SELECT DISTINCT store_code, city
FROM read_csv('data/sales/2026-01.csv', types = {'store_code': 'VARCHAR'})
ORDER BY store_code;
"

Two other read_csv options come up often. A file saved from an older spreadsheet program may not be UTF-8: add encoding = 'latin-1' (or 'utf-16') so names such as São Tomé or Yaoundé are not mangled. And if a source system adds or reorders columns from one month to the next, union_by_name = true lines files up by column name instead of position.

Check it worked

The DESCRIBE output lists each column with its type, and store_code shows as varchar. The second query and the last one both list 014, 027, 031 and 045; with types set, that no longer depends on what the file contains.

Step 5 · Query a whole folder with a glob

Put a wildcard in the path and DuckDB reads every matching file as one table. Every row also carries a hidden filename column you can select, which shows where it came from:

Bash
cd ~/duckdb-demo
uv run duckdb -c "
SELECT filename, count(*) AS orders
FROM read_csv('data/sales/*.csv', types = {'store_code': 'VARCHAR'})
GROUP BY filename
ORDER BY filename;
"
uv run duckdb -c "
SELECT strftime(order_date, '%Y-%m') AS month,
       count(*) AS orders,
       round(sum(quantity * unit_price), 2) AS revenue
FROM read_csv('data/sales/*.csv', types = {'store_code': 'VARCHAR'})
GROUP BY month
ORDER BY month;
"

When April arrives, drop 2026-04.csv into the folder and the same query includes it. Nothing else changes.

Check it worked

The first query lists the three file paths with 5, 4 and 5 orders. The second shows January at 104.45, February at 88.25 and March at 110.3, which add up to 303.

Step 6 · Save a clean copy as Parquet with COPY

Re-reading and re-typing CSV files every time is slow on large data and easy to get wrong. Parquet stores each column with its type and compresses it, so a cleaned Parquet file is usually much smaller than the CSV it came from, which matters when you share files over a metered or prepaid connection. COPY ... TO writes the result of any query to a file:

Bash
cd ~/duckdb-demo
mkdir -p out
uv run duckdb -c "
COPY (
    SELECT order_id, order_date, store_code, city, product, quantity, unit_price,
           round(quantity * unit_price, 2) AS revenue
    FROM read_csv('data/sales/*.csv', types = {'store_code': 'VARCHAR'})
    ORDER BY order_id
) TO 'out/sales_q1.parquet' (FORMAT parquet);
"
uv run duckdb -c "DESCRIBE SELECT * FROM read_parquet('out/sales_q1.parquet');"
uv run duckdb -c "
SELECT city, count(*) AS orders, round(sum(revenue), 2) AS revenue
FROM read_parquet('out/sales_q1.parquet')
GROUP BY city
ORDER BY revenue DESC;
"

The Parquet file keeps the types you set. Anyone who reads it later, in DuckDB, pandas, Polars or Spark, gets store_code as text and order_date as a date without repeating your fixes.

Check it worked

DESCRIBE on the Parquet file shows store_code as varchar and a new revenue column as double. The last query lists Lagos first with 5 orders and 152.75, then Nairobi (65.5), Accra (43.55) and São Tomé (41.2).

Step 7 · Join the Parquet file to a pandas DataFrame from Python

In Python, DuckDB can query a pandas DataFrame by its variable name, as if it were a table. That is handy when part of your data comes from a spreadsheet or an API and the rest sits in files. Create targets.py, which holds each city's quarterly target in a DataFrame and compares it with actual revenue from the Parquet file:

Bash
cd ~/duckdb-demo
cat > targets.py <<'PY'
import duckdb
import pandas as pd

targets = pd.DataFrame({
    "city": ["Lagos", "Nairobi", "Accra", "São Tomé"],
    "target": [150.0, 70.0, 42.0, 50.0],
})

result = duckdb.sql("""
    SELECT s.city,
           round(sum(s.revenue), 2) AS revenue,
           t.target,
           round(100 * sum(s.revenue) / t.target, 1) AS pct_of_target
    FROM read_parquet('out/sales_q1.parquet') AS s
    JOIN targets AS t USING (city)
    GROUP BY s.city, t.target
    ORDER BY pct_of_target DESC
""")

print(result)

report = result.df()
print("Returned a", type(report).__name__, "with", len(report), "rows")
print("Cities on target:", ", ".join(report.loc[report["pct_of_target"] >= 100, "city"]))
PY
uv run targets.py | tee out/targets.txt

FROM targets works because DuckDB looks up the name in your Python variables when no table of that name exists. .df() turns the result back into a pandas DataFrame for the rest of your code.

Check it worked

The table lists Accra at 103.7 per cent of target, Lagos at 101.8, Nairobi at 93.6 and São Tomé at 82.4. The last two lines read Returned a DataFrame with 4 rows and Cities on target: Accra, Lagos.

Step 8 · Keep the data in a persistent .duckdb file

So far every query has run in memory and nothing was kept between commands. Give duckdb a file name and it opens, or creates, a database file that keeps tables between sessions:

Bash
cd ~/duckdb-demo
uv run duckdb sales.duckdb -c "
CREATE OR REPLACE TABLE sales AS
SELECT * FROM read_parquet('out/sales_q1.parquet');
SELECT count(*) AS orders, round(sum(revenue), 2) AS revenue FROM sales;
"

Now reopen the same file from Python. Opening it read-only means a script cannot change your data by mistake:

Bash
cd ~/duckdb-demo
cat > reopen.py <<'PY'
import duckdb

con = duckdb.connect("sales.duckdb", read_only=True)
print(con.sql("SHOW TABLES"))
orders, revenue = con.sql("SELECT count(*), round(sum(revenue), 2) FROM sales").fetchall()[0]
print(f"sales table: {orders} orders, {revenue} revenue")
con.close()
PY
uv run reopen.py | tee out/reopen.txt

Only one process at a time can open a .duckdb file for writing. If a notebook has it open and a script tries to write to it, the script gets a lock error. Several processes can read the same file at once when they all open it with read_only=True.

Check it worked

The command-line query prints 14 orders and 303.0 revenue. The Python script lists one table, sales, then sales table: 14 orders, 303.0 revenue. The file sales.duckdb is now in the folder; run ls -lh sales.duckdb to see it. To remove everything this tutorial created, delete ~/duckdb-demo.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.