Datasette CSV Import: Load a Large CSV Through the Browser, Then Verify Every Row Landed
Datasette CSV import walkthrough: stream a large CSV through the browser, then prove every row landed with SQL counts, duplicate checks and API recovery steps.
You have a 26,000-row CSV of wildlife observations, a Datasette instance on your own machine and a request for a faceted table your team can browse by Friday. Getting the file in is the easy part. The harder part is proving afterwards that the table holds every record from the file, exactly once, with each column typed the way your queries assume. This Datasette CSV import guide takes one illustrative file through the whole loop: count the source, create a table with a primary key, stream the file through the browser, reconcile the table against the file with SQL and a facet check, then keep a short record of what you saw.
The feature is new. On December 1, 2026, Simon Willison released Datasette 1.0a46 and published Large CSV imports in Datasette (Datasette Advent Day 1). He writes that CSV or TSV files of any size can now be imported into a Datasette table using the browser upload tool, with the files streamed and parsed in the browser and sent to the Datasette insert API in batches. His video imports 26,000 rows of iNaturalist observation data in a few seconds. His release note for datasette 1.0a46 calls large CSV imports the big new feature of this alpha.

Batching changes what can go wrong. A small pasted CSV either lands or it does not. A streamed import can stop part-way through. A second attempt can double the table when there is no primary key for repeated rows to collide with. A missing permission can block every write, and a column typed from the first rows can be wrong for row 19,000. Each of those leaves a table that looks plausible on its own page. The checks below catch all four, and the recovery steps use only documented endpoints.
A note on what is real here. The file, its counts and every response shown as expected output belong to a modelled case labelled import:inat-observations-01. They are illustrative, not results from a run we performed. The commands, endpoints, permissions and behaviors come from the Datasette documentation and release notes linked throughout. Version 1.0a46 is an alpha, so confirm details against the documentation for the exact release you install.
What you need before you import
Gather these before you open any dialog. Each item maps to a failure you would otherwise meet half-way through an upload, when it is more expensive to fix.
- [ ] Datasette 1.0a46 or later. The GitHub releases page for simonw/datasette lists 1.0a46 as a pre-release dated December 1, so you are opting into an alpha with breaking changes between releases.
- [ ] A SQLite database file Datasette can write to. The write API returns a 403 error for an immutable database, so open the file as a normal, writable database. A scratch copy is ideal. If the database already holds data you care about, take and verify a snapshot first, as described in Copy and Verify a Live SQLite Snapshot with sqlite3_rsync.
- [ ] An actor allowed to write. Locally, the root actor started with
--rootreceives every permission, including insert-row, update-row, create-table, alter-table and drop-table, according to the authentication and permissions documentation. On a shared instance those actions must be granted to your actor in datasette.yaml. - [ ] An API token for the scripted steps. The JSON write API is POST-only and needs an authenticated token sent as an
Authorization: Bearerheader. - [ ] A CSV with a stable unique ID column whose header names match the table you will create. That column is what makes a re-run safe instead of destructive.
- [ ] A way to count CSV records properly.
wc -lcounts newline characters, not records, so keep Python 3 or a similar CSV-aware tool on hand.
If a coding agent or a scheduled script will run these steps for you, give it the same narrowly scoped token you would give a colleague and nothing broader. AI Agent Identity: Treat Every Agent as a Privileged User explains why the import credential deserves the same care as a human login.
The worked case: import:inat-observations-01
The example mirrors the scale of Willison’s demo with an invented file; it is not his data. observations.csv holds one header line plus 26,000 records, one per wildlife observation, with these columns:
| Column | Example value | Table type | Why the type matters |
|---|---|---|---|
| id | 184920331 | integer, primary key | Unique per observation; a repeated id collides instead of appending |
| observed_on | 2026-10-04 | text | ISO dates sort correctly as text and support date facets |
| taxon_name | Quercus agrifolia | text | Required for analysis, so it gets a blank check |
| iconic_taxon | Plantae | text | The column used for the facet spot-check |
| quality_grade | research | text | Low-cardinality filter column |
| latitude | 37.8716 | float | Numeric range queries need real numbers, not strings |
| longitude | -122.2727 | float | Same reason as latitude |
| place_zip | 01234 | text | Leading zeros must survive the import |
Two of those decisions carry the whole procedure. The id column becomes the primary key, so a second insert of the same observation is refused or skipped rather than silently appended. And place_zip is declared text from the start. The 1.0a46 release notes say a table created from pasted or uploaded CSV now keeps leading zeros such as 01234 by making that column text, but declaring the type yourself removes any dependence on inference.
The source facts you will reconcile against are: 26,000 records, 26,000 distinct ids, zero blank taxon_name values, and six iconic_taxon groups summing to 26,000 (Plantae 11,412; Insecta 6,903; Aves 4,118; Fungi 2,207; Mammalia 791; Arachnida 569). Every one of those numbers is illustrative.
Step 1: Count the source file first
Record the truth about the file before Datasette touches it. Once the import has run, any number you read from the table cannot also serve as its own check, so the reference values must come from the file.
- Run
wc -lfor a quick line count. For 26,000 records plus a header, expect 26,001. - Run a CSV-aware count, because quoted fields containing line breaks inflate
wc -l, and a file without a final newline makes it read one short. - Save both outputs next to the file. They become the reference column of your verification record in the last section.
wc -l observations.csv
# illustrative: 26001 observations.csv
python3 - observations.csv <<'EOF'
import csv, sys, collections
with open(sys.argv[1], newline="") as f:
rows = list(csv.DictReader(f))
print("records", len(rows))
print("distinct ids", len({r["id"] for r in rows}))
print("blank taxon_name", sum(1 for r in rows if not r["taxon_name"].strip()))
for taxon, n in collections.Counter(r["iconic_taxon"] for r in rows).most_common():
print(taxon, n)
EOF
The script is plain Python standard library, not part of Datasette. Its illustrative output is records 26000, distinct ids 26000, blank taxon_name 0, then the six taxon totals listed above.
Read that output before moving on. If distinct ids is lower than records, stop: the file itself repeats ids, and the primary key will reject those rows later. Decide now whether they are true duplicates you will remove, or distinct observations that need a different key. If wc -l and the record count disagree by more than one, some fields contain embedded line breaks, which is harmless for the import but means the line count is not your reference.
Step 2: Start Datasette with a writable database and a root session
This step gives you a writable database, a signed-in root actor for the browser, and a token for the command-line steps.
- Create the database file or copy an existing one. With the sqlite3 shell, any write creates a fresh file, for example
sqlite3 inat.db "create table _init(x); drop table _init;". - Start Datasette with the root option:
datasette inat.db --root. The authentication documentation shows Datasette printing a single-use login URL on startup, followed by Uvicorn running on http://127.0.0.1:8001. - Open the login URL, then visit
http://127.0.0.1:8001/-/actor. Expected:{"id": "root"}. - While signed in, open
/-/create-tokenand create a token. The documentation says tokens made there can be restricted to specific actions, databases or tables; restrict it to the inat database if you will hand it to a script. Export it in your shell asDSTOK. Datasette signed tokens begin withdstok_. - Visit
http://127.0.0.1:8001/inatand confirm the database appears there; every command below uses the/inatpath. - Visit
/-/versionsand note the reported version for your record.
The root option is designed for local development and testing. On a shared server, grant the specific actions instead. The authentication docs show a permissions block that gives create-table on a database and insert-row on one table to an actor id. For scripted tokens, datasette create-token accepts --all, --database and --resource restrictions, but it signs with DATASETTE_SECRET or --secret, so it only works against an instance whose secret you know. Restrictions act as an allowlist layered on the actor’s permissions; they can remove access but never grant it. The reasoning matches Stage-Only npm Tokens for Agents: scope each credential to the one job it performs.
Step 3: Create the observations table with an id primary key
Why create the table yourself instead of letting the upload create it? The 1.0a46 notes describe “Create table from data” in detail: it previews the first 100 rows, detects column types from the first 1,000 and offers a menu on each column for changing its type. They do not say whether you can choose a primary key there, and the create API documentation states that a table created without pk gets a hidden rowid column. A rowid table accepts the same CSV twice without complaint. Creating the table first with the documented create endpoint removes that uncertainty.
- POST the schema to
/inat/-/createwith your token. - Expect a 201 status and a response containing the generated
schemastring. - Confirm the primary key through the table JSON with
?_extra=primary_keys.
curl -s -X POST http://127.0.0.1:8001/inat/-/create \
-H "Authorization: Bearer $DSTOK" \
-H "Content-Type: application/json" \
-d '{
"table": "observations",
"columns": [
{"name": "id", "type": "integer"},
{"name": "observed_on", "type": "text"},
{"name": "taxon_name", "type": "text"},
{"name": "iconic_taxon", "type": "text"},
{"name": "quality_grade", "type": "text"},
{"name": "latitude", "type": "float"},
{"name": "longitude", "type": "float"},
{"name": "place_zip", "type": "text"}
],
"pk": "id"
}'
# illustrative: {"ok": true, "database": "inat", "table": "observations",
# "table_url": "http://127.0.0.1:8001/inat/observations", ...,
# "schema": "CREATE TABLE [observations] (\n [id] INTEGER PRIMARY KEY, ..."}
curl -s "http://127.0.0.1:8001/inat/observations.json?_size=0&_extra=primary_keys" \
-H "Authorization: Bearer $DSTOK"
# expected to include: "primary_keys": ["id"]
The valid column types for this endpoint are text, integer, float and blob. Because id is an integer primary key, the docs say it would auto-increment when a row omits it; every CSV record supplies its own id, so that never happens here. An empty primary_keys list means the table has no explicit primary key, and you should drop it and create it again before importing anything.
Do not try to seed this table by sending all 26,000 rows to the create endpoint. Since 1.0a46 the create table API applies the max_insert_rows limit, 100 rows by default, and a larger request is a 400 error with no table created.
Step 4: Stream the CSV with Insert multiple rows
The 1.0a46 release notes say “Insert multiple rows” can import CSV and TSV files of any size into a table that already exists, in the same streaming way as table creation. Its preview shows the first 100 rows, and it asks what to do about a row that cannot be inserted instead of stopping. With “Skip existing rows” turned on, the dialog reports how many rows were inserted and how many already existed.
- Open
http://127.0.0.1:8001/inat/observationsas root. Since 1.0a42 the table page only loads its editing tools when the actor can insert, alter, update or delete, so missing controls usually mean you are not signed in as a writer. - Open the Insert multiple rows dialog from the table’s editing controls and choose
observations.csv. - Read the 100-row preview. Check that the header names match the table’s column names, that place_zip still shows 01234 and that ids look like your file. The notes do not describe how unmatched headers are handled, so fix any mismatch in the file rather than hoping the dialog maps it.
- Turn on Skip existing rows. On a first run nothing exists, so it costs nothing; on a re-run it is the resume mechanism.
- Start the import and watch the progress bar. The notes describe larger files being read a piece at a time with rows inserted in batches, a progress bar and a button to stop.
- If the dialog flags a row it cannot insert, prefer stopping over skipping for an import you must reconcile. Write down the row it names. Every skipped row becomes a count mismatch later, and you want to know its cause, not discover it.
- When the dialog finishes, copy its inserted and existing counts into your notes. For this case, the illustrative expectation is 26,000 inserted and 0 existing.
The transaction model explains why a stopped import is recoverable. The JSON API documentation describes a compact insert form, a columns list plus rows as lists of values, and says every row in such a request is inserted in one transaction, so if any row fails, none in that request are inserted. It adds that Datasette’s own CSV and TSV import dialogs use this form. A stop therefore leaves whole batches in the table, never half a batch. The notes do not state the batch size, so do not try to predict the partial count; measure it.

Two other 1.0a46 changes protect this example. Integers too large for JavaScript, such as 64-bit IDs, are no longer rounded on CSV import, which matters if your id column holds very large values. And the import code is only fetched when one of the import dialogs is switched into use, so the table page stays light for readers.
Step 5: Reconcile the table against the source
Now compare the table with the numbers from Step 1. Use two independent routes: the exact count endpoint and SQL. Verification needs only read access, the same separation of read and write roles argued in Postgres MCP Server Setup: Make Read-Only Mean Read-Only With a Database Role.
The JSON API documents POST /<database>/<table>/-/count, which returns an exact count of rows matching the table’s filters. Unlike the count extra, it is not capped by the row count limit, though the usual SQL time limit still applies. It needs view-table permission. Arbitrary SQL on the /inat/-/query page needs execute-sql, which root has.
curl -s -X POST http://127.0.0.1:8001/inat/observations/-/count \
-H "Authorization: Bearer $DSTOK"
# illustrative: {"ok": true, "count": 26000}
curl -s -X POST "http://127.0.0.1:8001/inat/observations/-/count?iconic_taxon=Plantae" \
-H "Authorization: Bearer $DSTOK"
# illustrative: {"ok": true, "count": 11412}
Paste the following into the SQL editor at http://127.0.0.1:8001/inat/-/query:
-- import:inat-observations-01 reconciliation (expected values are illustrative)
select
count(*) as row_count, -- expect 26000
count(distinct id) as distinct_ids, -- expect 26000
sum(case when taxon_name is null or trim(taxon_name) = '' then 1 else 0 end) as missing_taxon, -- expect 0
sum(case when observed_on is null or trim(observed_on) = '' then 1 else 0 end) as missing_date, -- expect 0
min(id) as min_id,
max(id) as max_id
from observations;
-- any repeated ids? expect no rows
select id, count(*) as copies
from observations
group by id
having count(*) > 1
limit 20;
-- did numeric columns store numbers? expect one row: real | 26000
select typeof(latitude) as stored_as, count(*) as n
from observations
group by 1;
-- facet spot-check, computed in SQL
select iconic_taxon, count(*) as n
from observations
group by iconic_taxon
order by n desc;
Finally open http://127.0.0.1:8001/inat/observations?_facet=iconic_taxon. The facets documentation says facets work in both the HTML page and the .json view, return 30 values by default and do not require execute-sql. The JSON form is /inat/observations.json?_facet=iconic_taxon&_size=0&_extra=facet_results.
| Input | Action | Expected result (illustrative) |
|---|---|---|
| import:inat-observations-01 source file observations.csv | Run wc -l observations.csv and the csv.DictReader script from Step 1 |
26001 observations.csv; script prints records 26000 and distinct ids 26000 |
| import:inat-observations-01 table inat/observations after the dialog finishes | POST /inat/observations/-/count with the bearer token |
{"ok": true, "count": 26000}, equal to the source record count |
| import:inat-observations-01 id column | Run the reconciliation select on /inat/-/query |
row_count 26000 and distinct_ids 26000 on the same result row |
| import:inat-observations-01 required taxon_name values | Read missing_taxon from the same select |
0, matching the script’s blank taxon_name 0 |
| import:inat-observations-01 latitude column | Run the typeof(latitude) group-by query |
One row, real 26000; any text row signals a type problem |
| import:inat-observations-01 iconic_taxon facet | Open /inat/observations?_facet=iconic_taxon |
Plantae 11,412; Insecta 6,903; Aves 4,118; Fungi 2,207; Mammalia 791; Arachnida 569 |
| import:inat-observations-01 schema | GET /inat/observations.json?_size=0&_extra=primary_keys |
"primary_keys": ["id"]; an empty list means a rowid table |
A pass requires every row of that table to match. Equal totals alone are not enough: a table could hold 26,000 rows made of 25,990 distinct observations plus ten repeats, which only the distinct count and the duplicate query reveal.
Read the outcome: which failure did you hit
The numbers from Step 5 identify the situation without guesswork. The chart shows the row count (count(*)) each scenario would produce for this case; the decision diagram maps each result to one recovery path.
| What you observe | Diagnosis | Next action |
|---|---|---|
| count 26,000, distinct ids 26,000, no blanks, facets match | Complete import | Record PASS in the verification record |
| count below 26,000, no repeated ids | Stopped or interrupted import; whole batches landed | Re-run Insert multiple rows with Skip existing rows, then verify again |
| count above 26,000, distinct ids 26,000 | The data went into a rowid table twice | Preview and drop the table, re-create it with pk id, import again |
| count 26,000 but distinct ids lower | The source file repeats ids, or rows were appended to a rowid table | Run the duplicate query; fix the source or the key |
typeof(latitude) shows text rows |
Values stored as strings | Fix the type with alter_column, or drop and re-import |
| Write requests fail with 401 or 403 | Expired token or missing permission | Renew the token or grant the named action, then retry |
One count mismatch has a harmless explanation: a difference of exactly one between wc -l and the table usually means the file lacks a trailing newline. That is why the CSV-aware record count, not the line count, is the reference.
Recover through the JSON API
The dialog is the easiest resume path, but scripted recovery is repeatable and leaves an exact trail. Every call below is documented in the JSON write API reference and needs the permissions named beside it.
- Partial import, dialog route. Re-run Insert multiple rows on the same file with Skip existing rows on. Existing ids are skipped and only missing ones land. Illustratively, after a stop at 18,400 rows, expect 7,600 inserted and 18,400 existing, then re-run Step 5.
- Partial import, API route. Send the missing rows in compact form with
"ignore": true(insert-row). The response reportsinsertedandignoredcounts. Withoutignore, a single repeated id fails withUNIQUE constraint failed: observations.idand none of the rows in that request are inserted. The compact form is limited by request body size, 10MB unlessmax_post_body_byteschanges it, rather than bymax_insert_rows. - Doubled rows in a rowid table. POST to
/-/dropwith no body to preview the row count, then send{"confirm": true}(drop-table).confirmmust be the JSON boolean true; a string such as “true” is a 400 error and nothing is dropped. Then repeat Steps 3 to 5. - Wrong column type. POST an
alter_columnoperation to/-/alter(alter-table). The docs say this change rebuilds the table: a new table is created, rows are copied in, the old one dropped and the new one renamed. Re-run thetypeofquery afterwards. - Corrected values for existing rows. Use
/-/upsert(insert-row and update-row) in compact form; the columns must include the primary key. A row whose id exists is updated, and a new id is inserted.
# 2. Resume: insert missing rows, skipping ids that already exist
curl -s -X POST http://127.0.0.1:8001/inat/observations/-/insert \
-H "Authorization: Bearer $DSTOK" \
-H "Content-Type: application/json" \
-d '{
"columns": ["id", "observed_on", "taxon_name", "iconic_taxon",
"quality_grade", "latitude", "longitude", "place_zip"],
"rows": [
[184920331, "2026-10-04", "Quercus agrifolia", "Plantae", "research", 37.8716, -122.2727, "01234"],
[184920332, "2026-10-04", "Danaus plexippus", "Insecta", "needs_id", 37.8702, -122.2591, "01234"]
],
"ignore": true
}'
# illustrative, when 184920331 already exists: {"ok": true, "inserted": 1, "ignored": 1}
# 3. Preview, then drop a doubled rowid table
curl -s -X POST http://127.0.0.1:8001/inat/observations/-/drop \
-H "Authorization: Bearer $DSTOK"
# illustrative: {"ok": true, "database": "inat", "table": "observations",
# "row_count": 52000, "message": "Pass \"confirm\": true to confirm"}
curl -s -X POST http://127.0.0.1:8001/inat/observations/-/drop \
-H "Authorization: Bearer $DSTOK" \
-H "Content-Type: application/json" \
-d '{"confirm": true}'
# expected: {"ok": true}
# 4. Fix a column stored with the wrong type
curl -s -X POST http://127.0.0.1:8001/inat/observations/-/alter \
-H "Authorization: Bearer $DSTOK" \
-H "Content-Type: application/json" \
-d '{"operations": [{"op": "alter_column", "args": {"name": "latitude", "type": "float"}}]}'
# illustrative: {"ok": true, ..., "altered": true, "schema": "CREATE TABLE ...",
# "before_schema": "CREATE TABLE ...", "operations_applied": 1}
# 5. Correct one value on an existing row
curl -s -X POST http://127.0.0.1:8001/inat/observations/-/upsert \
-H "Authorization: Bearer $DSTOK" \
-H "Content-Type: application/json" \
-d '{"columns": ["id", "quality_grade"], "rows": [[184920332, "research"]]}'
# expected: status 200 and {"ok": true}
If you must keep a rowid table, for instance because other tables already reference it, you can delete repeats in place through /inat/-/execute-write. That endpoint needs execute-write-sql plus delete-row on the table, and it reports SQLite’s row count in its response:
curl -s -X POST http://127.0.0.1:8001/inat/-/execute-write \
-H "Authorization: Bearer $DSTOK" \
-H "Content-Type: application/json" \
-d '{"sql": "delete from observations where rowid not in (select min(rowid) from observations group by id)"}'
# illustrative: {"ok": true, "message": "Query executed, 26000 rows affected", "rowcount": 26000, ...}
That removes the second copy but leaves a table that will happily accept a third. Dropping and re-creating with a primary key is the durable fix; treat in-place cleanup as a stopgap.
Troubleshoot the dialog and the API
Most import problems announce themselves through a specific status code or a specific missing control. The JSON API documents a standard error shape with ok, error, errors and status, and the authentication documentation separates an unusable token (401) from a missing permission (403).
| Symptom | Likely cause | Fix |
|---|---|---|
| No editing controls on the table page | The current actor cannot insert, alter, update or delete | Sign in through the root login URL, or grant insert-row in datasette.yaml |
401 with WWW-Authenticate: Bearer error="invalid_token" |
Token expired, malformed or signed with another secret | Create a new token at /-/create-token |
| 403 naming a missing action | The actor or token lacks that permission; restrictions cannot add access | Grant the action to the actor, then mint a token that includes it |
| 403 on every write to the database | The database is immutable | Restart Datasette with the file opened as a writable database |
400 UNIQUE constraint failed: observations.id |
An API insert repeated an existing id without ignore |
Add "ignore": true, or use upsert for intended changes |
400 Row 0 is missing primary key column(s) |
An upsert row omitted the id | Include id in the columns list |
400 from /-/create with many rows |
Over 100 rows hit max_insert_rows since 1.0a46 |
Create the empty table, then insert in compact form |
| JSON upload refused | JSON files are still read whole and limited to 50MB | Convert to CSV or TSV, which stream |
| Facet counts missing on a big table | The facet exceeded facet_time_limit_ms |
Use the SQL group-by query from Step 5 |
Table off by exactly one against wc -l |
File has no trailing newline | Trust the CSV-aware record count |
When “Create table from data” is the path you used and an import does not finish, the release notes say the dialog offers to drop the table it created, given the drop-table permission. Accepting is reasonable for a scratch table, but take the counts first if you want to understand where it stopped.
Keep the verification record
The last deliverable is a short record that someone else can read without rerunning anything. It ties the import to a file, a schema and a set of numbers. This filled example belongs to import:inat-observations-01, and every value in it is illustrative:
case: import:inat-observations-01
datasette_version: 1.0a46 # from /-/versions
database: inat
table: observations
primary_key: [id] # from ?_extra=primary_keys
source:
file: observations.csv
wc_l: 26001
records: 26000
distinct_ids: 26000
blank_taxon_name: 0
import:
method: Insert multiple rows dialog, Skip existing rows on
dialog_inserted: 26000
dialog_existing: 0
rows_skipped_by_choice: 0
table_checks:
count_endpoint: 26000
distinct_ids: 26000
missing_taxon: 0
missing_date: 0
latitude_stored_as: {real: 26000}
facet_iconic_taxon: {Plantae: 11412, Insecta: 6903, Aves: 4118, Fungi: 2207, Mammalia: 791, Arachnida: 569}
result: PASS
checked_by: analyst@example.org
checked_on: 2026-12-01
Before you mark the record PASS, confirm each line:
- [ ] The count endpoint equals the CSV-aware record count, not the
wc -lline count. - [ ]
count(distinct id)equalscount(*), and the duplicate query returns no rows. - [ ] Required columns have zero blank or null values, or each exception is explained.
- [ ]
typeofshows numeric columns stored as numbers. - [ ] Every facet total matches the source-side counter.
- [ ]
primary_keyslists id, so the next re-run cannot double the table.
With the record in place, the table is ready for the analysis that follows. Charts built on it can then be checked against their own SQL, the next step covered in Verify Datasette Charts Against the SQL Behind Them. If imports like this run on a schedule or through an agent, keep the record alongside the run logs so every load leaves the same receipt; AgentOps: Running a Fleet of AI Agents Without Losing Your Mind describes that discipline for automated work generally.
Sources
- Simon Willison, Large CSV imports in Datasette (Datasette Advent Day 1), Simon Willison’s Weblog, December 1, 2026.
- Simon Willison, Release: datasette 1.0a46, Simon Willison’s Weblog, December 1, 2026.
- Releases, simonw/datasette, GitHub, 1.0a46 release notes dated December 1, 2026.
- JSON API, Datasette documentation (latest).
- Authentication and permissions, Datasette documentation (latest).
- Facets, Datasette documentation (latest).

