Migrating and upgrading the database

Two kinds of move, one rule: no migration without a restored backup, a dry run and a way back. Here is the recipe from MySQL to PostgreSQL with pgloader, the differences that make the application fail afterwards, and how to move PostgreSQL between major versions.

Last checked:

On this pageWhat this page covers
  1. Should you move at all?
  2. MySQL to PostgreSQL with pgloader
  3. What breaks the application afterwards
  4. Typical differences from MySQL to PostgreSQL
  5. Schema changes in the app: Alembic and friends
  6. Upgrading PostgreSQL between major versions

Should you move at all?

Moving from MySQL to PostgreSQL makes sense when you need something MySQL lacks: extensions like PostGIS or pgvector, stronger types, or a target system that runs only on PostgreSQL. It does not make sense if the only problem is slow queries – that is usually solved with indexes, not a new engine. We chose to leave 130 million rows in MySQL.

Often the job is not a migration but a copy. We have built integrations between e-conomic, Google Sheets and SQL for clients, where data is pulled from the accounting system into an SQL database for reports and lookups. The source stays in e-conomic, and the SQL database is a read copy that can be rebuilt. That is a very different risk from moving a system’s own database.

If your data lives in Microsoft SQL Server, licence prices, type mapping and a tested load file are on the SQL Server to PostgreSQL page.

MySQL to PostgreSQL with pgloader

pgloader reads schema and data straight from MySQL, creates tables, indexes and foreign keys in PostgreSQL and resets sequences. The conversion rules go into a command file.

-- shop.load  –  run with:  pgloader shop.load
-- The password comes from the environment: export MIGRATE_PASSWORD=...
LOAD DATABASE
     FROM mysql://migrate:{{MIGRATE_PASSWORD}}@localhost:3306/shop
     INTO postgresql://migrate:{{MIGRATE_PASSWORD}}@localhost:5432/shop

 WITH include drop, create tables, create indexes, foreign keys,
      reset sequences, workers = 4, concurrency = 1

 CAST type datetime to timestamptz drop default drop not null using zero-dates-to-null,
      type date drop not null drop default using zero-dates-to-null,
      type tinyint when (= precision 1) to boolean drop typemod using tinyint-to-boolean

 ALTER SCHEMA 'shop' RENAME TO 'public';

MySQL 8.4 needs a detour. We tested this recipe on 19.11.2026 with pgloader 3.6.10 from Debian. MariaDB 10.11 → PostgreSQL 18 went through cleanly, with 0000-00-00 becoming NULL and tinyint(1) becoming boolean. Against MySQL 8.4 it failed: first at login (caching_sha2_password), and after enabling mysql_native_password, on the character set. What worked was loading the data into a temporary MariaDB first:

# MySQL 8.4 → temporary MariaDB → PostgreSQL
mysqldump --single-transaction --routines --triggers --hex-blob --set-gtid-purged=OFF shop \
  | sed 's/utf8mb4_0900_ai_ci/utf8mb4_unicode_ci/g' \
  | mariadb -h staging-db shopstage
pgloader shopstage.load    # same command file, FROM points at the MariaDB copy

Run it against a copy first, never against production. Then count rows in the key tables on both sides. On the PostgreSQL side one query counts every table exactly:

-- Exact row count per table in public (PostgreSQL)
SELECT table_name,
       (xpath('/row/c/text()',
              query_to_xml(format('SELECT count(*) AS c FROM %I.%I', table_schema, table_name),
                           false, true, '')))[1]::text::bigint AS rows
FROM information_schema.tables
WHERE table_schema = 'public' AND table_type = 'BASE TABLE'
ORDER BY table_name;

Check the character set before you start. MySQL databases created by our control panel were in utf8mb3, and we had to convert 58 tables and 245 columns in one product. Data already stored wrongly moves with it.

What breaks the application afterwards

pgloader moves the data. The application’s SQL is yours to fix, and this is where most migrations overrun.

Typical differences from MySQL to PostgreSQL

MySQL / MariaDBPostgreSQLWhat to do
Backticks around names"name"Search and replace; ideally names without quotes
LIMIT 20, 10LIMIT 10 OFFSET 20Fix the queries
INSERT … ON DUPLICATE KEY UPDATEINSERT … ON CONFLICT (…) DO UPDATENeeds a unique index on the conflict column
IFNULL(a, b)COALESCE(a, b)COALESCE works in both
Case-insensitive comparisonCase-sensitivecitext, ILIKE or an index on lower(email)
Loose GROUP BYAll non-aggregated columns requiredFix the queries – the error appears at run time
ON UPDATE CURRENT_TIMESTAMPdoes not existA trigger that sets the column
0000-00-00 as a dateinvalidBecomes NULL – check the code copes
DATETIME rounds fractional secondstimestamptz stores microsecondsTests that compare times may change
What we check in the code before a migration.

The last row is one we tripped over ourselves: MySQL DATETIME rounds fractional seconds, so times can differ from what the application wrote. Run the whole test suite against PostgreSQL, not SQLite. We have seen 320 green tests on SQLite while four tables were dead in production.

Schema changes in the app: Alembic and friends

If you use Alembic, Django or another migration tool, know its traps. Alembic’s --autogenerate silently drops tables that belong to another service in the same database. We stop that with a filter:

# alembic/env.py – autogenerate may only touch tables that exist in our model
def include_object(obj, name, type_, reflected, compare_to):
    # Table in the database but not in the model = someone else's table. Leave it.
    return not (type_ == "table" and reflected and compare_to is None)

context.configure(
    connection=connection,
    target_metadata=target_metadata,
    include_object=include_object,
)

Two parallel development sessions once wrote the same hand-made revision id in bkg.dk. Let the tool generate ids. And on bkg.dk the deploy refuses data migrations, so only additive changes go out – new tables and columns, no rewriting of existing data. The 02.11.2026 release shipped 6 additive migrations with 2,782 tests green and a dump before deploy.

Upgrading PostgreSQL between major versions

Minor versions (18.0 → 18.6) are new binaries and a restart. We did that on 11 servers on 22.10.2026. A month later 18.7 and 16.16 were already out, so plan minor updates every quarter. Major versions (16 → 18) need either dump and restore or pg_upgrade.

# PostgreSQL 16 → 18 with pg_upgrade (Debian/Ubuntu paths, PGDG packages)
sudo apt install postgresql-18
sudo systemctl stop postgresql
OLD=/usr/lib/postgresql/16/bin NEW=/usr/lib/postgresql/18/bin
sudo -u postgres "$NEW/pg_upgrade" \
  --old-bindir="$OLD" --new-bindir="$NEW" \
  --old-datadir=/var/lib/postgresql/16/main --new-datadir=/var/lib/postgresql/18/main \
  --old-options='-c config_file=/etc/postgresql/16/main/postgresql.conf' \
  --new-options='-c config_file=/etc/postgresql/18/main/postgresql.conf' \
  --link --check          # check only – run again without --check when it is green
# After starting 18:
sudo -u postgres "$NEW/vacuumdb" --all --analyze-in-stages --missing-stats-only
sudo -u postgres "$NEW/vacuumdb" --all --analyze-only

--link is fast because files are not copied, but the old cluster cannot be used again once the new one has started. That is why a restored backup must exist first. PostgreSQL 18 also has --swap and carries planner statistics across unless you choose --no-statistics. Extensions such as PostGIS must be installed in the same version on the new cluster.

MySQL and MariaDB. Use the distribution’s or vendor’s packages, not a panel button that “updates”. Our control panel’s MariaDB button reinstalls and moves the data directory aside, and its PostgreSQL update copies only bin/. After a MariaDB major version, run mariadb-upgrade.

Checklist for migration day

Checklist: migration and major version

WhenItemDone when
Week beforeRestore test of the latest backupThe copy is restored and counted
Week beforeDry run on a copy, timedYou know how long the downtime is
Week beforeCharacter set, collation and extensions checkedNo utf8mb3, same extensions in the new version
Week beforeTest suite against the new engineGreen against PostgreSQL, not SQLite
The dayWrites stopped, last dump takenDump read with pg_restore --list
The dayMigration run, rows counted on both sidesCounts match in the key tables
The dayApplication points at the new databaseLogin, order and invoice tested by hand
AfterStatistics and VACUUM runvacuumdb --analyze-only finished
AfterBackup job points at the new databaseFirst nightly dump is offsite and tested
AfterOld database kept read-onlyAt least 14 days before deleting it
What we go through ourselves. One item not green means postponing.

Sources

Last reviewed: 2026-12-03

Questions about migration

How long does a MySQL to PostgreSQL migration take?

Moving the data takes minutes to hours depending on size. What takes time is fixing the application’s SQL and testing. Count on several days for a system with its own code.

Is there a free MySQL to PostgreSQL tool?

Yes, pgloader is open source and moves schema, data, indexes and sequences. With MySQL 8.4 we needed a MariaDB staging copy in our test.

When should we upgrade PostgreSQL 14?

Now. PostgreSQL 14 had its final release in November 2026 and gets no more security fixes.

Can we go back after pg_upgrade with –link?

Not once the new cluster has started. That is why a restored backup must be ready before you begin.

Fixed price, no commitment

Get a fixed price for your database task

Tell us briefly what you use today and what you want to achieve. A person answers by e-mail with a proposal and a fixed price before any work starts.

  • A fixed price before we start
  • An answer by e-mail, no calls
  • Your details are used only to answer you

Fields marked with * are required.

What is it about?