Skip to content

Cross-Database Migration Guide (PostgreSQL ↔ MySQL) ​

Migrating indexes between PostgreSQL and MySQL requires careful planning due to fundamental differences in index types, syntax, and behavior. This guide covers critical gotchas and workarounds.

Index Type Compatibility Matrix ​

text
Index Feature                PostgreSQL              MySQL 8.4 (InnoDB)      Migration Notes
────────────────────────────────────────────────────────────────────────────────────────────
B-Tree Index                 BTREE (default)         BTREE (default)         Direct equivalent
Hash Index                   HASH                    USING HASH vẫn tạo BTREE (InnoDB chỉ có adaptive hash nội bộ)
Partial Index                WHERE clause            Không có                Functional index/generated column có điều kiện (index vẫn chứa mọi dòng)
Expression Index             (LOWER(col))            Functional key parts ((LOWER(col))) từ 8.0.13
INCLUDE Clause               PG 11+                  Không có                Thêm cột vào khoá index (index lớn hơn)
Unique Partial Index         WHERE ...               Không có                Generated column trả NULL cho dòng ngoài điều kiện + UNIQUE KEY (UNIQUE bỏ qua NULL)
Prefix Index                 Không có trực tiếp      col(N)                  Dùng expression index LEFT(col, N)
Full-Text Search             GIN + tsvector          FULLTEXT                Cú pháp khác
Spatial Index                GiST (PostGIS)          SPATIAL (R-Tree)        PostGIS phong phú hơn
Array Containment            GIN trên array          Không có kiểu ARRAY     Bảng nối, hoặc JSON + multi-valued index (8.0.17+) với MEMBER OF
JSON Index                   GIN trên JSONB          Không index trực tiếp cột JSON: dùng generated column hoặc functional/multi-valued index
BRIN (Block Range)           Dữ liệu tuần tự         Không có                Partitioning (cần chọn biểu thức cho pruning được, xem mục 5)
BLOOM Filter                 Extension               Không có                Không có cách thay

1. Partial Indexes → Workarounds (PostgreSQL → MySQL) ​

PostgreSQL (native partial index):

sql
-- Index only active users
CREATE INDEX idx_active_users ON users(email)
WHERE status = 'active' AND verified = true;

-- Query uses index:
SELECT * FROM users WHERE status = 'active' AND verified = true AND email = 'john@example.com';
-- ✅ Uses idx_active_users (small, fast)

MySQL Workaround (không có partial index):

sql
-- MySQL 8.4. Bảng tạo trong khối, có 20 000 dòng (10% active, một nửa verified)
CREATE TABLE users (id INT PRIMARY KEY AUTO_INCREMENT, email VARCHAR(255), status VARCHAR(20), verified BOOLEAN, deleted_at DATETIME NULL);
SET SESSION cte_max_recursion_depth = 100000;
INSERT INTO users (email, status, verified)
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 20000)
SELECT CONCAT('User', i, '@Example.com'), IF(i % 10 = 0, 'active', 'inactive'), (i % 2 = 0) FROM n;

-- Cách 1: generated column (không cần trigger) + index kết hợp
ALTER TABLE users ADD COLUMN is_active_verified BOOLEAN
  GENERATED ALWAYS AS (CASE WHEN status = 'active' AND verified = 1 THEN 1 ELSE NULL END) STORED;
CREATE INDEX idx_active_users ON users (is_active_verified, email);

SELECT id FROM users WHERE is_active_verified = 1 AND email = 'User10@Example.com';
-- EXPLAIN: key = idx_active_users, Extra = Using index

-- Cách 2: functional index (8.0.13+), khỏi tốn cột lưu; truy vấn phải dùng ĐÚNG biểu thức đó
CREATE INDEX idx_active_fn ON users ((CASE WHEN status = 'active' AND verified = 1 THEN 1 END), email);
SELECT id FROM users WHERE (CASE WHEN status = 'active' AND verified = 1 THEN 1 END) = 1 AND email = 'User10@Example.com';

-- Lưu ý: đây KHÔNG phải partial index. Index vẫn có đủ 20 000 mục (dòng không thoả điều kiện có giá trị NULL ở cột đầu),
-- nên không nhỏ hơn index thường như partial index của PostgreSQL.
-- MySQL không có materialized view và không tạo được index trên VIEW (CREATE INDEX ON view báo ERROR 1347).

2. Expression Indexes → Generated Columns (PostgreSQL → MySQL) ​

PostgreSQL (expression index):

sql
-- Case-insensitive email search
CREATE INDEX idx_email_lower ON users(LOWER(email));

SELECT * FROM users WHERE LOWER(email) = 'john@example.com';
-- ✅ Uses idx_email_lower

MySQL (functional index, 8.0.13+):

sql
-- MySQL 8.4; chạy sau khối tạo bảng users ở mục 1
CREATE INDEX idx_email_lower ON users ((LOWER(email)));

SELECT id FROM users WHERE LOWER(email) = 'user10@example.com';
-- EXPLAIN: key = idx_email_lower (không cần đổi câu truy vấn, miễn dùng đúng biểu thức LOWER(email))

-- Nếu muốn có cột riêng (ví dụ để SELECT hoặc UNIQUE theo giá trị đã chuẩn hoá), dùng generated column:
-- ALTER TABLE users ADD COLUMN email_lower VARCHAR(255) GENERATED ALWAYS AS (LOWER(email)) STORED;
-- CREATE INDEX idx_email_lower2 ON users (email_lower);   -- khi đó truy vấn nên dùng email_lower

-- Lưu ý collation: cột dùng utf8mb4_0900_ai_ci (mặc định MySQL 8) vốn không phân biệt hoa thường,
-- nên WHERE email = 'user10@example.com' đã khớp 'User10@Example.com' (đo: 1 dòng); index LOWER() thường không cần.
-- PostgreSQL thì phân biệt hoa thường (LIKE phân biệt, ILIKE không), nên mới cần index trên LOWER().

3. INCLUDE Clause → Composite Index (PostgreSQL → MySQL) ​

PostgreSQL (covering index with INCLUDE):

sql
-- Index on email, include name/status for index-only scan
CREATE INDEX idx_user_email ON users(email)
INCLUDE (name, status);

SELECT name, status FROM users WHERE email = 'john@example.com';
-- ✅ Index-only scan (no heap fetch)

MySQL Workaround (composite index):

sql
-- Minh hoạ: giả định bảng users có thêm cột name (bảng users ở mục 1 chưa có cột này nên chạy nguyên văn báo ERROR 1072)
-- Thêm cột vào index (mọi cột đều thành phần của khoá, sắp xếp/lọc được)
CREATE INDEX idx_user_email_name_status ON users(email, name, status);

SELECT name, status FROM users WHERE email = 'john@example.com';
-- ✅ Covering index (no table lookup)

-- Caveat: name and status are part of index key, not just payload
--         Index is larger, but still works for covering

4. GIN/GiST Indexes → Workarounds (PostgreSQL → MySQL) ​

PostgreSQL (GIN index for arrays):

sql
-- Array column with GIN index
CREATE TABLE posts (
    id SERIAL PRIMARY KEY,
    tags TEXT[]
);

CREATE INDEX idx_tags ON posts USING GIN(tags);

SELECT * FROM posts WHERE tags @> ARRAY['postgresql', 'indexing'];
-- ✅ Uses GIN index for array containment

MySQL Workaround (junction table):

sql
-- Normalize to many-to-many relationship
CREATE TABLE posts (
    id INT PRIMARY KEY AUTO_INCREMENT
);

CREATE TABLE tags (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(50) UNIQUE
);

CREATE TABLE post_tags (
    post_id INT,
    tag_id INT,
    PRIMARY KEY (post_id, tag_id),
    INDEX idx_tag_post (tag_id, post_id)
);

-- Query with JOIN:
SELECT DISTINCT p.id
FROM posts p
INNER JOIN post_tags pt1 ON p.id = pt1.post_id
INNER JOIN tags t1 ON pt1.tag_id = t1.id AND t1.name = 'postgresql'
INNER JOIN post_tags pt2 ON p.id = pt2.post_id
INNER JOIN tags t2 ON pt2.tag_id = t2.id AND t2.name = 'indexing';
-- ✅ Uses composite indexes on post_tags

5. BRIN Indexes → Partitioning (PostgreSQL → MySQL) ​

PostgreSQL (BRIN cho chuỗi thời gian):

sql
-- PostgreSQL 18. Bảng 1 triệu dòng, created_at tăng dần
CREATE TABLE ev (id bigint, created_at timestamp);
INSERT INTO ev SELECT g, timestamp '2024-01-01' + g * interval '1 second' FROM generate_series(1, 1000000) g;
CREATE INDEX idx_ev_brin ON ev USING BRIN (created_at);
CREATE INDEX idx_ev_btree ON ev (created_at);
SELECT pg_size_pretty(pg_relation_size('idx_ev_brin')) AS brin,
       pg_size_pretty(pg_relation_size('idx_ev_btree')) AS btree,
       pg_size_pretty(pg_relation_size('ev')) AS heap;
-- Đã đo: brin 24 kB, btree 21 MB, bảng 42 MB (số phụ thuộc dữ liệu; đo lại bằng chính bảng của bạn)

MySQL (partitioning theo khoảng):

sql
-- MySQL 8.4. Dùng RANGE COLUMNS trên cột thời gian để pruning hoạt động
CREATE TABLE events (
    id BIGINT NOT NULL,
    created_at DATETIME NOT NULL,
    data TEXT,
    PRIMARY KEY (id, created_at)   -- khoá phân vùng phải nằm trong mọi khoá unique/PK
)
PARTITION BY RANGE COLUMNS (created_at) (
    PARTITION p202401 VALUES LESS THAN ('2024-02-01'),
    PARTITION p202402 VALUES LESS THAN ('2024-03-01'),
    PARTITION p202403 VALUES LESS THAN ('2024-04-01'),
    -- ... thêm phân vùng mỗi tháng
    PARTITION p_future VALUES LESS THAN (MAXVALUE)
);

CREATE INDEX idx_created_at ON events (created_at);
INSERT INTO events VALUES (1,'2024-01-05','a'),(2,'2024-02-05','b'),(3,'2024-03-05','c');
EXPLAIN SELECT * FROM events WHERE created_at >= '2024-02-01' AND created_at < '2024-03-01';
-- cột partitions = p202402: chỉ quét một phân vùng (pruning)

Lưu ý: nếu dùng PARTITION BY RANGE (YEAR(created_at) * 100 + MONTH(created_at)) như bản cũ, truy vấn khoảng trên created_at KHÔNG được pruning (đã đo: cột partitions liệt kê cả 4 phân vùng). Pruning chỉ cắt phân vùng, không nhỏ gọn như BRIN; bảng phân vùng InnoDB không hỗ trợ khoá ngoại.

6. Prefix Indexes (MySQL → PostgreSQL) ​

MySQL (prefix index):

sql
-- Index first 10 characters of email
CREATE INDEX idx_email_prefix ON users(email(10));

SELECT * FROM users WHERE email = 'john.doe@example.com';
-- ✅ Uses idx_email_prefix (smaller index)

PostgreSQL Workaround (expression index):

sql
-- Expression index on substring
CREATE INDEX idx_email_prefix ON users(LEFT(email, 10));

-- Query MUST use same expression:
SELECT * FROM users WHERE LEFT(email, 10) = 'john.doe@e';
-- ✅ Uses idx_email_prefix

-- Caveat: Cannot use for full string match without expression
-- Tốt hơn: dùng index đầy đủ trên cột (email ngắn nên không vấn đề). Lưu ý TOAST KHÔNG gỡ giới hạn kích thước mục index:
-- PostgreSQL 18 từ chối giá trị > 1/3 trang (ví dụ ERROR: index row size 3216 exceeds btree version 4 maximum 2704);
-- với chuỗi dài, index trên md5(col) hoặc dùng full-text.
CREATE INDEX idx_email ON users(email);

7. Clustered vs Heap Storage Impact ​

MySQL InnoDB (Clustered Index):

sql
-- PRIMARY KEY determines physical row order
CREATE TABLE orders (
    id INT PRIMARY KEY AUTO_INCREMENT,
    customer_id INT,
    created_at DATETIME,
    INDEX idx_customer (customer_id)
);

-- Secondary index lưu kèm giá trị PRIMARY KEY (INT: 4 byte)
-- idx_customer: khoá (customer_id 4 byte + id 4 byte) = 8 byte dữ liệu khoá mỗi mục, chưa tính header bản ghi và overhead trang

PostgreSQL (Heap Storage):

sql
-- PRIMARY KEY is just another unique index
CREATE TABLE orders (
    id SERIAL PRIMARY KEY,
    customer_id INT,
    created_at TIMESTAMP
);

CREATE INDEX idx_customer ON orders(customer_id);

-- idx_customer: (customer_id 4 byte, TID 6 byte) = 10 byte dữ liệu khoá thuần; mục thật lớn hơn (header tuple 8 byte, căn lề, con trỏ dòng 4 byte); so sánh công bằng cần đo bằng pg_relation_size
-- Physical row order doesn't match any index (heap storage)

-- Để xấp xỉ clustering của MySQL, dùng lệnh CLUSTER:
-- CẢNH BÁO: CLUSTER giữ khoá ACCESS EXCLUSIVE (chặn cả đọc lẫn ghi) suốt thời gian ghi lại bảng và cần thêm dung lượng đĩa cỡ bảng.
-- Chạy trong cửa sổ bảo trì trên bảng lớn; dùng pg_repack nếu cần làm online.
CLUSTER orders USING orders_pkey;
-- Sắp xếp lại bảng một lần theo PRIMARY KEY; dòng chèn/sửa sau đó KHÔNG được giữ thứ tự (phải chạy lại)

8. Concurrent Index Creation Differences ​

text
Feature                      PostgreSQL 18                MySQL 8.4
────────────────────────────────────────────────────────────────────────
Index không chặn ghi         CREATE INDEX CONCURRENTLY    ALGORITHM=INPLACE, LOCK=NONE (mặc định cho index phụ)
Khoá khi chạy                SHARE UPDATE EXCLUSIVE       Metadata lock độc quyền ngắn ở đầu và cuối
                             (cho phép đọc/ghi)           (chờ nếu có giao dịch dài đang mở)
Giới hạn                     Không chạy trong khối        Nhật ký DML trong lúc build có hạn
                             transaction                  (innodb_online_alter_log_max_size)
Khi lỗi                      Để lại index INVALID         Rollback, không còn index
Làm lại sau lỗi              DROP INDEX rồi chạy lại      Chạy lại
Build song song              PG 11+                       8.0.27+ (innodb_ddl_threads)
Theo dõi tiến độ             pg_stat_progress_create_    performance_schema: sự kiện stage/innodb/alter table*
                             index                        (WORK_COMPLETED/WORK_ESTIMATED, cần bật instrument/consumer)

Đã chạy trên mysql:8.4 (bảng 1 triệu dòng, ghi song song): ALGORITHM=INPLACE, LOCK=NONE thêm index trong 1,97 giây mà các INSERT/UPDATE đồng thời mất khoảng 0,09 giây (không bị chặn) và events_stages_current hiện stage/innodb/alter table (read PK and internal sort) 17118/38142; ALGORITHM=COPY chặn ghi 3,15 giây trong lúc build, và ALGORITHM=COPY, LOCK=NONE bị từ chối ERROR 1846 ... COPY algorithm requires a lock.

PostgreSQL:

sql
CREATE INDEX CONCURRENTLY idx_customer ON orders(customer_id);
-- Non-blocking, but slower
-- If fails, leaves INVALID index (must DROP manually)

-- Check for invalid indexes:
SELECT indexrelid::regclass, indisvalid
FROM pg_index
WHERE NOT indisvalid;

MySQL:

sql
-- MySQL 8.4
-- (bảng orders ở mục 7 đã có INDEX idx_customer; xoá trước để chạy lại được, nếu không báo ERROR 1061 Duplicate key name)
DROP INDEX idx_customer ON orders;
CREATE INDEX idx_customer ON orders(customer_id) ALGORITHM=INPLACE LOCK=NONE;
-- DML vẫn chạy trong lúc build (từ 5.6, không chỉ 8.0)
-- RỦI RO: lệnh cần metadata lock độc quyền ngắn ở đầu và cuối; nếu có giao dịch dài đang giữ MDL
-- trên bảng thì DDL chờ và các truy vấn sau nó xếp hàng phía sau -> kiểm trước bằng
-- SELECT * FROM performance_schema.metadata_locks WHERE object_name = 'orders';
-- Lỗi giữa chừng: tự rollback, không cần dọn

9. Migration Checklist ​

PostgreSQL → MySQL:

text
[ ] Partial index -> generated column / functional index (lưu ý index vẫn chứa mọi dòng)
[ ] Expression index -> functional key part ((LOWER(col))) từ 8.0.13
[ ] GIN/GiST/BRIN -> bảng nối, multi-valued index hoặc partitioning (pruning được)
[ ] INCLUDE -> thêm cột vào khoá index
[ ] tsvector full-text -> FULLTEXT (cú pháp khác)
[ ] So sánh EXPLAIN từng truy vấn chính
[ ] Chọn PK vì mọi secondary index chứa PK (clustered index)
[ ] Khác biệt isolation: gap lock ở REPEATABLE READ
[ ] Kiểu dữ liệu, collation, upsert, RETURNING, DDL (bảng bên dưới)

MySQL → PostgreSQL:

text
[ ] Prefix index -> index đầy đủ (hoặc LEFT())
[ ] Generated column -> expression index (đơn giản hơn)
[ ] FULLTEXT -> GIN với to_tsvector
[ ] SPATIAL -> PostGIS
[ ] Partitioning -> declarative partitioning (có thể thêm BRIN)
[ ] Không có gap lock; vẫn còn MVCC ở cả hai bên: đo lại tranh chấp thực tế
[ ] Theo dõi autovacuum / bloat (MySQL dùng purge thread, không cần VACUUM)
[ ] Build index song song (max_parallel_maintenance_workers); đo thời gian thật trước khi hứa hẹn

Ánh xạ kiểu dữ liệu và cú pháp thường gặp (đã chạy trên MySQL 8.4 / PostgreSQL 18):

PostgreSQLMySQL 8.4Ghi chú
SERIAL / IDENTITYINT/BIGINT AUTO_INCREMENTChạy lại sequence khi import dữ liệu
BOOLEANBOOLEAN (= TINYINT(1))
TIMESTAMPTZTIMESTAMP (đổi sang UTC khi lưu) hoặc DATETIMEChốt múi giờ trước khi chuyển
JSONBJSONIndex qua generated column/multi-valued
UUIDBINARY(16) hoặc CHAR(36)UUID_TO_BIN(uuid, 1) cho thứ tự thời gian
TEXT[] (ARRAY)không cóBảng nối hoặc JSON
LIKE (phân biệt hoa thường) / ILIKEcollation mặc định utf8mb4_0900_ai_ci không phân biệtHành vi so sánh đổi ngầm: kiểm UNIQUE và kết quả tìm kiếm
INSERT ... ON CONFLICT (k) DO UPDATE SET v = EXCLUDED.vINSERT ... AS new ON DUPLICATE KEY UPDATE v = new.v (8.0.19+)ON CONFLICT DO NOTHING ~ INSERT IGNORE (nuốt cả lỗi khác, thận trọng)
RETURNINGMySQL 8.4 không có (ERROR 1064); MariaDB cóĐọc lại bằng LAST_INSERT_ID() hoặc SELECT
DDL trong transaction (rollback được)DDL tự commit ngầmMigration nhiều bước cần kế hoạch lui riêng

Công cụ: pgloader, pg_dump/mysqldump (dùng --single-transaction để không khoá bảng InnoDB), AWS DMS, ora2pg (cho Oracle). Cutover: dừng ghi hoặc dùng logical replication/CDC, đối chiếu số dòng và checksum trước khi chuyển lưu lượng; có đường lui (giữ nguồn cũ ở chế độ chỉ đọc).

Đã chạy trên mysql:8.4 (bảng InnoDB 1 triệu dòng, ghi song song): mysqldump mặc định (--opt gồm --lock-tables) giữ metadata lock SHARED_READ_ONLY trên mọi bảng đang dump, nên UPDATE bị chặn tới khi dump xong (trong lần đo là khoảng 5 giây; số đổi theo máy, chỉ thứ tự độ lớn có ý nghĩa); thêm --single-transaction --routines --triggers thì ghi không bị chặn (0,08 giây). --single-transaction chỉ nhất quán cho bảng InnoDB: bảng MyISAM (và MEMORY) không nhất quán: vẫn có thể bị ghi trong lúc dump, hoặc bị table lock khi đọc (docs: "any MyISAM or MEMORY tables dumped while using this option may still change state").

pgloader 3.6.7 (image dimitri/pgloader) chạy được MySQL → PostgreSQL nhưng cần lưu ý: (1) MySQL 8.4 mặc định không nạp mysql_native_password và pgloader báo MYSQL-UNSUPPORTED-AUTHENTICATION với caching_sha2_password; phải khởi động mysqld với --mysql-native-password=ON (cờ của server MySQL, không phải cờ pgloader) và tạo user dùng plugin đó; (2) cột INT AUTO_INCREMENT không thành SERIAL (mất default, chỉ BIGINT AUTO_INCREMENT được tạo sequence orders_id_seq), phải tự thêm GENERATED ... AS IDENTITY hoặc sequence sau khi chuyển; (3) JSON thành json (không phải jsonb), TIMESTAMP/DATETIME thành timestamptz, BINARY(16) thành bytea, TINYINT(1) thành boolean, BIGINT UNSIGNED thành bigint (giá trị 18446744073709551615 làm hỏng cả bảng: 0 dòng nhập, FK không tạo được); (4) tên index bị đổi thành idx_<oid>_<tên cũ>, còn UNIQUE, index nhiều cột và FK được giữ.

10. Real-World Migration Example ​

Scenario: Migrating e-commerce database (PostgreSQL → MySQL)

PostgreSQL Schema:

sql
CREATE TABLE products (
    id SERIAL PRIMARY KEY,
    name TEXT,
    description TEXT,
    category VARCHAR(50),
    tags TEXT[],  -- Array of tags
    price DECIMAL(10,2),
    stock INT,
    is_active BOOLEAN
);

-- Partial index (active products only)
CREATE INDEX idx_active_products ON products(category)
WHERE is_active = true;

-- Expression index (case-insensitive name)
CREATE INDEX idx_name_lower ON products(LOWER(name));

-- GIN index (array containment)
CREATE INDEX idx_tags ON products USING GIN(tags);

MySQL Equivalent:

sql
CREATE TABLE products (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255),
    description TEXT,
    category VARCHAR(50),
    price DECIMAL(10,2),
    stock INT,
    is_active BOOLEAN,

    -- Generated column for partial index workaround
    is_active_flag BOOLEAN GENERATED ALWAYS AS (
        CASE WHEN is_active = 1 THEN 1 ELSE NULL END
    ) STORED,

    -- Generated column for case-insensitive search
    name_lower VARCHAR(255) GENERATED ALWAYS AS (LOWER(name)) STORED,

    INDEX idx_active_products (is_active_flag, category),
    INDEX idx_name_lower (name_lower)
);

-- Junction table for tags (replace GIN index)
CREATE TABLE tags (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(50) UNIQUE
);

CREATE TABLE product_tags (
    product_id INT,
    tag_id INT,
    PRIMARY KEY (product_id, tag_id),
    INDEX idx_tag_product (tag_id, product_id),
    FOREIGN KEY (product_id) REFERENCES products(id),
    FOREIGN KEY (tag_id) REFERENCES tags(id)
);

Kết luận quan trọng:

Migration giữa hai database cần chuyển đổi kiểu index, không chỉ đổi cú pháp. Các tính năng nâng cao của PostgreSQL (partial, expression, GIN/GiST/BRIN) phải được mô phỏng trong MySQL bằng generated column, functional index, bảng nối hoặc partitioning. Chuẩn bị cho index lớn hơn và nhiều thay đổi ở tầng ứng dụng khi chuyển sang MySQL.

Phải nhớ:

  1. MySQL không có partial index, INCLUDE, GIN/BRIN: mỗi cái có cách thay riêng và index thay thế thường lớn hơn.
  2. Kiểm cả hành vi ngầm: collation không phân biệt hoa thường, DDL tự commit, không có RETURNING, gap lock.
  3. Mọi cách thay thế phải kiểm bằng EXPLAIN và đo trên dữ liệu thật trước cutover.