Skip to content

Fixed-width files

Read and write fixed-width and mainframe files, including COBOL copybooks and EBCDIC

Connector software
Free and open source
Service credentials
Not needed
Use with an agent

Install the Orchard skill in your project to help your agent find connectors, configure them, and verify SQL results.

npx skills add Query-farm/vgi-skills --skill orchard

Copy this request into your coding agent to get started.

Use https://query.farm/products/orchard/connectors/fixedformat/index.md to help me query Fixed-width files with DuckDB or Haybarn 2.0.1 and VGI protocol 3.4. Ask only for missing details about the result I need or whether I want local execution, self-hosting or Query Farm hosting. Check the connector's actual hosting availability, credentials and input requirements. Read one format of each needed reference and the exact object declarations before writing SQL. Use a released connector, and distinguish a saved example result from anything you actually execute. If you cannot run the query, tell me what remains to verify.

Read a fixed-width accounts file as typed rows

Example output · captured
Connector release
v0.13.1
Engine
2.0.1
VGI protocol
3.4.0
SELECT *
FROM fixed.main.read_fixed('https://raw.githubusercontent.com/Query-farm/vgi-fixedformat/v0.12.0/data/accounts.dat', 'name:A10 qty:9(5)')
Result
name qty
JOHN 42
JANE 100
BOB 7

Quick start

Choose where to run Fixed-width files, then follow the steps below.

The connector runs alongside DuckDB or Haybarn. No Query Farm account is needed.

1. Install the vgi extension

Run this in your SQL client. On DuckDB, keep FROM query_farm on LOAD in later sessions.

setup.sql
SET allow_extension_repositories = 'allowed';

CREATE EXTENSION REPOSITORY IF NOT EXISTS query_farm
    WITH PREFIX 'https://duckdb-extensions.query.farm';

INSTALL vgi FROM query_farm;
LOAD vgi FROM query_farm;

2. Attach the connector

Attach the release directly

Downloads the latest release for your platform and caches it locally.

ATTACH 'fixed' AS fixed (
  TYPE vgi,
  LOCATION 'github-auto://Query-farm/vgi-fixedformat'
);

3. Run a query

query.sql
SELECT *
FROM fixed.main.read_fixed('https://raw.githubusercontent.com/Query-farm/vgi-fixedformat/v0.12.0/data/accounts.dat', 'name:A10 qty:9(5)')
More example queries →
Technical details
Verified connector release
v0.13.1
Engine
2.0.1
VGI protocol
3.4.0
Verified on
December 1, 2026
Release notes on GitHub
Pin a version for production

When running the connector yourself, keep a specific release until you’re ready to upgrade. Replace the ATTACH statement above with this one and follow the same extension and credential setup.

Attach the release directly

Uses the verified release each time you attach the connector.

ATTACH 'fixed' AS fixed (
  TYPE vgi,
  LOCATION 'github-auto://Query-farm/[email protected]'
);

Overview

Fixed-width / Perl-unpack / Python-struct / COBOL-copybook record parsing and formatting for SQL.

Catalog

Everything fixed exposes once attached — read straight from the worker's released build.

fixed 1 schema
main 1 view · 11 functions

Fixed-width / copybook parsing, formatting, reading, and writing functions.

Schema examples (9)
Examples (9)

Decode a fixed-width record into a typed struct with a template spec.

SELECT fixed.main.unpack_fixed('JohnDoe  00042', 'A8 N');

Encode a struct back into a fixed-width record blob.

SELECT fixed.main.pack_fixed({'name': 'Jo', 'id': 7}, 'A2 N');

Introspect how a layout spec resolves — fields, types, byte offsets — without reading data.

SELECT * FROM fixed.main.describe_fixed('name:A10 qty:9(5)');

Write a relation out to a fixed-width file and report the write summary.

SELECT rows_written, bytes_written
FROM fixed.main.write_fixed((FROM (VALUES ('ALICE', 5)) AS v(name, qty)), '/tmp/fixed_example.dat', 'name:A10 qty:9(5)');
5 more examples

Scan a sample fixed-width accounts file (pinned to a release tag) into typed rows.

SELECT *
FROM fixed.main.read_fixed('https://raw.githubusercontent.com/Query-farm/vgi-fixedformat/v0.12.0/data/accounts.dat', 'name:A10 qty:9(5)');
Result
name qty
JOHN 42
JANE 100
BOB 7

Convert an ASCII newline feed (10-char name, 5-digit qty) into a fixed-length EBCDIC mainframe file with a packed-decimal COMP-3 quantity by piping read_fixed into write_fixed; returns 3 rows and 39 bytes (13-byte records, no separators).

SELECT rows_written, bytes_written
FROM fixed.main.write_fixed((FROM fixed.main.read_fixed('https://raw.githubusercontent.com/Query-farm/vgi-fixedformat/v0.12.0/data/accounts.dat', 'name:A10 qty:9(5)')), '/tmp/fixed_example_ebcdic.dat', '01 ACCT. 05 NAME PIC X(10). 05 QTY PIC S9(5) COMP-3.', encoding => 'ebcdic', framing => 'fixed');

Extract only the detail (D) records of a header/detail/trailer file with read_multi and write them to a flat sku/qty fixed-width file with write_fixed, dropping the header and trailer; returns 2 rows and 32 bytes.

SELECT rows_written, bytes_written
FROM fixed.main.write_fixed((SELECT d.sku, d.qty FROM (SELECT union_extract(record, 'D') AS d FROM fixed.main.read_multi('https://raw.githubusercontent.com/Query-farm/vgi-fixedformat/v0.12.0/data/multi.dat', '{"discriminator":{"offset":0,"width":1},"records":{"H":[{"type":"filler","width":1},{"name":"co","type":"str","width":20}],"D":[{"type":"filler","width":1},{"name":"sku","type":"str","width":10},{"name":"qty","type":"int","digits":5}],"T":[{"type":"filler","width":1},{"name":"cnt","type":"int","digits":6}]}}') WHERE union_tag(record) = 'D')), '/tmp/fixed_example_details.dat', 'sku:A10 qty:9(5)');

Reconcile a header/detail/trailer batch: report the header's company, the number of detail records and their total qty, the trailer's declared record count, and whether the detail count matches it (ACME CORP, 2 details, qty 49, trailer 2, balanced).

WITH r AS (SELECT record FROM fixed.main.read_multi('https://raw.githubusercontent.com/Query-farm/vgi-fixedformat/v0.12.0/data/multi.dat', '{"discriminator":{"offset":0,"width":1},"records":{"H":[{"type":"filler","width":1},{"name":"co","type":"str","width":20}],"D":[{"type":"filler","width":1},{"name":"sku","type":"str","width":10},{"name":"qty","type":"int","digits":5}],"T":[{"type":"filler","width":1},{"name":"cnt","type":"int","digits":6}]}}')) SELECT max(union_extract(record, 'H').co) AS company, count(*) FILTER (WHERE union_tag(record) = 'D') AS detail_records, sum(union_extract(record, 'D').qty) AS total_qty, max(union_extract(record, 'T').cnt) AS trailer_count, count(*) FILTER (WHERE union_tag(record) = 'D') = max(union_extract(record, 'T').cnt) AS balanced
FROM r;

Introspect how a layout spec resolves — one row per field with its dotted path, DuckDB type, byte offset, and width — without reading any data.

SELECT path, sql_type, byte_offset, width
FROM fixed.main.describe_fixed('name:A10 qty:9(5)')
ORDER BY byte_offset;
Views
spec_reference 2 examples4 cols

Reference registry of the worker's spec formats, encoding / framing / compression option tokens, and field-kind to DuckDB-type mappings.

Columns
topic VARCHAR
The vocabulary group: 'spec_format', 'encoding', 'framing', 'compression', or 'field_kind'.
token VARCHAR
The accepted option value within the topic, or the field-kind name for 'field_kind' rows.
maps_to VARCHAR
For 'field_kind' rows, the DuckDB column type the kind maps to; an empty string for the option-token rows.
description VARCHAR
A one-line explanation of the token.
Examples (2)

List the record-framing modes the worker accepts, with their meanings.

SELECT token, description
FROM fixed.main.spec_reference
WHERE topic = 'framing'
ORDER BY token;

Show how each layout field kind maps to a DuckDB column type.

SELECT token AS field_kind, maps_to AS duckdb_type
FROM fixed.main.spec_reference
WHERE topic = 'field_kind'
ORDER BY token;
Link
Scalar functions
pack_fixed (data ANY, spec VARCHAR, encoding VARCHAR) +1 overload 2 examples

Format a STRUCT into a fixed-width record blob using the given layout spec (template / JSON / copybook), emitting ASCII bytes; the inverse of unpack_fixed

Arguments
data ANY
The record to encode, as a `STRUCT` whose fields correspond to the layout's fields (the kind of value `unpack_fixed` returns).
spec VARCHAR
The layout describing how to lay the fields out: a Perl/Python `unpack` template string (e.g. 'A2 N'), a JSON field list, or a COBOL copybook. The format is auto-detected.
encoding VARCHAR
Byte encoding for the emitted record: 'ascii' (the default) or 'ebcdic' (CP037). Controls how text and zoned-number bytes are written.
Overloads
pack_fixed(data ANY, spec VARCHAR) → BLOBpack_fixed(data ANY, spec VARCHAR, encoding VARCHAR) → BLOB
ReturnsBLOB
Examples (2)

Pack a struct into an EBCDIC (CP037) record blob; the encoding also governs zoned/COMP-3 sign nibbles.

SELECT fixed.main.pack_fixed({'name': 'Jo', 'id': 7}, 'name:A2 id:N', 'ebcdic');

EBCDIC round-trip: unpack an EBCDIC record ('Jo' then a 4-byte big-endian 7) and pack it back with the same encoding, confirming the bytes are reproduced.

SELECT fixed.main.pack_fixed(fixed.main.unpack_fixed(rec, 'name:A2 id:N', 'ebcdic'), 'name:A2 id:N', 'ebcdic') = rec AS round_trips
FROM (SELECT '\xD1\x96\x00\x00\x00\x07'::BLOB AS rec);
Link
unpack_fixed (rec ANY, spec VARCHAR, encoding VARCHAR) +1 overload 2 examples

Parse a fixed-width record into a STRUCT using the given layout spec (template / JSON / copybook), assuming ASCII bytes

Arguments
rec ANY
A single fixed-width record to decode — one row's worth of bytes, laid out as described by `spec`.
spec VARCHAR
The layout describing the record's fields: a Perl/Python `unpack` template string (e.g. 'A8 N'), a JSON field list, or a COBOL copybook. The format is auto-detected. Determines the `STRUCT` field names and types.
encoding VARCHAR
Byte encoding of the record: 'ascii' (the default) or 'ebcdic' (CP037). Controls how text and zoned-number bytes are interpreted.
Overloads
unpack_fixed(rec ANY, spec VARCHAR) → STRUCT("name" VARCHAR, qty BIGINT)unpack_fixed(rec ANY, spec VARCHAR, encoding VARCHAR) → STRUCT(field_1 VARCHAR, field_2 VARCHAR)
ReturnsSTRUCT(field_1 VARCHAR, field_2 VARCHAR)
Examples (2)

Unpack an ASCII record by passing 'ascii' explicitly (the default).

SELECT fixed.main.unpack_fixed('JohnDoe 12345', 'A8 A5', 'ascii');

Unpack an EBCDIC (CP037) record; the encoding also governs zoned/COMP-3 sign nibbles.

SELECT fixed.main.unpack_fixed(rec, 'A8 N', 'ebcdic')
FROM (SELECT 'JohnDoe \x00\x00\x00\x2A'::BLOB AS rec);
Link
unpack_multi (rec ANY, spec VARCHAR, encoding VARCHAR) +1 overload 1 example

Parse one heterogeneous (multi-record-type) record into a DuckDB UNION using the multi-record spec, assuming ASCII bytes

Arguments
rec ANY
A single multi-record-type record to decode — one row's bytes, whose discriminator field picks the layout it is decoded with.
spec VARCHAR
The multi-record JSON layout: a `discriminator` ({offset, width}) plus a `records` map of record-type tag → JSON field list. Determines the UNION variants.
encoding VARCHAR
Byte encoding of the record: 'ascii' (the default) or 'ebcdic' (CP037).
Overloads
unpack_multi(rec ANY, spec VARCHAR) → ANYunpack_multi(rec ANY, spec VARCHAR, encoding VARCHAR) → ANY
ReturnsANY
Example

Decode one detail record into a UNION and read its tag + a field.

SELECT union_tag(u) AS kind, union_extract(u, 'D').sku AS sku
FROM (SELECT fixed.main.unpack_multi('DWIDGET    00042', '{"discriminator":{"offset":0,"width":1},"records":{"H":[{"type":"pad","width":1},{"name":"co","type":"str","width":20}],"D":[{"type":"pad","width":1},{"name":"sku","type":"str","width":10},{"name":"qty","type":"int","digits":5}]}}') AS u);
Link
Table functions
copy_fixed (spec := VARCHAR, format := VARCHAR, encoding := VARCHAR, framing := VARCHAR, record_length := BIGINT, compression := VARCHAR, max_decompressed_bytes := BIGINT, endpoint := VARCHAR, region := VARCHAR, url_style := VARCHAR, use_ssl := BOOLEAN)

Read a fixed-width / flat-file / COBOL-copybook file into the COPY target table (the COPY-FROM counterpart of read_fixed)

Named arguments
spec := VARCHAR
The record layout to decode each row with: a Perl/Python `unpack` template, a JSON field list, or a COBOL copybook. The decoded columns are assigned to the COPY target table's columns by position, so the spec must produce the same number of columns in the same order (each cast to the target column's type).
format := VARCHAR
Force how `spec` is interpreted: 'template', 'json', or 'copybook'. Omit to auto-detect.
encoding := VARCHAR
Byte encoding of the file: 'ascii' (the default) or 'ebcdic' (CP037). · default "ascii"
framing := VARCHAR
How records are delimited: 'newline' (the default), 'fixed', 'rdw', or 'rdw_blocked'. · default "newline"
record_length := BIGINT
The length of each record in BYTES; used only for 'fixed' framing. Defaults to the length implied by the layout `spec`.
compression := VARCHAR
Input compression: 'auto' (the default — detect gzip/zstd from the file's magic bytes, else read raw), 'none', 'gzip', or 'zstd'. Applies to local and cloud paths alike; decompression happens before framing/decoding. · default "auto"
max_decompressed_bytes := BIGINT
Safety cap on total DECOMPRESSED bytes per file (a decompression-bomb backstop; default 16 GiB). Only applies to gzip/zstd input. Raise it to load a legitimately huge compressed file.
endpoint := VARCHAR
Custom S3 endpoint for an `s3://` source (e.g. MinIO/R2 'host:9000'); overrides any endpoint from a CREATE SECRET.
region := VARCHAR
AWS region for an `s3://` source. Overrides the region from a CREATE SECRET.
url_style := VARCHAR
S3 addressing for an `s3://` source: 'path' (path-style, e.g. MinIO) or 'vhost'. · default "vhost"
use_ssl := BOOLEAN
Whether to use TLS for an `s3://` source's custom endpoint (default true).
Returns columns
name VARCHAR
The target column populated from the first decoded field (bytes 0–9).
qty INTEGER
The target column populated from the second decoded field, cast from the 5-digit value.
Returns columns · depends on the arguments
name VARCHAR
The target column populated from the first decoded field (bytes 0–9).
qty INTEGER
The target column populated from the second decoded field, cast from the 5-digit value.
Link
copy_to_fixed (spec := VARCHAR, format := VARCHAR, encoding := VARCHAR, framing := VARCHAR, compression := VARCHAR, endpoint := VARCHAR, region := VARCHAR, url_style := VARCHAR, use_ssl := BOOLEAN)

Write the COPY source out to a fixed-width / flat-file / COBOL-copybook file (the COPY-TO counterpart of write_fixed)

Named arguments
spec := VARCHAR
The record layout to encode each row with: a Perl/Python `unpack` template, a JSON field list, or a COBOL copybook. Each input column is matched to a layout field by name.
format := VARCHAR
Force how `spec` is interpreted: 'template', 'json', or 'copybook'. Omit to auto-detect.
encoding := VARCHAR
Byte encoding to write: 'ascii' (the default) or 'ebcdic' (CP037). · default "ascii"
framing := VARCHAR
How to delimit records in the output: 'newline' (the default), 'fixed', 'rdw', or 'rdw_blocked'. · default "newline"
compression := VARCHAR
Compress the output: 'auto' (the default — gzip if the path ends '.gz', zstd if '.zst', else raw), 'none', 'gzip', or 'zstd'. · default "auto"
endpoint := VARCHAR
Custom S3 endpoint for an `s3://` destination (e.g. MinIO/R2 'host:9000').
region := VARCHAR
AWS region for an `s3://` destination.
url_style := VARCHAR
S3 addressing for an `s3://` destination: 'path' (path-style, e.g. MinIO) or 'vhost'. · default "vhost"
use_ssl := BOOLEAN
Whether to use TLS for an `s3://` destination's custom endpoint (default true).
Returns columns
Count BIGINT
The number of source rows written to the file, reported by DuckDB as the `COPY … TO` statement's result.
Returns columns · depends on the arguments
Count BIGINT
The number of source rows written to the file, reported by DuckDB as the `COPY … TO` statement's result.
Link
describe_fixed (spec VARCHAR, format := VARCHAR) 2 examples

Describe a fixed-width layout spec (fields, types, offsets) without reading data

Positional arguments
spec VARCHAR
The record layout to describe: a Perl/Python `unpack` template, a JSON field list, or a COBOL copybook. Format is auto-detected unless `format` is given.
Named arguments
format := VARCHAR
Force how `spec` is interpreted: 'template', 'json', or 'copybook'. Omit to auto-detect.
Returns columns
path VARCHAR
Dotted field path within the record, e.g. `item.sku`; group items and their children are each a row.
depth BIGINT
Nesting level of the field (0 at the top level, deeper for group children).
kind VARCHAR
Codec label describing how the bytes are decoded, e.g. `text`, `int32 LE`, `comp-3`, `zoned`.
sql_type VARCHAR
The DuckDB column type this field maps to, e.g. `VARCHAR`, `DECIMAL(9,2)`, `STRUCT`, `BIGINT[]`.
byte_offset BIGINT
Static byte position of the field within the record (before any OCCURS DEPENDING ON table).
width BIGINT
Per-occurrence field width in bytes.
occurs BIGINT
Declared repeat / OCCURS maximum for a repeating field, else NULL.
depending_on VARCHAR
The controlling field name for an `OCCURS … DEPENDING ON` table, else NULL.
Examples (2)

Introspect a two-field template layout: show each field's DuckDB type, byte offset, and width.

SELECT path, sql_type, byte_offset, width
FROM fixed.main.describe_fixed('name:A10 qty:9(5)')
ORDER BY byte_offset;

Resolve a COBOL copybook (forcing the copybook format) and list only the repeating OCCURS fields.

SELECT path, sql_type, occurs
FROM fixed.main.describe_fixed('01 REC. 05 SKU PIC X(8). 05 QTY PIC 9(3) OCCURS 4.', format => 'copybook')
WHERE occurs IS NOT NULL;
Link
describe_multi (spec VARCHAR) 2 examples

Describe a multi-record spec (each record type's fields) without reading data

Arguments
spec VARCHAR
The multi-record JSON layout to describe: a `discriminator` ({offset, width}) plus a `records` map of record-type tag → JSON field list (same as read_multi).
Returns columns
record_type VARCHAR
The discriminator tag of the record type this field belongs to.
path VARCHAR
Dotted field path within that record type, e.g. `item.sku`.
depth BIGINT
Nesting level of the field (0 at the top level).
kind VARCHAR
Codec label describing how the bytes are decoded, e.g. `text`, `int32 LE`, `comp-3`.
sql_type VARCHAR
The DuckDB column type this field maps to, e.g. `VARCHAR`, `DECIMAL(9,2)`, `STRUCT`.
byte_offset BIGINT
Static byte position of the field within its record type.
width BIGINT
Per-occurrence field width in bytes.
occurs BIGINT
OCCURS maximum for a repeating field, else NULL.
depending_on VARCHAR
The controlling field name for an `OCCURS … DEPENDING ON` table, else NULL.
Examples (2)

Resolve a header/detail multi-record spec and show each record type's fields with their DuckDB types and byte offsets.

SELECT record_type, path, sql_type, byte_offset
FROM fixed.main.describe_multi('{"discriminator":{"offset":0,"width":1},"records":{"H":[{"name":"co","type":"str","width":20}],"D":[{"name":"sku","type":"str","width":10},{"name":"qty","type":"int","digits":5}]}}')
ORDER BY record_type, byte_offset;

Count how many fields each record type declares in a multi-record layout.

SELECT record_type, count(*) AS field_count
FROM fixed.main.describe_multi('{"discriminator":{"offset":0,"width":1},"records":{"H":[{"name":"co","type":"str","width":20}],"D":[{"name":"sku","type":"str","width":10},{"name":"qty","type":"int","digits":5}]}}')
GROUP BY record_type
ORDER BY record_type;
Link
read_fixed (path ANY, spec VARCHAR, format := VARCHAR, encoding := VARCHAR, framing := VARCHAR, record_length := BIGINT, compression := VARCHAR, max_decompressed_bytes := BIGINT, endpoint := VARCHAR, region := VARCHAR, url_style := VARCHAR, use_ssl := BOOLEAN) 2 examples

Read a fixed-width file (template / JSON / copybook spec) into rows

Positional arguments
path ANY
Path(s) to the fixed-width file(s) to read: a single path, or a list of paths to read several files in one call (their rows are concatenated in order). A path may be a glob (e.g. 'data/*.dat') to scan matching files in sorted order, or a cloud URL: 's3://bucket/key' (AWS S3, or R2/MinIO/GCS-HMAC via a `CREATE SECRET (TYPE s3, …, ENDPOINT …)`) or 'https://host/file'. Credentials come from the matching DuckDB secret, resolved per path scope — so a list spanning several buckets picks the right secret for each.
spec VARCHAR
The record layout to decode each row with: a Perl/Python `unpack` template, a JSON field list, or a COBOL copybook. Determines the output column names and types; format is auto-detected unless `format` is given.
Named arguments
format := VARCHAR
Force how `spec` is interpreted: 'template', 'json', or 'copybook'. Omit to auto-detect.
encoding := VARCHAR
Byte encoding of the file: 'ascii' (the default) or 'ebcdic' (CP037). · default "ascii"
framing := VARCHAR
How records are delimited in the file: 'newline' (the default), 'fixed' (back-to-back records of equal length), 'rdw', or 'rdw_blocked'. · default "newline"
record_length := BIGINT
The length of each record in BYTES. Used only for 'fixed' framing (back-to-back equal-length records); ignored for the other framings. Defaults to the length implied by the layout `spec`.
compression := VARCHAR
Input compression: 'auto' (the default — detect gzip/zstd from the file's magic bytes, else read raw), 'none', 'gzip', or 'zstd'. Applies to local and cloud paths alike; decompression happens before framing/decoding. · default "auto"
max_decompressed_bytes := BIGINT
Safety cap on total DECOMPRESSED bytes per file (a decompression-bomb backstop; default 16 GiB). Only applies to gzip/zstd input — uncompressed files are unbounded. Raise it to read a legitimately huge compressed file.
endpoint := VARCHAR
Custom S3 endpoint for an `s3://` path (e.g. MinIO/R2 'host:9000'); a scheme is inferred from `use_ssl` when omitted. Overrides any endpoint from a CREATE SECRET.
region := VARCHAR
AWS region for an `s3://` path. Overrides the region from a CREATE SECRET.
url_style := VARCHAR
S3 addressing for an `s3://` path: 'path' (path-style, e.g. MinIO) or 'vhost' (the default). Overrides a CREATE SECRET's URL_STYLE. · default "vhost"
use_ssl := BOOLEAN
Whether to use TLS for an `s3://` path's custom endpoint (default true). Set false for a plain-HTTP endpoint such as a local MinIO.
Returns columns
name VARCHAR
The 10-byte text field decoded from bytes 0–9.
qty BIGINT
The 5-digit zoned integer decoded from bytes 10–14.
id BIGINT
The 7-digit zoned integer decoded from bytes 0–6.
Returns columns · depends on the arguments
name VARCHAR
The 10-byte text field decoded from bytes 0–9.
qty BIGINT
The 5-digit zoned integer decoded from bytes 10–14.
id BIGINT
The 7-digit zoned integer decoded from bytes 0–6.
Examples (2)

Profile a newline-delimited fixed-width feed of 7-digit ids (a sample file pinned to a release tag): count the rows and report the id range.

SELECT count(*) AS records, min(id) AS min_id, max(id) AS max_id
FROM fixed.main.read_fixed('https://raw.githubusercontent.com/Query-farm/vgi-fixedformat/v0.12.0/data/large.dat', 'id:9(7)');

Read two account files at once (a list of paths or URLs; a local path may also be a glob such as 'data/acct*.dat') with a 10-char name and 5-digit qty, and total the quantity across every record.

SELECT sum(qty) AS total_qty
FROM fixed.main.read_fixed(['https://raw.githubusercontent.com/Query-farm/vgi-fixedformat/v0.12.0/data/acct1.dat', 'https://raw.githubusercontent.com/Query-farm/vgi-fixedformat/v0.12.0/data/acct2.dat'], 'name:A10 qty:9(5)');
Link
read_multi (path ANY, spec VARCHAR, encoding := VARCHAR, framing := VARCHAR, record_length := BIGINT, compression := VARCHAR, max_decompressed_bytes := BIGINT, endpoint := VARCHAR, region := VARCHAR, url_style := VARCHAR, use_ssl := BOOLEAN) 4 examples

Read a heterogeneous (multi-record-type) flat file into a UNION column

Positional arguments
path ANY
Path(s) to the file(s) to read: a single path or a list of paths. May glob (e.g. 'data/*.dat') or be a cloud URL ('s3://bucket/key' or 'https://host/file'). Credentials come from the matching DuckDB secret, scoped per path.
spec VARCHAR
The multi-record JSON layout: a `discriminator` ({offset, width}) plus a `records` map of record-type tag → JSON field list (the same field syntax as read_fixed's JSON spec). An optional `default` tag handles unmatched values. Determines the UNION variants of the output `record` column.
Named arguments
encoding := VARCHAR
Byte encoding of the file: 'ascii' (the default) or 'ebcdic' (CP037). The discriminator bytes are transcoded out of EBCDIC before matching. · default "ascii"
framing := VARCHAR
How records are delimited: 'newline' (the default), 'fixed' (back-to-back equal-length records — every record type padded to a common length), 'rdw', or 'rdw_blocked'. · default "newline"
record_length := BIGINT
Per-record length in BYTES for 'fixed' framing; ignored otherwise. Defaults to the longest record type's layout length.
compression := VARCHAR
Input compression: 'auto' (default — detect gzip/zstd from magic bytes), 'none', 'gzip', or 'zstd'. Decompression happens before framing/decoding. · default "auto"
max_decompressed_bytes := BIGINT
Safety cap on total DECOMPRESSED bytes per file (default 16 GiB). Only applies to gzip/zstd input.
endpoint := VARCHAR
Custom S3 endpoint for an `s3://` path (e.g. MinIO/R2 'host:9000'); a scheme is inferred from `use_ssl` when omitted. Overrides any endpoint from a CREATE SECRET.
region := VARCHAR
AWS region for an `s3://` path. Overrides the region from a CREATE SECRET.
url_style := VARCHAR
S3 addressing for an `s3://` path: 'path' (path-style, e.g. MinIO) or 'vhost' (the default). Overrides a CREATE SECRET's URL_STYLE. · default "vhost"
use_ssl := BOOLEAN
Whether to use TLS for an `s3://` path's custom endpoint (default true). Set false for a plain-HTTP endpoint such as a local MinIO.
Returns columns
record UNION of 3 branches
A sparse UNION with one `STRUCT` variant per record type in the spec — here `H` (header), `D` (detail), and `T` (trailer).
UNION one of 3 branches · pick one with union_value(<branch> := …)
  • H co STRUCT
    • coVARCHAR
  • D sku · qty STRUCT
    • skuVARCHAR
    • qtyBIGINT
  • T cnt STRUCT
    • cntBIGINT
Returns columns · depends on the arguments
record UNION of 3 branches
A sparse UNION with one `STRUCT` variant per record type in the spec — here `H` (header), `D` (detail), and `T` (trailer).
UNION one of 3 branches · pick one with union_value(<branch> := …)
  • H co STRUCT
    • coVARCHAR
  • D sku · qty STRUCT
    • skuVARCHAR
    • qtyBIGINT
  • T cnt STRUCT
    • cntBIGINT
Examples (4)

Read an undelimited header/detail/trailer file (every record type padded to one 21-byte length, so framing => 'fixed') into a UNION column and project the detail rows' sku and qty.

SELECT union_extract(record, 'D').sku AS sku,
  union_extract(record, 'D').qty AS qty
FROM fixed.main.read_multi('https://raw.githubusercontent.com/Query-farm/vgi-fixedformat/v0.12.0/data/multi_fixed.dat', '{"discriminator":{"offset":0,"width":1},"records":{"H":[{"type":"filler","width":1},{"name":"co","type":"str","width":20}],"D":[{"type":"filler","width":1},{"name":"sku","type":"str","width":10},{"name":"qty","type":"int","digits":5},{"type":"filler","width":5}],"T":[{"type":"filler","width":1},{"name":"cnt","type":"int","digits":6},{"type":"filler","width":14}]}}', framing => 'fixed')
WHERE union_tag(record) = 'D'
ORDER BY sku;

Count records of each type in a multi-record file that contains an unknown record type ('Z'): the spec's "default": "D" decodes it as a detail record instead of failing the read.

SELECT union_tag(record) AS record_type, count(*) AS n
FROM fixed.main.read_multi('https://raw.githubusercontent.com/Query-farm/vgi-fixedformat/v0.12.0/data/multi_bad.dat', '{"discriminator":{"offset":0,"width":1},"records":{"H":[{"type":"filler","width":1},{"name":"co","type":"str","width":20}],"D":[{"type":"filler","width":1},{"name":"sku","type":"str","width":10},{"name":"qty","type":"int","digits":5}],"T":[{"type":"filler","width":1},{"name":"cnt","type":"int","digits":6}]},"default":"D"}')
GROUP BY record_type
ORDER BY record_type;

Extract only the detail (D) records of a header/detail/trailer file with read_multi and write them to a flat sku/qty fixed-width file with write_fixed, dropping the header and trailer; returns 2 rows and 32 bytes.

SELECT rows_written, bytes_written
FROM fixed.main.write_fixed((SELECT d.sku, d.qty FROM (SELECT union_extract(record, 'D') AS d FROM fixed.main.read_multi('https://raw.githubusercontent.com/Query-farm/vgi-fixedformat/v0.12.0/data/multi.dat', '{"discriminator":{"offset":0,"width":1},"records":{"H":[{"type":"filler","width":1},{"name":"co","type":"str","width":20}],"D":[{"type":"filler","width":1},{"name":"sku","type":"str","width":10},{"name":"qty","type":"int","digits":5}],"T":[{"type":"filler","width":1},{"name":"cnt","type":"int","digits":6}]}}') WHERE union_tag(record) = 'D')), '/tmp/fixed_example_details.dat', 'sku:A10 qty:9(5)');
1 more example

Reconcile a header/detail/trailer batch: report the header's company, the number of detail records and their total qty, the trailer's declared record count, and whether the detail count matches it (ACME CORP, 2 details, qty 49, trailer 2, balanced).

WITH r AS (SELECT record FROM fixed.main.read_multi('https://raw.githubusercontent.com/Query-farm/vgi-fixedformat/v0.12.0/data/multi.dat', '{"discriminator":{"offset":0,"width":1},"records":{"H":[{"type":"filler","width":1},{"name":"co","type":"str","width":20}],"D":[{"type":"filler","width":1},{"name":"sku","type":"str","width":10},{"name":"qty","type":"int","digits":5}],"T":[{"type":"filler","width":1},{"name":"cnt","type":"int","digits":6}]}}')) SELECT max(union_extract(record, 'H').co) AS company, count(*) FILTER (WHERE union_tag(record) = 'D') AS detail_records, sum(union_extract(record, 'D').qty) AS total_qty, max(union_extract(record, 'T').cnt) AS trailer_count, count(*) FILTER (WHERE union_tag(record) = 'D') = max(union_extract(record, 'T').cnt) AS balanced
FROM r;
Link
Table in-out functions
write_fixed (data TABLE, path VARCHAR, spec VARCHAR, format := VARCHAR, encoding := VARCHAR, framing := VARCHAR, compression := VARCHAR, endpoint := VARCHAR, region := VARCHAR, url_style := VARCHAR, use_ssl := BOOLEAN) 3 examples

Write a relation to a fixed-width file (inverse of read_fixed)

Positional arguments
data TABLE
The input relation to write out, supplied as a subquery (e.g. `(FROM tbl)`). Each row's columns are matched by name to the layout fields.
path VARCHAR
Path of the fixed-width file to create; it is overwritten if it already exists. May also be an 's3://bucket/key' URL (AWS S3, or R2/MinIO/GCS-HMAC via a `CREATE SECRET (TYPE s3, …, ENDPOINT …)`) — credentials come from the matching DuckDB secret, scoped to the URL. Writing to 'http(s)://' is not supported.
spec VARCHAR
The record layout to encode each row with: a Perl/Python `unpack` template, a JSON field list, or a COBOL copybook. Format is auto-detected unless `format` is given.
Named arguments
format := VARCHAR
Force how `spec` is interpreted: 'template', 'json', or 'copybook'. Omit to auto-detect.
encoding := VARCHAR
Byte encoding to write: 'ascii' (the default) or 'ebcdic' (CP037). · default "ascii"
framing := VARCHAR
How to delimit records in the output: 'newline' (the default), 'fixed', 'rdw', or 'rdw_blocked'. · default "newline"
compression := VARCHAR
Compress the output: 'auto' (the default — gzip if the path ends '.gz', zstd if '.zst', else raw), 'none', 'gzip', or 'zstd'. The whole file is compressed. · default "auto"
endpoint := VARCHAR
Custom S3 endpoint for an `s3://` path (e.g. MinIO/R2 'host:9000'); a scheme is inferred from `use_ssl` when omitted. Overrides any endpoint from a CREATE SECRET.
region := VARCHAR
AWS region for an `s3://` path. Overrides the region from a CREATE SECRET.
url_style := VARCHAR
S3 addressing for an `s3://` path: 'path' (path-style, e.g. MinIO) or 'vhost' (the default). Overrides a CREATE SECRET's URL_STYLE. · default "vhost"
use_ssl := BOOLEAN
Whether to use TLS for an `s3://` path's custom endpoint (default true). Set false for a plain-HTTP endpoint such as a local MinIO.
Returns columns
rows_written BIGINT
Number of records written to the file.
bytes_written BIGINT
Total number of bytes written to the file, including record framing and any compression.
Examples (3)

Write two accounts to a newline-framed fixed-width file (10-char name, 5-digit quantity) and report how much was written.

SELECT rows_written, bytes_written
FROM fixed.main.write_fixed((FROM (VALUES ('ALICE', 5), ('BOB', 999)) AS v(name, qty)), '/tmp/fixed_example_write.dat', 'name:A10 qty:9(5)');

Write back-to-back fixed-length records (no newline) by forcing the framing named argument, returning just the record count.

SELECT rows_written
FROM fixed.main.write_fixed((FROM (VALUES ('ALICE', 5), ('BOB', 999)) AS v(name, qty)), '/tmp/fixed_example_write.dat', 'name:A10 qty:9(5)', framing => 'fixed');

Convert an ASCII newline feed (10-char name, 5-digit qty) into a fixed-length EBCDIC mainframe file with a packed-decimal COMP-3 quantity by piping read_fixed into write_fixed; returns 3 rows and 39 bytes (13-byte records, no separators).

SELECT rows_written, bytes_written
FROM fixed.main.write_fixed((FROM fixed.main.read_fixed('https://raw.githubusercontent.com/Query-farm/vgi-fixedformat/v0.12.0/data/accounts.dat', 'name:A10 qty:9(5)')), '/tmp/fixed_example_ebcdic.dat', '01 ACCT. 05 NAME PIC X(10). 05 QTY PIC S9(5) COMP-3.', encoding => 'ebcdic', framing => 'fixed');
Link
write_multi (data TABLE, path VARCHAR, spec VARCHAR, encoding := VARCHAR, framing := VARCHAR, compression := VARCHAR, endpoint := VARCHAR, region := VARCHAR, url_style := VARCHAR, use_ssl := BOOLEAN) 1 example

Write a relation's UNION column to a multi-record-type file (inverse of read_multi)

Positional arguments
data TABLE
The input relation to write out, supplied as a subquery (e.g. `(FROM read_multi(...))`). It must have exactly ONE column: a UNION whose variant names are the discriminator tags of `spec`.
path VARCHAR
Path of the multi-record file to create; it is overwritten if it already exists. May also be an 's3://bucket/key' URL (AWS S3, or R2/MinIO/GCS-HMAC via a `CREATE SECRET (TYPE s3, …, ENDPOINT …)`) — credentials come from the matching DuckDB secret, scoped to the URL. Writing to 'http(s)://' is not supported.
spec VARCHAR
The multi-record JSON layout (the same spec read_multi uses): a `discriminator` ({offset, width}) plus a `records` map of record-type tag → JSON field list. The UNION column's variant names must match these tags.
Named arguments
encoding := VARCHAR
Byte encoding to write: 'ascii' (the default) or 'ebcdic' (CP037). The discriminator tag is transcoded to this encoding. · default "ascii"
framing := VARCHAR
How to delimit records in the output: 'newline' (the default), 'fixed', 'rdw', or 'rdw_blocked'. · default "newline"
compression := VARCHAR
Compress the output: 'auto' (the default — gzip if the path ends '.gz', zstd if '.zst', else raw), 'none', 'gzip', or 'zstd'. The whole file is compressed. · default "auto"
endpoint := VARCHAR
Custom S3 endpoint for an `s3://` path (e.g. MinIO/R2 'host:9000'); a scheme is inferred from `use_ssl` when omitted. Overrides any endpoint from a CREATE SECRET.
region := VARCHAR
AWS region for an `s3://` path. Overrides the region from a CREATE SECRET.
url_style := VARCHAR
S3 addressing for an `s3://` path: 'path' (path-style, e.g. MinIO) or 'vhost' (the default). Overrides a CREATE SECRET's URL_STYLE. · default "vhost"
use_ssl := BOOLEAN
Whether to use TLS for an `s3://` path's custom endpoint (default true). Set false for a plain-HTTP endpoint such as a local MinIO.
Returns columns
rows_written BIGINT
Number of records written to the file across all record types.
bytes_written BIGINT
Total number of bytes written to the file, including record framing and any compression.
Example

Round-trip a heterogeneous flat file: read it into a UNION column and write it back out to a new multi-record file, reporting the counts.

SELECT rows_written, bytes_written
FROM fixed.main.write_multi((FROM fixed.main.read_multi('https://raw.githubusercontent.com/Query-farm/vgi-fixedformat/v0.12.0/data/multi.dat', '{"discriminator":{"offset":0,"width":1},"records":{"H":[{"type":"filler","width":1},{"name":"co","type":"str","width":20}],"D":[{"type":"filler","width":1},{"name":"sku","type":"str","width":10},{"name":"qty","type":"int","digits":5}],"T":[{"type":"filler","width":1},{"name":"cnt","type":"int","digits":6}]}}')), '/tmp/fixed_example_multi_out.dat', '{"discriminator":{"offset":0,"width":1},"records":{"H":[{"type":"filler","width":1},{"name":"co","type":"str","width":20}],"D":[{"type":"filler","width":1},{"name":"sku","type":"str","width":10},{"name":"qty","type":"int","digits":5}],"T":[{"type":"filler","width":1},{"name":"cnt","type":"int","digits":6}]}}');
Link

COPY formats

Attaching fixed also registers 2 file formats for DuckDB's own COPY statement, so you can load files into local tables and write query results out to files without a function call. The FORMAT name starts with the ATTACH alias — fixed with the Quick start above; use yours if you attach it under another name.

FORMAT 'fixed.fixed'

COPY … FROM · import

Load Fixed-Width File (COPY FROM). Load a fixed-width / flat-file / COBOL-copybook file into the COPY target table

copy.sql
-- Load a file into an existing local table
COPY my_table FROM 'data.fixed' (FORMAT 'fixed.fixed');

Options

Pass these inside the COPY statement's parentheses, after FORMAT. Unknown options are rejected.

specVARCHAR
The record layout to decode each row with: a Perl/Python `unpack` template, a JSON field list, or a COBOL copybook. The decoded columns are assigned to the COPY target table's columns by position, so the spec must produce the same number of columns in the same order (each cast to the target column's type).
formatVARCHAR
Force how `spec` is interpreted: 'template', 'json', or 'copybook'. Omit to auto-detect.
encodingVARCHAR
Byte encoding of the file: 'ascii' (the default) or 'ebcdic' (CP037).
framingVARCHAR
How records are delimited: 'newline' (the default), 'fixed', 'rdw', or 'rdw_blocked'.
record_lengthBIGINT
The length of each record in BYTES; used only for 'fixed' framing. Defaults to the length implied by the layout `spec`.
compressionVARCHAR
Input compression: 'auto' (the default — detect gzip/zstd from the file's magic bytes, else read raw), 'none', 'gzip', or 'zstd'. Applies to local and cloud paths alike; decompression happens before framing/decoding.
max_decompressed_bytesBIGINT
Safety cap on total DECOMPRESSED bytes per file (a decompression-bomb backstop; default 16 GiB). Only applies to gzip/zstd input. Raise it to load a legitimately huge compressed file.
endpointVARCHAR
Custom S3 endpoint for an `s3://` source (e.g. MinIO/R2 'host:9000'); overrides any endpoint from a CREATE SECRET.
regionVARCHAR
AWS region for an `s3://` source. Overrides the region from a CREATE SECRET.
url_styleVARCHAR
S3 addressing for an `s3://` source: 'path' (path-style, e.g. MinIO) or 'vhost'.
use_sslBOOLEAN
Whether to use TLS for an `s3://` source's custom endpoint (default true).
Full reference

Load a fixed-width file into a table:

COPY <table> FROM '<path>' (FORMAT 'fixed.fixed', spec '<layout>');

Decoded columns map to the target table's columns by position (cast to each type). Named options: spec (required), format, encoding, framing, record_length, and S3 overrides. The COPY-FROM counterpart of read_fixed.

FORMAT 'fixed.fixed_out'

COPY … TO · export

Write Fixed-Width File (COPY TO). Write the COPY source out to a fixed-width / flat-file / COBOL-copybook file

copy.sql
-- Write a query's rows out to a file
COPY (SELECT * FROM my_table) TO 'out.fixed' (FORMAT 'fixed.fixed_out');

Options

Pass these inside the COPY statement's parentheses, after FORMAT. Unknown options are rejected.

specVARCHAR
The record layout to encode each row with: a Perl/Python `unpack` template, a JSON field list, or a COBOL copybook. Each input column is matched to a layout field by name.
formatVARCHAR
Force how `spec` is interpreted: 'template', 'json', or 'copybook'. Omit to auto-detect.
encodingVARCHAR
Byte encoding to write: 'ascii' (the default) or 'ebcdic' (CP037).
framingVARCHAR
How to delimit records in the output: 'newline' (the default), 'fixed', 'rdw', or 'rdw_blocked'.
compressionVARCHAR
Compress the output: 'auto' (the default — gzip if the path ends '.gz', zstd if '.zst', else raw), 'none', 'gzip', or 'zstd'.
endpointVARCHAR
Custom S3 endpoint for an `s3://` destination (e.g. MinIO/R2 'host:9000').
regionVARCHAR
AWS region for an `s3://` destination.
url_styleVARCHAR
S3 addressing for an `s3://` destination: 'path' (path-style, e.g. MinIO) or 'vhost'.
use_sslBOOLEAN
Whether to use TLS for an `s3://` destination's custom endpoint (default true).
Full reference

Write a relation to a fixed-width file:

COPY (<query>|<table>) TO '<path>' (FORMAT 'fixed.fixed_out', spec '<layout>');

Input columns map to layout fields by name. Named options: spec (required), format, encoding, framing, and S3 overrides. The COPY-TO counterpart of write_fixed.

Try these queries

Decode a fixed-width record into a typed struct with a template spec.

SELECT fixed.main.unpack_fixed('JohnDoe  00042', 'A8 N')

Uses unpack_fixed

Encode a struct back into a fixed-width record blob.

SELECT fixed.main.pack_fixed({'name': 'Jo', 'id': 7}, 'A2 N')

Uses pack_fixed

Introspect how a layout spec resolves — fields, types, byte offsets — without reading data.

SELECT * FROM fixed.main.describe_fixed('name:A10 qty:9(5)')

Uses describe_fixed

Write a relation out to a fixed-width file and report the write summary.

SELECT rows_written, bytes_written
FROM fixed.main.write_fixed((FROM (VALUES ('ALICE', 5)) AS v(name, qty)), '/tmp/fixed_example.dat', 'name:A10 qty:9(5)')

Uses write_fixed

Reconcile a header/detail/trailer batch: report the header's company, the number of detail records and their total qty, the trailer's declared record count, and whether the detail count matches it (ACME CORP, 2 details, qty 49, trailer 2, balanced).

WITH r AS (SELECT record FROM fixed.main.read_multi('https://raw.githubusercontent.com/Query-farm/vgi-fixedformat/v0.12.0/data/multi.dat', '{"discriminator":{"offset":0,"width":1},"records":{"H":[{"type":"filler","width":1},{"name":"co","type":"str","width":20}],"D":[{"type":"filler","width":1},{"name":"sku","type":"str","width":10},{"name":"qty","type":"int","digits":5}],"T":[{"type":"filler","width":1},{"name":"cnt","type":"int","digits":6}]}}')) SELECT max(union_extract(record, 'H').co) AS company, count(*) FILTER (WHERE union_tag(record) = 'D') AS detail_records, sum(union_extract(record, 'D').qty) AS total_qty, max(union_extract(record, 'T').cnt) AS trailer_count, count(*) FILTER (WHERE union_tag(record) = 'D') = max(union_extract(record, 'T').cnt) AS balanced
FROM r

Uses read_multi

write_then_read_fixed — Write a relation out to a fixed-width file with COPY ... TO and scan it straight back into typed rows with read_fixed.

COPY (FROM (VALUES ('ALICE', 5), ('BOB', 7)) AS v(name, qty)) TO '/tmp/fixed_executable_example.dat' (FORMAT 'fixed.fixed_out', spec 'name:A10 qty:9(5)');
SELECT name, qty FROM fixed.main.read_fixed('/tmp/fixed_executable_example.dat', 'name:A10 qty:9(5)') ORDER BY name;

Uses read_fixed

1 more example

unpack_pack_roundtrip — Decode a fixed-width record into a typed struct, then encode that struct back into the original record bytes — pack_fixed and unpack_fixed are exact inverses.

SELECT fixed.main.unpack_fixed('JohnDoe  00042', 'name:A8 qty:9(5)') AS decoded;
SELECT fixed.main.pack_fixed(fixed.main.unpack_fixed('JohnDoe  00042', 'name:A8 qty:9(5)'), 'name:A8 qty:9(5)')::VARCHAR = 'JohnDoe  00042' AS round_trips;

Uses unpack_fixedpack_fixed

20 more examples in the Catalog, each listed under the table or function it uses.

Fixed-width files is an independent open-source connector from Query.Farm. It is not affiliated with, endorsed by or sponsored by the services, projects or organisations it works with. Product names, logos and trademarks belong to their respective owners.