Skip to content

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.

Terminal window
brew install postgresql@18

Start the server now and at every login with launchd:

Terminal window
brew services start postgresql@18

If 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:

Terminal window
"$(brew --prefix postgresql@18)/bin/pg_ctl" -D "$(brew --prefix)/var/postgresql@18" start

Debian and Ubuntu

The postgresql package installs the distribution’s current version and starts it as a systemd service:

Terminal window
sudo apt install postgresql
sudo systemctl start postgresql

Create 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:

Terminal window
createuser --interactive -P
createdb --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:

Terminal window
psql -d <database>
psql -U <user> <database>

Export and import a database

Export a database to a SQL file with pg_dump:

Terminal window
pg_dump -U username dbname > load.sql

Import it into an existing database with psql:

Terminal window
psql -U username dbname < load.sql

Fix “permission denied for schema topology”

On servers whose template databases include PostGIS, pg_dump may fail like this:

pg_dump: SQL command failed
pg_dump: Error message from server: ERROR: permission denied for schema topology
pg_dump: The command was: LOCK TABLE topology.topology IN ACCESS SHARE MODE

The 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.

Terminal window
pg_dump -U username dbname -N topology -T spatial_ref_sys > dbexport.pgsql

Drop 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:

Terminal window
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:

Terminal window
psql -h localhost -U postgres postgres

Step 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.

Terminal window
# Method 1: update the system catalog
psql -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.

Terminal window
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.

Terminal window
psql -U postgres -c "DROP DATABASE mydb;"

Step 4. If the database had its own user, drop it as well:

Terminal window
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 size
FROM pg_catalog.pg_database d
ORDER BY
CASE WHEN pg_catalog.has_database_privilege(d.datname, 'CONNECT')
THEN pg_catalog.pg_database_size(d.datname)
ELSE NULL
END DESC
LIMIT 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 size
FROM information_schema.tables
ORDER 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_size
FROM (
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:

Terminal window
brew install pgloader
pgloader mysql://username_mysql:P@@ssword1@localhost:3306/dbname_mysql pgsql://username_pssql@localhost:5432/dbname_pssql

In 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:

Terminal window
pgloader pgload_test.load

This 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:

pgload_test.load
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 tables
WITH 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:

Terminal window
brew install --cask pgadmin4
brew install --cask postico
brew install --cask dbeaver-community
brew install --cask navicat-premium
brew install --cask sqlworkbenchj

Fix “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 transaction

XA uses PostgreSQL’s prepared transactions, which are disabled by default (max_prepared_transactions = 0). To enable them:

  1. Find postgresql.conf. Run SHOW config_file; in psql; it is usually in the server’s data directory.
  2. Find the max_prepared_transactions setting. If it is commented out (#max_prepared_transactions), remove the #.
  3. Set a value above zero, for example 20. The PostgreSQL documentation recommends at least the value of max_connections when you use prepared transactions.
  4. Save the file and restart PostgreSQL. This setting does not take effect on reload.

References

Related notes

6 min read

SQL joins

INNER, LEFT, RIGHT, FULL OUTER, CROSS and self joins in SQL, with two small example tables, the queries and their results.

  • Databases
3 min read

Database migration: MySQL to PostgreSQL

Migrate a MySQL database to PostgreSQL with pgloader in Docker, and fix the two authentication errors you are likely to hit.

  • Databases
5 min read

JDBC

JDBC driver, DataSource and XADataSource class names per database, with GlassFish and Payara connection pool examples.

  • Java & Jakarta EE
  • Databases

Type to search the whole site.