MySQL
Relational database ยอดนิยมที่ใช้ InnoDB เป็น default engine — จุดเด่นคือเปลี่ยน storage engine ได้ตามลักษณะ workload
Architecture — Clustered Index (InnoDB)
- ใช้ clustered index — primary key + ข้อมูลทั้ง row อยู่ใน leaf nodes ของ B+Tree
- ตาราง = primary index ตรง ๆ (ไม่มี heap แยก)
- Secondary index ชี้ไปที่ primary key (ไม่ใช่ row address)
- อ่าน secondary index → ต้อง 2 lookups: secondary → primary key → row
- แต่ UPDATE แถว (ที่ไม่ใช่ PK) → secondary index ไม่ต้อง update → write amplification ต่ำกว่า PostgreSQL
Page Size
- 16 KB ต่อ page (InnoDB default) — ใหญ่กว่า Postgres 2 เท่า
Storage Engines ที่เลือกได้
| Engine | ลักษณะ | Use case |
|---|---|---|
| InnoDB | B+Tree, ACID, row-level locking, FK | Default — ใช้ทั่วไป |
| MyISAM | B-Tree, ไม่มี transaction, table-level lock | Legacy — ห้ามใช้ใน production ใหม่ |
| MyRocks (RocksDB) | LSM-Tree, write-optimized | Write-heavy workload, insert เร็ว 10x, disk น้อย 50% |
| Aria (MariaDB) | คล้าย MyISAM แต่ crash-safe | MariaDB specific |
CREATE TABLE my_logs (...) ENGINE=RocksDB;
ALTER TABLE existing_table ENGINE=InnoDB;เปรียบเทียบกับ PostgreSQL
| ด้าน | MySQL (InnoDB) | PostgreSQL |
|---|---|---|
| Table storage | Clustered index | Heap-organized |
| Secondary index ชี้ไป | Primary key | tuple id (ctid) |
| Read via secondary | 2 lookups | 1 lookup |
| Write amplification | ต่ำกว่า | สูงกว่า |
| Engine เปลี่ยนได้ | ได้ | ไม่ได้ |
| Page size | 16 KB | 8 KB |
| MVCC | Undo log | Tuple versioning ใน heap |
กรณีของ Uber
Uber ย้ายจาก Postgres ไป MySQL ส่วนหนึ่งเพราะ write amplification ของ Postgres ไม่เหมาะกับ workload ที่มี UPDATE เยอะมาก — secondary index ทุกตัวต้อง update ทุกครั้งที่ tuple id เปลี่ยน
Key Points
- MySQL ใช้ clustered index — PK + data อยู่ด้วยกันใน leaf → secondary ชี้ PK
- เปลี่ยน storage engine ได้ตาม workload — จุดเด่นที่ Postgres ทำไม่ได้
- InnoDB เป็น default — ACID, row-level locking, FK support ครบ
- MyISAM = legacy, ไม่มี transaction, crash → corrupt → ห้ามใช้ในงานใหม่
- Write-heavy workload → พิจารณา MyRocks (LSM-Tree based)
Related
- PostgreSQL — คู่เปรียบเทียบหลัก
- Database Engines — InnoDB, MyISAM, RocksDB, LevelDB รายละเอียดลึก
- ACID — InnoDB รองรับ ACID ครบ, MyISAM ไม่
- Database Indexing — B+Tree structure ใน InnoDB
- Concurrency Control — Row-level locking vs Table-level locking