Practical PostgreSQL tips
A collection of tips for everyday work with PostgreSQL.
Export the schema (DDL) for an entire database, including comments
If you want to export the definitions of all tables in a database (DDL) and include comments (COMMENT), here are several common approaches.
Method 1: Use pg_dump (recommended)
PostgreSQL includes pg_dump, which can export the schema without data and include comments.
pg_dump -U 用户名 -d 数据库名 -s -f schema.sql
Options:
| Option | Meaning |
|---|---|
-U username | User to connect as |
-d database | Database name |
-s | Export only the schema (DDL), without data |
-f schema.sql | Output file path |
The resulting schema.sql contains:
CREATE TABLEstatements for all tables- DDL for indexes, constraints, sequences, views, and other objects
- Comments, including
COMMENT ON TABLEandCOMMENT ON COLUMN
Example:
pg_dump -U postgres -d mydb -s -f /tmp/mydb_schema.sql
Method 2: Export a particular schema
To export the table definitions in just one schema:
pg_dump -U 用户名 -d 数据库名 -n schema_name -s -f schema_name.sql
For example:
pg_dump -U postgres -d mydb -n public -s -f public_schema.sql
Method 3: Use pg_get_tabledef() (PostgreSQL 16+)
Starting with PostgreSQL 16, the original tip describes a native function for returning the complete CREATE TABLE statement:
SELECT pg_get_tabledef('public.my_table'::regclass);
⚠️ Warning: This tip identifies the function as available only in PostgreSQL 16+, not earlier versions.
Method 4: Export through the pgAdmin or DBeaver GUI
In a graphical tool such as pgAdmin or DBeaver:
- Right-click the database or schema → Generate SQL → DDL Script.
- Choose whether to include:
- Tables
- Views
- Comments
- Indexes
- Sequences
- Export to generate the full DDL with comments.
Method 5: Query system tables to export comments
Export comments on all tables:
SELECT
'COMMENT ON TABLE ' || c.relname || ' IS ''' || d.description || ''';'
FROM pg_class c
JOIN pg_description d ON c.oid = d.objoid
WHERE c.relkind = 'r'
AND d.objsubid = 0;
Export comments on all columns:
SELECT
'COMMENT ON COLUMN ' || c.relname || '.' || a.attname || ' IS ''' || d.description || ''';'
FROM pg_description d
JOIN pg_class c ON c.oid = d.objoid
JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = d.objsubid
WHERE c.relkind = 'r'
AND d.objsubid > 0;
Choosing a method
| Goal | Recommended method |
|---|---|
| Export an entire database's DDL and comments | pg_dump -s ✅ |
| Export a specific schema | pg_dump -n schema_name -s ✅ |
| Get a single table definition (PostgreSQL 16+) | pg_get_tabledef() |
| Export graphically | pgAdmin / DBeaver |
| Generate comments in a script | Query pg_description |
Where to run pg_dump
pg_dump is a PostgreSQL client tool. You can run it in the following places.
Operating system command line
| System | Where to run it |
|---|---|
| Linux / macOS | Terminal |
| Windows | PowerShell or cmd |
pg_dump installation paths
| System | Default installation path |
|---|---|
| Linux (apt/yum) | /usr/bin/pg_dump or /usr/pgsql-<version>/bin/pg_dump |
| macOS (Homebrew) | /usr/local/bin/pg_dump or /opt/homebrew/bin/pg_dump |
| Windows | C:\Program Files\PostgreSQL\<version>\bin\pg_dump.exe |
Check the path:
# Linux/macOS
which pg_dump
# Windows
where pg_dump
Check the version:
pg_dump --version
Connection parameters
pg_dump connects to PostgreSQL over the network. Common options include:
| Option | Meaning |
|---|---|
-h | Database server address |
-p | Port (default 5432) |
-U | Username |
-d | Database name |
Full example:
pg_dump -h localhost -p 5432 -U postgres -d mydb -s -f schema.sql
Databases running in Docker containers
If the database runs in a Docker container, you have two choices.
Option 1: Run the command inside the container
docker exec -it postgres_container bash
pg_dump -U postgres -d mydb -s > /tmp/schema.sql
Option 2: Connect over the network from the host
pg_dump -h 127.0.0.1 -p 5432 -U postgres -d mydb -s -f schema.sql
Execution environments at a glance
| Scenario | Where to run it | Example |
|---|---|---|
| Local database | Local command line | pg_dump -U postgres -d mydb -s -f schema.sql |
| Remote database | Local command line with -h | pg_dump -h remote_ip -U user -d db -s -f schema.sql |
| Database in Docker | Inside the container | docker exec -it pg bash -c "pg_dump -U postgres -d db -s > /tmp/schema.sql" |
| Windows | PowerShell / CMD | pg_dump -U postgres -d mydb -s -f "C:\path\schema.sql" |
Exporting DDL from Amazon RDS
RDS doesn't let you log into the database host. But since pg_dump is a client tool, you can export directly as long as your machine can reach port 5432 on the RDS instance.
Option A: Connect directly from your machine
Prerequisites: RDS has “Publicly accessible = Yes” and the security group allows TCP 5432 from your current public IP.
pg_dump \
-h your-rds-endpoint.rds.amazonaws.com \
-p 5432 \
-U dbuser \
-d dbname \
-s \
--no-owner --no-privileges \
--sslmode=require \
--sslrootcert=/path/to/rds-combined-ca-bundle.pem \
-f schema.sql
💡 Tip: Use
--sslmode=requiretogether with an AWS RDS CA certificate for a more reliable connection. Download the certificate from AWS and save it asrds-combined-ca-bundle.pem.
Option B: Private RDS instance via a bastion or port forwarding
B1. SSH bastion (an EC2 instance in the same VPC)
# 本地开隧道:把本地 5432 → RDS:5432,通过 bastion 主机
ssh -i your-key.pem -L 5432:your-rds-endpoint.rds.amazonaws.com:5432 ec2-user@bastion-ec2-public-ip
Leave that terminal open and run this in a second one:
pg_dump -h 127.0.0.1 -p 5432 -U dbuser -d dbname -s \
--sslmode=require --sslrootcert=/path/to/rds-combined-ca-bundle.pem \
-f schema.sql
B2. Port forwarding with AWS SSM Session Manager (works without a public endpoint)
Prerequisites: an EC2 instance with SSM Agent installed in the same VPC, connectivity from that instance to RDS on port 5432, and a locally configured awscli.
aws ssm start-session \
--target i-xxxxxxxxxxxxxxxxx \
--document-name AWS-StartPortForwardingSession \
--parameters "localPortNumber=5432,portNumber=5432,host=your-rds-endpoint.rds.amazonaws.com"
Once the forward is active, run pg_dump with -h 127.0.0.1 -p 5432.
Option C: Run pg_dump inside the VPC
Launch a small EC2 instance in the same VPC/subnet, or use an existing operations machine. Install the PostgreSQL client, then run:
pg_dump -h your-rds-endpoint.rds.amazonaws.com -p 5432 -U dbuser -d dbname -s \
--sslmode=require --sslrootcert=/path/to/rds-combined-ca-bundle.pem \
-f /tmp/schema.sql
Copy the file back to your machine with scp.
Optional: IAM database authentication without storing a password
RDS PostgreSQL supports an IAM token as a temporary password, valid for about 15 minutes. Enable IAM authentication for the database user.
TOKEN=$(aws rds generate-db-auth-token \
--hostname your-rds-endpoint.rds.amazonaws.com \
--port 5432 \
--region your-region \
--username dbuser)
PGPASSWORD="$TOKEN" pg_dump \
-h your-rds-endpoint.rds.amazonaws.com \
-p 5432 \
-U dbuser \
-d dbname \
-s \
--sslmode=require --sslrootcert=/path/to/rds-combined-ca-bundle.pem \
-f schema.sql
RDS troubleshooting checklist
| Check | What to look for |
|---|---|
| Security group | The RDS security group must allow the source (your public IP or the bastion's ENI) to access port 5432. |
| NACL | The subnet's network ACL must allow port 5432. |
| Parameter group | If rds.force_ssl=1, include --sslmode=require and the CA certificate. |
| Account privileges | Exporting DDL requires read access to the system catalogs, which ordinary users generally have. |
| Version compatibility | The original note recommends a pg_dump version ≤ the RDS engine's major version, observing that large version differences can cause compatibility issues. |
Using a connection string
pg_dump accepts a PostgreSQL connection string in place of separate -h -p -U -d arguments.
URI format (most common)
pg_dump 'postgresql://用户名:密码@主机:端口/数据库名?参数=值' -s -f schema.sql
Example:
pg_dump 'postgresql://dbuser:MyP@[email protected]:5432/mydb?sslmode=require' -s -f schema.sql
keyword=value format
You can also use space-separated key/value pairs:
pg_dump 'host=your-rds-endpoint.rds.amazonaws.com port=5432 dbname=mydb user=dbuser password=MyPassword sslmode=require' -s -f schema.sql
Include the RDS SSL certificate
If your RDS instance enforces SSL, you can add:
pg_dump 'postgresql://dbuser:[email protected]:5432/mydb?sslmode=verify-full&sslrootcert=/path/to/rds-combined-ca-bundle.pem' -s -f schema.sql
Special characters in passwords
If a password in the URL contains special characters such as @, #, ?, &, or $, URL-encode them:
| Character | URL encoding |
|---|---|
@ | %40 |
# | %23 |
? | %3F |
& | %26 |
$ | %24 |
% | %25 |
For example: MyP@ss$word! → MyP%40ss%24word!
⚠️ Warning: Wrap the connection string in single quotes. A shell interprets characters such as
$within double quotes and may change the password.
# 正确:使用单引号
pg_dump 'postgresql://user:Pa$$word@host:5432/db' -s -f schema.sql
# 错误:双引号会导致 $$ 被 shell 解析
pg_dump "postgresql://user:Pa$$word@host:5432/db" -s -f schema.sql
Avoid exposing the password
Put the password in an environment variable instead of directly in the URI:
export PGPASSWORD='MyP@ssword!'
pg_dump 'postgresql://[email protected]:5432/mydb?sslmode=require' -s -f schema.sql
Or set it for one command:
PGPASSWORD='MyP@ssword!' pg_dump 'postgresql://[email protected]:5432/mydb?sslmode=require' -s -f schema.sql
Connection strings at a glance
| Method | Example |
|---|---|
| URI | 'postgresql://user:pass@host:5432/db?sslmode=require' |
| keyword=value | 'host=host port=5432 user=user password=pass dbname=db sslmode=require' |
| Add an SSL certificate | ?sslmode=verify-full&sslrootcert=/path/to/rds-combined-ca-bundle.pem |
| Store the password in the environment | PGPASSWORD=... pg_dump 'postgresql://user@host/db' |
References
- PostgreSQL Documentation - pg_dump. (n.d.). Retrieved December 24, 2025, from https://www.postgresql.org/docs/current/app-pgdump.html
- PostgreSQL Documentation - System Catalogs. (n.d.). Retrieved December 24, 2025, from https://www.postgresql.org/docs/current/catalogs.html
- AWS Documentation - Using SSL with a PostgreSQL DB instance. (n.d.). Retrieved December 24, 2025, from https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/PostgreSQL.Concepts.General.SSL.html
- AWS Documentation - IAM database authentication for MariaDB, MySQL, and PostgreSQL. (n.d.). Retrieved December 24, 2025, from https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.html