Migrating a PostgreSQL database to MySQL is not a dump-and-restore job. The two databases look similar from a distance, but they differ in data types, SQL dialect, indexing, transaction behaviour, and even how identifiers are treated. A migration that works on a small test database can fail in production on a single boolean column, an unsigned foreign key, or a timezone conversion.
This guide shows how to migrate Postgres to MySQL in a controlled sequence: inventory the source, map the schema, export data, import it, rebuild constraints, validate, and cut over with a rollback plan. It is the English version of the Indonesian guide Migrasi Database: PostgreSQL ke MySQL.
Before You Start: What Actually Changes
This guide assumes MySQL 8.0 or later. Older MySQL versions lack features you will want during migration, including window functions, common table expressions, and enforced CHECK constraints.
The biggest differences that affect a migration:
- No schemas. In PostgreSQL, a schema is a namespace inside a database. In MySQL, a database is the schema. Tables in
publicusually become tables in the target database. - DDL is not transactional. A failed MySQL
ALTER TABLEdoes not roll back cleanly like PostgreSQL DDL. Always take a snapshot before schema changes. - Case sensitivity. PostgreSQL folds unquoted identifiers to lowercase. MySQL on Linux is case-sensitive for table names by default, so
Usersandusersare different tables. - No arrays, no custom types. PostgreSQL arrays and user-defined types need a relational or JSON representation in MySQL.
- Different SQL dialect.
ILIKE,RETURNING,ON CONFLICT,::casts,generate_series(), andDISTINCT ONdo not work as-is. - Time zone handling. MySQL
TIMESTAMPconverts values using the session time zone. Store UTC and set the session explicitly.
A common question is whether pgloader can do the job. Despite its popularity, pgloader loads data into PostgreSQL; it is not a PostgreSQL-to-MySQL migration tool. For this direction, use a controlled pg_dump/CSV workflow or a commercial migration tool that explicitly supports PostgreSQL as a source and MySQL as a target.
Step 1: Inventory the Database
Start by measuring what you have. You need table sizes, row counts, and a list of features that do not map cleanly.
-- Database size
SELECT pg_size_pretty(pg_database_size(current_database()));
-- Largest tables first
SELECT relname, n_live_tup
FROM pg_stat_user_tables
ORDER BY n_live_tup DESC
LIMIT 30;
-- Columns that need special handling
SELECT table_name, column_name, data_type, udt_name
FROM information_schema.columns
WHERE data_type IN ('ARRAY', 'USER-DEFINED')
OR udt_name IN ('jsonb', 'uuid', 'bytea', 'inet', 'cidr', 'interval', 'money')
ORDER BY table_name, ordinal_position;
Also inventory views, materialized views, triggers, functions, extensions, indexes, and foreign keys. Then grep the application code for PostgreSQL-specific SQL. The queries below are the usual blockers:
ILIKEand case-insensitive searches.RETURNINGclauses afterINSERT,UPDATE, orDELETE.ON CONFLICT ... DO UPDATE(upserts).::typecasts and custom operators.generate_series(),array_agg(),string_agg(), and array operators.DISTINCT ON,LATERAL, andNULLS FIRST/LAST.
Decide up front whether you will rewrite these queries, move them into the application layer, or keep them behind a compatibility layer. That work is part of the migration, not an afterthought.
Step 2: Map PostgreSQL Types to MySQL
Use explicit mappings and keep primary keys and foreign keys consistent. A BIGINT parent with a BIGINT UNSIGNED child will fail when you add the foreign key.
| PostgreSQL | MySQL 8.0+ | Notes |
|---|---|---|
smallint, integer, bigint |
SMALLINT, INT, BIGINT |
Use UNSIGNED consistently if IDs are never negative |
serial, bigserial |
INT AUTO_INCREMENT, BIGINT AUTO_INCREMENT |
Remove DEFAULT nextval(...); reset the counter after import |
numeric(p,s) |
DECIMAL(p,s) |
Keep precision and scale exactly |
real, double precision |
FLOAT, DOUBLE |
Floating-point rounding may differ |
text, varchar(n) |
TEXT, VARCHAR(n) |
Index prefix limits apply to TEXT |
boolean |
TINYINT(1) |
Convert true/false to 1/0 |
uuid |
CHAR(36) or BINARY(16) |
CHAR(36) is simpler; BINARY(16) is compact |
json, jsonb |
JSON |
GIN indexes have no direct equivalent; use generated columns or multi-valued indexes |
bytea |
LONGBLOB |
Export as base64, decode with FROM_BASE64() |
timestamp with time zone |
DATETIME stored in UTC |
Convert to UTC before export; set session time_zone='+00:00' |
timestamp without time zone |
DATETIME |
No conversion; document the assumed zone |
date, time |
DATE, TIME |
Watch fractional seconds precision |
interval |
BIGINT seconds or VARCHAR |
Choose one representation and apply it everywhere |
inet, cidr |
VARCHAR(43) |
Store as text; validate in the application |
array[] |
Child table or JSON |
Normalize if you need joins and indexes |
enum |
ENUM or lookup table |
A lookup table is easier to change later |
money |
DECIMAL(19,4) |
Strip currency symbols before import |
tsvector |
FULLTEXT index or external search |
Ranking and stemming differ |
Step 3: Prepare the MySQL Target
Create the target database with utf8mb4. Do not use utf8; in MySQL that name refers to a three-byte subset that cannot store emoji or many CJK characters.
CREATE DATABASE app
CHARACTER SET utf8mb4
COLLATE utf8mb4_0900_ai_ci;
-- If you use LOAD DATA LOCAL INFILE
SET GLOBAL local_infile = ON;
Check these settings before loading data:
- Time zone. Run
SET time_zone = '+00:00';in the loading session and configure the application to use UTC. - SQL mode. Keep strict mode enabled so truncated data fails loudly instead of being silently cut.
- Packet size. Increase
max_allowed_packetif any row or batch exceeds the default. - Storage engine. Use InnoDB for transactions and foreign keys.
- Table name case.
lower_case_table_namesis set when MySQL is initialised; changing it later is painful. Match your naming convention before creating tables.
Step 4: Convert the Schema
For small schemas, convert the DDL by hand. For larger schemas, generate a first pass with a script and review every table. A regular expression can rename types, but it cannot understand indexes, constraints, or generated columns.
import re
def convert(sql: str) -> str:
replacements = [
(r'\bbigserial\b', 'BIGINT AUTO_INCREMENT'),
(r'\bserial\b', 'INT AUTO_INCREMENT'),
(r'\buuid\b', 'CHAR(36)'),
(r'\bjsonb?\b', 'JSON'),
(r'\bbytea\b', 'LONGBLOB'),
(r'\btimestamp with time zone\b', 'DATETIME'),
(r'\btimestamp without time zone\b', 'DATETIME'),
(r'\binterval\b', 'BIGINT'),
(r'\binet\b|\bcidr\b', 'VARCHAR(43)'),
(r'\bboolean\b', 'TINYINT(1)'),
(r'\bmoney\b', 'DECIMAL(19,4)'),
]
for pattern, replacement in replacements:
sql = re.sub(pattern, replacement, sql, flags=re.I)
return sql
with open('schema.sql') as f:
print(convert(f.read()))
Then fix what the script cannot:
- Remove PostgreSQL-specific clauses such as
DEFAULT nextval(...),USING, and tablespaces. - Create primary keys and
AUTO_INCREMENTcolumns explicitly. - Convert partial indexes to generated columns or application logic.
- Convert expression indexes to generated columns plus indexes.
- Check index key length; InnoDB has a 3072-byte limit for
utf8mb4indexes. - Create foreign keys only after data is loaded, or disable foreign key checks during the load.
Step 5: Export Data from PostgreSQL
Use CSV for bulk data. It is faster and easier to transform than INSERT statements, and it avoids quoting differences between the two databases. The Indonesian guide shows pg_dump --column-inserts; that works for small tables, but CSV scales better.
Set a consistent session before exporting:
SET client_encoding = 'UTF8';
SET timezone = 'UTC';
SET datestyle = 'ISO, YMD';
Export one table at a time with an explicit column list and explicit transformations:
\copy (SELECT
id,
name,
CASE WHEN active THEN 1 ELSE 0 END AS active,
created_at AT TIME ZONE 'UTC' AS created_at
FROM users
ORDER BY id)
TO 'users.csv' WITH (FORMAT csv, HEADER true);
For special types:
- bytea:
encode(payload, 'base64') AS payload_b64. - jsonb: cast to text:
data::text. - arrays:
array_to_json(tags)::textif you keep JSON, or export a child table. - timestamps: always convert to UTC with
AT TIME ZONE 'UTC'. - booleans: convert to
1/0in the query, not after import.
If the database is large, take a snapshot or briefly pause writes so every table is exported from the same point in time. Exporting tables one by one while the application is writing will produce inconsistent foreign keys and row counts.
Step 6: Import Data into MySQL
Load into staging tables first. Disable foreign key checks for the session, import in dependency order, then re-enable and validate.
SET foreign_key_checks = 0;
SET unique_checks = 0;
LOAD DATA LOCAL INFILE '/data/users.csv'
INTO TABLE users
CHARACTER SET utf8mb4
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(id, name, active, created_at);
SET unique_checks = 1;
SET foreign_key_checks = 1;
LOAD DATA LOCAL INFILE requires local_infile=ON on both the client and the server, and the client must be started with --local-infile=1. If your security policy forbids local infile, put the CSV on the MySQL server and use LOAD DATA INFILE instead.
For base64 columns, load into a user variable and decode in the SET clause:
LOAD DATA LOCAL INFILE '/data/files.csv'
INTO TABLE files
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n' IGNORE 1 LINES
(id, payload_b64)
SET payload = FROM_BASE64(payload_b64);
Commit in batches for very large tables. A single 50 GB transaction is harder to retry than twenty 2.5 GB batches.
Step 7: Reset AUTO_INCREMENT and Rebuild Indexes
Importing explicit IDs does not automatically move the AUTO_INCREMENT counter. If you insert a new row after migration, MySQL may try to reuse ID 1 and fail with a duplicate-key error.
SELECT MAX(id) + 1 FROM users;
ALTER TABLE users AUTO_INCREMENT = 1001;
Repeat for every table with an auto-increment key, or generate the statements from information_schema. Then create secondary indexes and foreign keys, and run ANALYZE TABLE so the optimizer has current statistics.
Check for orphaned rows before adding each foreign key:
SELECT COUNT(*)
FROM orders o
LEFT JOIN users u ON u.id = o.user_id
WHERE u.id IS NULL;
Step 8: Validate the Migration
Do not trust a successful import. Validate at three levels: structural, data, and application.
- Row counts. Compare every table. A difference of one row matters.
- Key ranges. Compare
MIN(id),MAX(id), and the count of distinct IDs. - Critical values. Compare sums for money columns, min/max for dates, and counts for statuses.
- Foreign keys. Run orphan checks for every relationship, even if the constraint was added successfully.
- Encoding. Insert and read back emoji, accented characters, and CJK text.
- Time zones. Compare a known timestamp in PostgreSQL and MySQL, then check what the application displays.
- Application tests. Run read and write smoke tests, pagination, search, and reporting queries against staging.
- Performance. Run
EXPLAINon the ten slowest production queries. Missing or different indexes show up here.
For a stronger check, compute a per-row hash in both databases and compare aggregates. Do this for the largest and most business-critical tables, not just a sample.
Step 9: Cut Over and Keep a Rollback Path
A migration is not finished when the data loads. It is finished when the application runs on MySQL and you can still go back.
- Freeze writes to PostgreSQL, or put the application in read-only mode.
- Run the final delta import for rows changed since the main load.
- Switch connection strings and restart the application.
- Run smoke tests immediately: login, create, update, delete, search, report.
- Monitor errors and latency for at least one full business cycle.
- Keep PostgreSQL read-only for a rollback window. Do not delete it on day one.
Have a written rollback trigger: error rate above a threshold, missing data, failed payments, or unacceptable latency. A rollback plan that exists only in someone’s head is not a rollback plan.
Common Errors and Fixes
| Error | Cause | Fix |
|---|---|---|
| 1062 Duplicate entry | Auto-increment counter is behind existing IDs, or source data has duplicates | Reset AUTO_INCREMENT; deduplicate before import |
| 1366 Incorrect string value | Connection or table is not utf8mb4 |
Set database, table, and connection charset to utf8mb4 |
| 1215 Cannot add foreign key | Column types differ (signed vs unsigned, length, engine) | Make parent and child types identical; use InnoDB |
| 1406 Data too long | VARCHAR(n) is shorter than the source value |
Widen the column or truncate deliberately |
| 1292 Incorrect datetime value | Format, time zone, or zero dates | Export ISO timestamps in UTC; convert zero dates to NULL |
| 1265 Data truncated | Boolean t/f loaded into a numeric column |
Convert booleans to 1/0 during export |
| 1071 Specified key was too long | Index exceeds the InnoDB key limit | Use a prefix index or a smaller VARCHAR |
| 1148 Local infile not allowed | local_infile is disabled |
Enable it on client and server, or use server-side LOAD DATA INFILE |
| 2006 MySQL server has gone away | Packet or batch too large | Increase max_allowed_packet; reduce batch size |
Production Checklist
- Schema reviewed table by table; no unchecked regex output.
- Primary keys, foreign keys, and indexes recreated.
AUTO_INCREMENTreset for every table.- All timestamps stored and read as UTC.
- Row counts and critical aggregates match.
- Application queries rewritten for MySQL syntax.
- Staging load test passed with production-sized data.
- Backup, rollback plan, and rollback trigger documented.
- PostgreSQL kept available until the new system is stable.
Final Thoughts
The safest way to convert Postgres to MySQL is not to look for a magic one-click tool. It is to reduce uncertainty step by step: know your types, export consistent data, load into a prepared schema, validate aggressively, and keep a way back. If you plan to migrate data from Postgres to MySQL in production, rehearse the entire run on a staging copy first and time every phase.
Untuk versi bahasa Indonesia dengan tabel perbedaan tipe data dan contoh script, baca panduan migrasi PostgreSQL ke MySQL.
Related Reading
Eksplorasi konten lain dari Oentoro
Berlangganan untuk dapatkan pos terbaru lewat email.