CODE/2022-09-15

Essential PostgreSQL Commands with psql

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.
COMPANION ESSAYS / 思想脉络与互照篇目
同卷深读2026-05-22 ·

Installing Python 3 Alongside System Python on CentOS 7

同属「系统工程卷」脉络衍生思考与工程推演推演阅读 →
跨界互照2026-08-22 ·

我的书架:03|金融经管:经济运行、金融体系与企业治理

我的书架:03|金融经管:经济运行、金融体系与企业治理

跨领域对照思辨 · 从「思想随笔」视界互为印证推演阅读 →
RELATED INDEX / 相关阅读索引
柯航hang.ke·© 2014—2026
CC BY-NC 4.0·