Skip to content
migration.tools

database · mysql · postgresql

MySQL to PostgreSQL: the differences that actually break migrations

Migrating from MySQL to PostgreSQL: type mapping, AUTO_INCREMENT and sequences, zero dates, case sensitivity, query rewrites and how to verify the result.

By

Updated · first published · 6 min read

Two database cylinders joined by a route line, with type mappings such as TINYINT(1) to boolean and AUTO_INCREMENT to IDENTITY along the way.

Key points

  • Convert and load the schema first, into an empty PostgreSQL database, before moving any data.
  • After loading rows with explicit IDs, reset every sequence with setval(), or the next INSERT fails with a duplicate key error.
  • MySQL's default collations compare text case-insensitively; PostgreSQL's don't. Check unique constraints and WHERE clauses on emails and usernames.
  • Zero dates (0000-00-00) are invalid in PostgreSQL and must become NULL or a real date before loading.
  • Stored procedures, triggers and ON UPDATE CURRENT_TIMESTAMP need to be rewritten by hand.

Moving from MySQL to PostgreSQL looks like a syntax exercise: swap backticks for double quotes, rename a few types, done. The syntax is the easy part. What breaks migrations is the handful of places where the two databases behave differently while accepting similar-looking SQL — and those failures tend to show up a week after cutover, in a support ticket, not during the import.

This guide walks through those places in the order you will meet them: schema, data, queries, and verification.

Start with the schema, on its own

Export the schema without data (mysqldump --no-data), convert it, and load it into an empty PostgreSQL database. Fix everything that fails before you touch a single row. Schema errors are cheap when the tables are empty and expensive when you are halfway through a 40 GB load.

The MySQL to PostgreSQL converter handles the mechanical rewrite and, more importantly, lists the decisions it made in its review notes. Read those notes; each one is a question about your data that only you can answer.

Type mapping

Most types have a direct equivalent. A few need a decision:

MySQLPostgreSQLWatch out for
INT AUTO_INCREMENTinteger GENERATED BY DEFAULT AS IDENTITYSequences must be reset after loading data
TINYINT(1)booleanOnly if the column really holds 0/1 — some schemas store small counters here
INT UNSIGNEDbigintPostgreSQL has no unsigned types; bigint covers the full range
DATETIMEtimestampNo time zone in either; keep it that way unless you are ready to convert
TIMESTAMPtimestamptzMySQL stores these as UTC and converts on read
DOUBLEdouble precisionSame IEEE 754 semantics
ENUM('a','b')text + CHECK, or a native enumA CHECK constraint is easier to change later
JSONjsonbjsonb normalises key order and drops duplicate keys
LONGBLOBbyteaDumps must encode binary data, usually as hex

ENUM deserves a moment. PostgreSQL has real enum types, but adding a value means ALTER TYPE, and removing one is effectively impossible. A text column with a CHECK (status IN (...)) constraint behaves the same for your application and is far easier to evolve.

AUTO_INCREMENT and the sequence trap

PostgreSQL implements auto-increment with sequences. When you load existing rows with their original IDs, the sequence doesn't move: it still thinks the next value is 1. The import succeeds, the application starts, and the first new row fails with duplicate key value violates unique constraint.

After the data is loaded, reset each sequence to the current maximum:

SELECT setval(pg_get_serial_sequence('users', 'id'), COALESCE(MAX(id), 1))
FROM users;

Do this for every table with a generated key, and make it part of the migration script rather than a manual step. It's the most common post-migration bug. The MySQL to PostgreSQL converter appends these setval() calls to its output for you; if you load data any other way, add them yourself.

Things with no equivalent

  • ON UPDATE CURRENT_TIMESTAMP has no column-level equivalent. Write a BEFORE UPDATE trigger, or set the column from the application.
  • Prefix indexes such as KEY (title(191)) don't exist. Index the whole column, or create an expression index if you need a prefix.
  • FULLTEXT indexes become a tsvector column (or expression) with a GIN index — and the query syntax changes from MATCH ... AGAINST to @@ to_tsquery(...).
  • Stored procedures, functions and triggers are programs in each database's own language. Translate them by hand and test them. A converter that silently rewrites them is guessing.

Move the data

For small and medium databases, converting the INSERT statements from a dump works well. For large ones, export CSV from MySQL and load it with PostgreSQL's COPY, which is much faster than individual inserts. The open-source pgloader can also migrate directly from a live MySQL server and is worth considering for very large databases.

Whichever route you take, three kinds of data will cause trouble.

Zero dates

MySQL, depending on its sql_mode, accepts 0000-00-00 and 0000-00-00 00:00:00 as dates. PostgreSQL rejects them, and the load stops. Decide what they mean — almost always "unknown" — and convert them to NULL. If the column is NOT NULL, that decision has to include the schema too.

Backslashes and string escapes

MySQL treats backslash as an escape character inside string literals by default, so dumps contain \', \n and \\. PostgreSQL, with standard_conforming_strings on (the default), treats a backslash as a literal character. A dump loaded without converting those escapes either fails or, worse, loads text with stray backslashes in it. Converting the dump — rather than editing it with find-and-replace — handles this correctly, because it has to tokenise the strings to do it.

Character sets

MySQL's historical utf8 charset is really utf8mb3: it can't store characters outside the Basic Multilingual Plane, such as most emoji. If your old database used it, some text may already have been truncated or replaced when it was written. PostgreSQL databases are normally UTF-8 throughout, so the migration won't make this worse — but it's worth knowing before someone blames the new database for missing characters.

Rewrite the queries that behave differently

Your schema can be perfect and the application still break, because SQL dialects diverge in ways that don't cause syntax errors.

Case sensitivity. MySQL's default collations compare strings case-insensitively, so WHERE email = 'Ana@Example.com' matches ana@example.com. In PostgreSQL it doesn't. The same goes for unique constraints: two accounts that MySQL considered duplicates can now both exist. For columns like email and username, use the citext extension, a unique index on lower(email), or a case-insensitive ICU collation.

GROUP BY. Older MySQL configurations allowed selecting columns that are neither grouped nor aggregated, and returned an arbitrary value for them. PostgreSQL rejects those queries. They show up as errors immediately, which is the good kind of failure.

Upserts. INSERT ... ON DUPLICATE KEY UPDATE becomes INSERT ... ON CONFLICT (key) DO UPDATE SET col = EXCLUDED.col. Note that PostgreSQL needs you to name the conflicting constraint or columns.

Small syntax differences that the SQL dialect converter can handle for ad-hoc queries:

  • LIMIT 10, 20 becomes LIMIT 20 OFFSET 10
  • IFNULL(a, b) becomes COALESCE(a, b)
  • DATE_FORMAT(d, '%Y-%m') becomes to_char(d, 'YYYY-MM')
  • `quoted` identifiers become "quoted" ones, and unquoted identifiers are folded to lower case

If your application uses an ORM, much of this is already handled — but raw queries, reports and migration scripts usually aren't. Search the codebase for them before cutover. If you are moving to an ORM at the same time, the SQL to Prisma schema tool can draft models from the converted DDL.

Prove it worked

A migration you haven't verified is a migration you are assuming worked. At minimum:

  1. Row counts per table, source and target, side by side.
  2. Aggregates on the columns that matter: sums of money columns, min and max of dates, counts of distinct keys.
  3. A full diff of the critical tables. Export the same table from both databases to CSV, ordered by primary key, and compare them with the CSV compare tool. Differences in formatting (1.0 vs 1, t vs true) are expected; differences in values are not.

The guide on proving a data migration worked goes through reconciliation in more depth.

A checklist for cutover day

  • Schema converted, loaded and reviewed; every review note resolved
  • Data loaded; zero dates and escapes handled
  • Sequences reset on every table with a generated key
  • Case-sensitive comparisons checked on emails, usernames and slugs
  • Triggers, procedures and ON UPDATE columns rewritten and tested
  • Application test suite run against PostgreSQL
  • Row counts, aggregates and critical-table diffs all clean
  • The MySQL database kept read-only and available, so rolling back is a decision rather than a rebuild

None of these steps is difficult on its own. Migrations go wrong when one is skipped because the import "worked".

About the author

Abdessamad Bettal, full-stack engineer and the developer of migration.tools — free, private, browser-based tools for moving databases, data, websites and content between systems.

LinkedIn GitHub