CalcSnippets Search
Database 2 min read

`psql -f` Is the Postgres Command You Should Use When a SQL Script Needs to Run the Same Way Every Time

A practical guide to `psql -f` for applying schema, seed, or admin scripts repeatably instead of pasting SQL into an interactive session and hoping for the best.

Why this matters: a lot of database work becomes risky and unreviewable the moment someone pastes SQL into a live shell instead of running a real script.

If a change needs to be repeated, reviewed, or shared, psql -f is one of the simplest ways to make that happen.

The basic form

Run a script file:

psql -d mydb -f schema.sql

That is already a better workflow than opening an interactive prompt and copy-pasting chunks by hand.

Why script execution is better than paste-driven DB work

When SQL lives in a file:

  1. it can be reviewed
  2. it can be versioned
  3. it can be rerun
  4. it can be shared between people and environments

When it lives only in scrollback, your operational story gets much weaker.

Combine it with stop-on-error behavior

For many operational scripts, you want failure to stop the run:

psql -v ON_ERROR_STOP=1 -d mydb -f schema.sql

This is especially useful for:

  1. schema changes
  2. grants and permissions
  3. seed data
  4. one-off maintenance scripts

Without it, later statements might continue after an early failure, which can make the end state harder to reason about.

Final recommendation

If a SQL operation matters enough to repeat or explain, put it in a file and run it with psql -f. It is one of the easiest upgrades from improvisation to something more trustworthy.

Sources

Keep reading

Related guides