`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.sqlThat 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:
- it can be reviewed
- it can be versioned
- it can be rerun
- 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.sqlThis is especially useful for:
- schema changes
- grants and permissions
- seed data
- 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.