psql is PostgreSQL's interactive command-line client. The examples below assume the database server is running and your account has the required privileges.Connect
bash_snippet
Bash · 2 lines|
| psql --version |
| psql -h localhost -p 5432 -U myuser -d mydb |
Authentication depends on server configuration. You do not have to switch to the operating system's
postgres user if another authorized account can connect. For a container, docker exec -it <container> psql -U myuser -d mydb is one option.Explore in psql
plain text_snippet
Plain Text · 5 lines|
| \l list databases |
| \c mydb connect to a database |
| \dt list tables in the current schema |
| \d mytable describe a relation |
| \q quit |
These are
psql meta-commands, not SQL statements.Create or remove a database
sql_snippet
SQL · 2 lines|
| CREATE DATABASE example OWNER myuser; |
| DROP DATABASE example; |
Database creation and deletion require appropriate privileges.
DROP DATABASE is destructive, cannot be run while connected to that database, and may fail if other sessions are connected. Verify the target and backups before executing it.Import a SQL backup
From the shell, not the
psql prompt:bash_snippet
Bash · 1 line|
| psql -h localhost -U myuser -d mydb -v ON_ERROR_STOP=1 -f backup.sql |
This applies a plain SQL script to an existing database; errors can leave earlier statements applied unless you arrange an appropriate transaction. A custom-format archive requires
pg_restore, not direct input to psql. Avoid putting passwords on the command line.✦ 卷终 · 柯航存卷 ✦