# DuckDB CLI: SQL on Your Logs and Exports, No Database Needed

To answer "which service logged the most errors in the last hour?" from a log file, you usually write a script or load the data into a database first. The DuckDB CLI skips both: it runs SQL directly on CSV, JSON and Parquet files.

> This post covers DuckDB 2.0.x (current at the time of writing: 2.0.1).

![Mermaid Diagram](https://mermaid.ink/img/pako:eNpVj71Ow0AQhF9l2Qqkc4FE5QIJHFkEBYjikMZxsbbXzinnW3N3IX_KuyM7FFDOzmi-2TNWUjPG2BjZVxtyAWaLtQUASPOZtB7I1sCHXlzwMbxmH-8KkmylYE7ua8dBQXsqIIoeYXKb17tqW5eQzKbF3bVkMlrLfMmu05YMBCoNF3_NJE-yFYgby6ERB75yug_-X2qe_wKh0YYLVNix60jXGJ8xbLgbnqi5oZ0JqK6XFTk94PyQacSGlDptjhhjRH1vOPJHH7hT8Gy03b5RlY06FRsUrDHjVhg-p2tUsJBSgih4YfPNQVek4MlpMgo8WR95drpBNUIyfRq23D_0B7xcFJZtIkYcxniz3-jAePkBOVN4iw?type=png)

## Install

```bash
curl https://install.duckdb.org | bash
duckdb -version
```

On Windows, run `irm https://install.duckdb.org/install.ps1 | iex` in PowerShell. `pip install duckdb-cli` and `uvx duckdb-cli` also work.

## Query a file directly

```bash
duckdb -c "FROM 'orders.csv' LIMIT 5"
```

The file extension picks the reader, and globs and compressed files work too, for example `FROM 'logs/*.json.gz'`. Look at the shape of the data first:

```sql
DESCRIBE SELECT * FROM 'orders.csv';
SUMMARIZE SELECT * FROM 'orders.csv';
```

`DESCRIBE` shows the detected column types. `SUMMARIZE` adds min, max, approximate distinct counts and null percentages for every column.

## JSON logs

Take newline-delimited JSON logs like this:

```json
{"ts":"2026-11-22T10:15:03Z","level":"ERROR","service":"payments","request":{"path":"/pay","status":502},"duration_ms":3021}
```

`.log` is not a known extension, so name the reader. `read_ndjson` takes a glob, and `ignore_errors` skips lines that are not valid JSON:

```bash
duckdb -c "SET timezone = 'UTC'" -c "
SELECT service, count(*) AS errors
FROM read_ndjson('logs/app-*.log', ignore_errors = true)
WHERE level = 'ERROR'
  AND ts >= now() - INTERVAL 1 HOUR
GROUP BY ALL
ORDER BY errors DESC"
```

The `SET timezone` line matters. `now()` has a time zone, but a `ts` read from JSON is a plain timestamp, so DuckDB interprets it in your session time zone. For logs written in UTC (timestamps ending in `Z`), set the session to UTC, or the window shifts by your local offset. For fixed dates, compare against a plain literal instead: `ts >= TIMESTAMP '2026-11-22 00:00:00'`.

Nested objects become structs, so you reach into them with a dot. This finds the slowest endpoints:

```sql
SELECT request.path, count(*) AS hits,
       quantile_cont(duration_ms, 0.95) AS p95_ms
FROM read_ndjson('logs/api-*.log')
GROUP BY ALL
ORDER BY p95_ms DESC
LIMIT 10;
```

Bucket by time with `date_trunc('hour', ts)`. ISO 8601 timestamps are detected automatically, but check `DESCRIBE` to be sure `ts` is a timestamp and not a string.

## Plain-text logs

For lines like `2026-11-22T10:15:03Z ERROR payments gateway timeout`, read each line as a single CSV column with a delimiter that never appears in the log, then split it with a regex:

```sql
WITH raw AS (
  SELECT regexp_extract(
           line,
           '^(\S+) (\w+) (\S+) (.*)$',
           ['ts', 'level', 'service', 'msg']) AS f
  FROM read_csv('app.log', columns = {'line': 'VARCHAR'}, delim = '\0')
)
SELECT f.service, count(*) AS errors
FROM raw
WHERE f.level = 'ERROR'
GROUP BY ALL
ORDER BY errors DESC;
```

`regexp_extract` with a list of names returns a struct. A line that does not match gets empty strings, not NULLs, so filter on a field you expect to be non-empty.

## Combine and convert

Joining two exports needs no import step:

```sql
SELECT c.country, sum(o.total) AS revenue
FROM 'orders.csv' o
JOIN 'customers.csv' c ON o.customer_id = c.customer_id
GROUP BY ALL
ORDER BY revenue DESC;
```

If you query the same logs repeatedly, convert them to Parquet once and query that instead:

```sql
COPY (SELECT * FROM read_ndjson('logs/app-*.log', ignore_errors = true))
TO 'logs.parquet' (FORMAT parquet, COMPRESSION zstd);
```

## Remote files

With the `httpfs` extension, DuckDB reads files over HTTPS and S3 without downloading them first. For Parquet it fetches only the columns and parts a query needs, so `SELECT count(*)` reads just the metadata. 2.0 also reads Parquet and CSV with asynchronous I/O, which helps most on object storage.

```sql
INSTALL httpfs;
LOAD httpfs;

SELECT count(*) FROM 'https://example.com/exports/events.parquet';

CREATE SECRET (TYPE s3, PROVIDER credential_chain);

SELECT service, count(*) AS errors
FROM read_ndjson('s3://my-bucket/logs/*.log')
WHERE level = 'ERROR'
GROUP BY ALL;
```

`credential_chain` picks up AWS credentials from the usual places (environment variables, credential files), so no keys appear in the query. Globs work on S3. R2 and GCS have their own secret types, and other S3-compatible providers need an `ENDPOINT` setting.

## Use it in scripts

```bash
duckdb -csv -c "SELECT service, count(*) AS errors FROM read_ndjson('logs/app-*.log') WHERE level = 'ERROR' GROUP BY ALL" > errors.csv

cat export.csv | duckdb -c "SELECT count(*) FROM read_csv('/dev/stdin')"
```

`-json` and `-markdown` are other output modes, and `-f query.sql` runs a script file. Arguments are processed in order, so put the output mode before `-c`.

## Gotchas

-   **Types are guessed from a sample.** By default DuckDB samples 20,480 rows (`sample_size`). A column that looks numeric early on and holds text later can fail or be misread. For CSV, use `all_varchar = true`, set `types`, or raise `sample_size`. For JSON, set `columns`. Then check with `DESCRIBE`.
    
-   **Bad rows.** For CSV, `ignore_errors = true` skips them, and `store_rejects = true` also records them in a rejects table so you can inspect what was dropped.
    
-   **Files with different columns.** Add `union_by_name = true` to align columns by name instead of position. For CSV, this uses more memory.
    
-   **Huge JSON lines.** A single JSON object is limited to 16 MiB by default (`maximum_object_size`).
    
-   **An empty glob is an error.** In 2.0, `allow_empty = true` returns an empty result instead, which helps in scripts.
    
-   **No database by default.** With no path, the CLI uses a transient in-memory database and saves nothing. To keep a table, give it a file: `duckdb logs.duckdb -c "CREATE TABLE logs AS FROM read_ndjson('logs/*.log')"`. Database files created by 2.0 cannot be opened by versions before 2.0.
    

## Where to start

Pick one log or export you already have and run `SUMMARIZE SELECT * FROM` on it. The column types and value ranges usually show you what to query next.

---

*Published via [ZyVOP](https://zyvop.com/duckdb-cli-sql-on-your-logs-and-exports-no-database-needed-j6fl0?utm_source=hashnode&utm_medium=crosspost&utm_campaign=syndication) — Write once in Markdown, auto-backup to GitHub, and syndicate to Dev.to, Medium & Hashnode in 1 click.*
