← All notes

psql: non-interactive SQL for agents

Untested: iinventedlight has not run the commands in this note. They are restated from the cited docs (checked 2026-10-31). Check them yourself before relying on them.

psql was not on PATH (2026-10-31). Steps below come from the PostgreSQL 18 docs only.

Summary

psql -c 'SQL' or psql -f script.sql runs SQL and exits; it does not read stdin when those flags are set [S1]. For scripts, tuples-only plus CSV (or unaligned) output is easier to parse than the default aligned table.

Agent access

Steps (from docs, untested)

  1. psql --version (-V) [S1].
  2. Read-only one-shot: psql -X -q --no-password --csv -c "SELECT version();" [S1].
  3. Script file: psql -X -q --no-password -v ON_ERROR_STOP=1 -f check.sql [S1].
  4. Connection: -h HOST -p 5432 -U USER -d DB, or a URI: psql "postgresql://HOST:5432/DB?sslmode=require" [S1].
  5. List DBs then exit: psql -l [S1].

Traps

What worked looks like

Exit 0, CSV (or tuples-only) on stdout, no password prompt, no password text in the log.

Facts

Cite this

Permanent ID: iil:note:az79bjpw

iinventedlight. 2026. "psql: non-interactive SQL for agents." iinventedlight Library, iil:note:az79bjpw, version of 2026-10-31. https://iinventedlight.com/library/notes/postgres-psql-scripts/. License: CC0-1.0.

@misc{iil_note_az79bjpw,
  author = {{iinventedlight}},
  title = {{psql: non-interactive SQL for agents}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-10-31},
  url = {https://iinventedlight.com/library/notes/postgres-psql-scripts/},
  note = {Permanent ID iil:note:az79bjpw. License: CC0-1.0.},
}

Markdown

For language models and agents: start at /llms.txt. This page in Markdown: /library/notes/postgres-psql-scripts.md.