PostgreSQL
PostgreSQL reference: install and start, dump and restore, force-drop a database, size queries, MySQL migration with pgloader and XA errors.
6 min readUpdated
PostgreSQL is an open-source relational database. This note collects the commands used most often in day-to-day work: installing and starting the server, creating users and databases, dumping and restoring, dropping a database that still has connections, measuring database and table sizes, migrating from MySQL with pgloader, and fixing the XA error that application servers report when prepared transactions are disabled.
Install and start the server
macOS with Homebrew
Homebrew ships PostgreSQL as versioned formulas such as postgresql@18. Installing it also creates a database cluster in $(brew --prefix)/var/postgresql@18.
brew install postgresql@18Start the server now and at every login with launchd:
brew services start postgresql@18If you do not want a background service, start the server in the foreground session instead. The formula is keg-only, so its binaries are not on your PATH by default:
"$(brew --prefix postgresql@18)/bin/pg_ctl" -D "$(brew --prefix)/var/postgresql@18" startDebian and Ubuntu
The postgresql package installs the distribution’s current version and starts it as a systemd service:
sudo apt install postgresqlsudo systemctl start postgresqlCreate users and databases
From the shell, createuser and createdb wrap the SQL commands. --interactive asks for the role’s attributes and -P asks for a password:
createuser --interactive -Pcreatedb --owner=postgres --encoding=UTF8 <database>The same in psql:
CREATE USER <user>;CREATE DATABASE <database>;By default, psql connects to a database with the same name as your operating system user. To connect elsewhere, name the database and user explicitly:
psql -d <database>psql -U <user> <database>Export and import a database
Export a database to a SQL file with pg_dump:
pg_dump -U username dbname > load.sqlImport it into an existing database with psql:
psql -U username dbname < load.sqlFix “permission denied for schema topology”
On servers whose template databases include PostGIS, pg_dump may fail like this:
pg_dump: SQL command failedpg_dump: Error message from server: ERROR: permission denied for schema topologypg_dump: The command was: LOCK TABLE topology.topology IN ACCESS SHARE MODEThe PostGIS topology schema and spatial_ref_sys table have restricted permissions. Exclude them from the dump: -N excludes a schema and -T excludes a table.
pg_dump -U username dbname -N topology -T spatial_ref_sys > dbexport.pgsqlDrop a database that has open connections
PostgreSQL refuses to drop a database while clients are connected to it.
On PostgreSQL 13 and later, FORCE terminates the connections and drops the database in one step. Run it while connected to a different database, as the owner or a superuser:
psql -U postgres -c "DROP DATABASE mydb WITH (FORCE);"On older versions, do it in steps. First connect as a superuser to another database, for example postgres:
psql -h localhost -U postgres postgresStep 1. Stop new connections to the database. Method 1 updates the system catalog and needs superuser privileges. Method 2 needs only database owner privileges, but superusers can still connect.
# Method 1: update the system catalogpsql -U postgres -c "UPDATE pg_database SET datallowconn = 'false' WHERE datname = 'mydb';"
# Method 2: ALTER DATABASE (superusers can still connect)psql -U postgres -c "ALTER DATABASE mydb CONNECTION LIMIT 0;"Step 2. Disconnect all clients of the database with pg_terminate_backend. This needs superuser privileges.
psql -U postgres -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'mydb';"Step 3. Drop the database. This needs database owner privileges.
psql -U postgres -c "DROP DATABASE mydb;"Step 4. If the database had its own user, drop it as well:
psql -U postgres -c "DROP USER mydbuser;"Measure database and table sizes
Size of one table (including its indexes and TOAST data) and of the whole database:
SELECT pg_size_pretty(pg_total_relation_size('"<schema>"."<table>"')), pg_size_pretty(pg_database_size('dbname'));The 20 largest databases with their owners. Databases you cannot connect to show “No Access”:
SELECT d.datname AS name, pg_catalog.pg_get_userbyid(d.datdba) AS owner, CASE WHEN pg_catalog.has_database_privilege(d.datname, 'CONNECT') THEN pg_catalog.pg_size_pretty(pg_catalog.pg_database_size(d.datname)) ELSE 'No Access' END AS sizeFROM pg_catalog.pg_database dORDER BY CASE WHEN pg_catalog.has_database_privilege(d.datname, 'CONNECT') THEN pg_catalog.pg_database_size(d.datname) ELSE NULL END DESCLIMIT 20;All tables in the current database, largest first:
SELECT table_schema || '.' || table_name AS table_full_name, pg_size_pretty(pg_total_relation_size('"' || table_schema || '"."' || table_name || '"')) AS sizeFROM information_schema.tablesORDER BY pg_total_relation_size('"' || table_schema || '"."' || table_name || '"') DESC;All tables with the table data, the indexes and the total listed separately:
SELECT table_name, pg_size_pretty(table_size) AS table_size, pg_size_pretty(indexes_size) AS indexes_size, pg_size_pretty(total_size) AS total_sizeFROM ( SELECT table_name, pg_table_size(table_name) AS table_size, pg_indexes_size(table_name) AS indexes_size, pg_total_relation_size(table_name) AS total_size FROM ( SELECT ('"' || table_schema || '"."' || table_name || '"') AS table_name FROM information_schema.tables ) AS all_tables ORDER BY total_size DESC) AS pretty_sizes;Both queries include the system catalogs. To list only your own tables, add WHERE table_schema NOT IN ('pg_catalog', 'information_schema') to the query on information_schema.tables.
The data size and row count of a table, or of selected rows. pg_column_size(t.*) measures each row as stored:
SELECT pg_size_pretty(sum(pg_column_size(t.*))) AS filesize, count(*) AS filerow FROM tablename AS t;
SELECT pg_size_pretty(sum(pg_column_size(t.*))) AS filesize, count(*) AS filerow FROM tablename AS t WHERE t.id = 12345;The size of a single column, for all rows or one row:
SELECT pg_size_pretty(sum(pg_column_size(t.fieldname))) AS field_size FROM tablename AS t;
SELECT pg_size_pretty(sum(pg_column_size(t.fieldname))) AS field_size FROM tablename AS t WHERE id = 1;Migrate from MySQL with pgloader
pgloader loads data from MySQL, SQLite, CSV files and other sources into PostgreSQL. Install it and migrate a whole database with a single command:
brew install pgloaderpgloader mysql://username_mysql:P@@ssword1@localhost:3306/dbname_mysql pgsql://username_pssql@localhost:5432/dbname_pssqlIn pgloader connection strings an @ inside the password is written twice, so P@@ssword1 stands for the password P@ssword1.
For more control, put the options in a command file and pass it to pgloader:
pgloader pgload_test.loadThis command file copies only the data into tables that already exist in PostgreSQL. It truncates them first, disables triggers during the load, and renames the MySQL schema to public:
LOAD DATABASE FROM mysql://username_mysql:P@@ssword1@localhost:3306/dbname_mysql INTO pgsql://username_pssql@localhost:5432/dbname_pssql
-- To let pgloader drop and create the tables instead: WITH include drop, create tablesWITH include no drop, truncate, disable triggers, create no tables, create no indexes, preserve index names, no foreign keys, data only
ALTER SCHEMA 'dbname_mysql' RENAME TO 'public';Install a GUI client
Common graphical clients for PostgreSQL:
- pgAdmin: the official administration tool.
- Postico: a native macOS client.
- DBeaver: a cross-platform client for many databases.
- Navicat: a commercial multi-database client.
- SQL Workbench/J: a Java-based SQL client.
All of them are available as Homebrew casks:
brew install --cask pgadmin4brew install --cask posticobrew install --cask dbeaver-communitybrew install --cask navicat-premiumbrew install --cask sqlworkbenchjFix “Error rolling back prepared transaction”
When a distributed (XA) transaction commits in GlassFish or another application server against PostgreSQL, you may see errors like these:
java.lang.RuntimeException: org.postgresql.xa.PGXAException: Error preparing transaction] on Resource [prepare] operation.
javax.enterprise.system.core.transaction.com.sun.jts.jtsxa|_ThreadID=22;_ThreadName=Thread-4;|JTS5068: Unexpected error occurred in rollback org.postgresql.xa.PGXAException: Error rolling back prepared transactionXA uses PostgreSQL’s prepared transactions, which are disabled by default (max_prepared_transactions = 0). To enable them:
- Find
postgresql.conf. RunSHOW config_file;inpsql; it is usually in the server’s data directory. - Find the
max_prepared_transactionssetting. If it is commented out (#max_prepared_transactions), remove the#. - Set a value above zero, for example 20. The PostgreSQL documentation recommends at least the value of
max_connectionswhen you use prepared transactions. - Save the file and restart PostgreSQL. This setting does not take effect on reload.