Separate Your PostgreSQL Query History by Environment
If you regularly connect to multiple PostgreSQL databases—especially both development and production environments—you've probably experienced that moment of dread when scrolling through your psql history. Was that DELETE statement from dev or prod? Why is that experimental query from last week's debugging session appearing while you're trying to carefully craft a production fix?
How psql Stores History
By default, psql stores your command history in: ~/.psql_history. Every query, regardless of which database, user, or host, gets appended to this file.
When you press the up arrow or use Ctrl+R to search history, psql reads from this unified history file.
Environment-Specific History Files
Add this line to your `~/.psqlrc:
\set HISTFILE ~/.psql_history-:DBNAME-:USER@:HOSTWith this configuration, psql will create distinct history files for each unique combination of database name, username, and host. For example:
~/.psql_history-myapp_dev-shantanulocalhostfor your local development~/.psql_history-myapp_prod-postgres@prod.example.comfor production~/.psql_history-analytics-readonly@analytics.example.comfor your analytics read replica
Now when you connect to postgres server, you'll only see commands you've previously run against that db.
No more accidental auto-completions from development experiments, no more scrolling through irrelevant queries.
Each environment maintains its own clean, contextual history.