You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This appendix summarizes essential PostgreSQL commands, queries, and Docker workflows used throughout the series.
It’s designed as a one-stop operational cheat sheet — the “what and how” without the full theory.
1. PostgreSQL Quick Start
Start PostgreSQL with Docker
docker run --name postgres -e POSTGRES_PASSWORD=mysecretpassword -p 5432:5432 -d postgres
Connect via psql
docker exec -it postgres psql -U postgres
Because this runs psql inside the container, it usually connects over the local Unix socket and will not prompt for a
password.
Exit psql
\q
2. psql Meta-Commands
Command
Purpose
\l
List databases
\c dbname
Connect to database
\dn
List schemas
\dt
List tables
\dv
List views
\df
List functions
\di
List indexes
\d table_name
Describe table columns and constraints
\d+ table_name
Show detailed table information
\timing
Toggle query timing
\x
Toggle expanded display
\set
List or set variables
\!
Execute shell command from within psql
\password
Change password for current user
3. Common SQL Admin Tasks
Operation
Command
Create a new database
CREATE DATABASE mydb;
Drop a database
DROP DATABASE mydb;
Create user
CREATE ROLE alice LOGIN PASSWORD 'secret';
Grant privileges
GRANT ALL PRIVILEGES ON DATABASE mydb TO alice;
View current connections
SELECT * FROM pg_stat_activity;
Kill a backend
SELECT pg_terminate_backend(pid);
Analyze statistics
ANALYZE;
Manual vacuum
VACUUM;
Compact table
VACUUM FULL table_name;
Rebuild index
REINDEX INDEX idx_name;
Force checkpoint
CHECKPOINT;
4. Query Tuning & Monitoring
Query Plan and Timing
EXPLAIN
SELECT*FROM table_name
WHERE
column ='value';
EXPLAIN ANALYZE
SELECT*FROM table_name
WHERE
column ='value';
I/O and Buffer Use
EXPLAIN (ANALYZE, BUFFERS)
SELECT*FROM table_name
WHERE
column >100;
Cache Hit Ratio
SELECT datname,
blks_hit::float / nullif(blks_hit + blks_read, 0) AS cache_hit_ratio
FROM pg_stat_database;
Top Queries by Execution Time
SELECT query, total_exec_time, calls
FROM pg_stat_statements
ORDER BY total_exec_time DESCLIMIT5;
Requires pg_stat_statements to be preloaded via shared_preload_libraries.
Table and Index Sizes
SELECT relname AS name,
pg_size_pretty(pg_total_relation_size(relid)) AS total_size
FROMpg_catalog.pg_statio_user_tables;