MySQL or PostgreSQL? How I Choose After Six Years of Running Both

Table of Contents
Reading Progress
0%

In 2023 a support ticket landed on my desk: the client’s app felt slow every Monday morning. Not down, just slow. The transaction list page took eight seconds instead of the usual one.

I opened the dashboards. The database was MySQL 5.7 on a four-core VPS, and its replica was nearly ten minutes behind every start of the week. The cause was not a strange query. It was one monthly report the finance team ran every Monday: a GROUP BY across three large tables with a JOIN that had no supporting index. That query scanned everything, filled the buffer pool, and the replica serving reports fell behind.

Two years later, at another company, I inherited PostgreSQL 12 with an entirely different problem: the disk was full. Not because there was much data, but because one audit_log table was updated constantly and autovacuum never caught up. Three gigabytes of table for four hundred thousand rows.

Those two incidents explain why I am tired of “MySQL vs PostgreSQL” articles built on benchmark tables. The problems I actually meet in production are almost never about which engine reads ten million rows faster. They are about migrations that half-complete, connections that pile up, and one reporting query that ruins everyone’s morning.

So this is not a neutral comparison. It is a working developer’s notes, including the choice I made and why.

The short version, before the nuance

MySQL is very hard to make a mess of. It is installed everywhere, the tooling is mature, read replicas are simple, and every hosting provider offers it. If your app is CRUD with heavy read traffic and a normal schema, MySQL will run for years without you thinking about it.

PostgreSQL prefers that you be honest. Types are strict, DDL is transactional, SQL is complete, and the extension ecosystem is large. In exchange, you have to care about vacuum, connections, and major upgrades.

If you only have thirty seconds: for a new project I start today, under the conditions I describe below, I pick PostgreSQL 18. For an application already running on MySQL with no real problems, I would not touch it.

What each one is actually optimising for

Most technical differences trace back to one design decision.

MySQL, through InnoDB, stores rows inside the primary key. The table itself is a B-tree ordered by PK. The upside: primary key lookups are very cheap, because the row lives in the same page as the index. The cost: a large random PK such as a UUID makes every insert write to a random page, and every secondary index stores the PK inside it, so a fat PK multiplies the cost of all your indexes. That is why the MySQL community is so insistent about BIGINT AUTO_INCREMENT.

PostgreSQL stores rows in a heap, and indexes point at the row’s physical location. The primary key is just a unique index. The upside: random PKs do not punish inserts, and you can have many indexes without duplicating the PK into each one. The cost: every UPDATE writes a new row version, and the old one must be cleaned up by vacuum. Forget that and your table bloats, exactly like my audit_log.

Neither model is right or wrong. But once you understand them, every complaint people have about each database starts to make sense.

MySQL’s real advantages

Simple to the point of boring, and that is a compliment. CREATE TABLE, connect, query, done. There is no shared_buffers to calculate and no work_mem that spills a query to disk when you get it wrong. Defaults are good enough for most small applications.

Read replicas are easy. One CHANGE REPLICATION SOURCE TO, one replication user, done. For a read-heavy app, adding a replica is the cheapest capacity you can buy.

The widest hosting footprint. Almost every shared host, panel, and managed service offers MySQL. If you deploy somewhere you do not fully control, MySQL is often the only option.

The PHP ecosystem lives on MySQL. WordPress, Laravel, and most PHP applications treat MySQL as the default. That is not a technical argument, but it is a very expensive practical one to ignore.

Sharding that has been proven at scale. Vitess and PlanetScale make horizontal sharding of MySQL possible at a scale PostgreSQL struggles to match without adding an extension layer such as Citus. If you genuinely expect to outgrow a single machine, that matters.

Cheaper memory per connection. MySQL uses threads; PostgreSQL uses processes. For a PHP-FPM app opening five hundred connections at once, MySQL is far friendlier and needs no additional connection pooler.

MySQL’s drawbacks that make me cautious

DDL is not transactional. This one hurts me most often. ALTER TABLE in MySQL commits implicitly. If a migration fails halfway, there is no ROLLBACK. You get a half-changed table and have to fix it by hand while hoping the backup is still valid. In PostgreSQL, a failed ALTER TABLE means nothing changed.

No RETURNING. Every insert that needs a generated value costs two round trips: INSERT, then LastInsertId(). It sounds trivial until you insert several rows and have to guess the order.

No partial indexes. A requirement like “email is unique only among users that are not deleted” has to be worked around in MySQL with a generated column and a unique index on top of it. It works, but it becomes tribal knowledge every new teammate must inherit.

REPEATABLE READ by default, with gap locks. This is the source of the deadlocks that confuse new developers most. Two transactions inserting different ranges can block each other because of gap locking, and the error message does not help at all. PostgreSQL defaults to READ COMMITTED without gap locks, and if you need stronger guarantees you can move to SERIALIZABLE with SSI.

Silent type coercion. MySQL converts mismatched types and only warns. We had the classic case on my team: a phone number 08123456789 compared as a number, the leading zero dropped, and a “find user” query returned the wrong person. PostgreSQL refuses that comparison with an error, which is annoying for five minutes and saves your data for five years.

The SQL is incomplete. There is still no FULL OUTER JOIN. INTERSECT and EXCEPT only arrived in 8.0.31. For reporting that needs analytical queries, you will often write two queries and merge them in the application.

Licensing and enterprise features. Community Edition is GPLv2. Several things that are free in PostgreSQL, such as thread pool, audit, and backup encryption, sit behind MySQL’s paid edition.

PostgreSQL’s advantages that keep me there

Transactional DDL. Migrations can be wrapped in a single transaction. Fail halfway? Everything rolls back. That one feature changed how I work with CI: migrations can be tested, rolled back, and re-run without leaving residue.

RETURNING and ON CONFLICT. One round trip for an insert that returns values. In Go, that removes an entire class of LastInsertId bugs.

Serious data types. jsonb, arrays, range, inet, uuid, timestamptz, and correct numeric. jsonb with a GIN index often removes the need for a separate document database for payloads whose shape keeps changing.

Flexible indexing. Partial indexes, expression indexes, covering indexes with INCLUDE, GIN for text and JSON, GiST for geospatial data, BRIN for very large time-series tables. I have solved performance problems many times by adding the right index instead of adding a server.

Extensions. PostGIS, pgvector, TimescaleDB, pg_partman, Citus, postgres_fdw. If the product needs vector similarity search tomorrow, I do not add a new service; I run CREATE EXTENSION vector.

Complete and correct SQL. Window functions, recursive CTEs, MERGE, GROUPING SETS, materialized views with REFRESH CONCURRENTLY, and CREATE INDEX CONCURRENTLY that does not lock the table. A report that takes three queries in MySQL takes one here.

Good built-in observability. pg_stat_statements, pg_stat_activity, auto_explain, pg_stat_user_tables. I can see which query is expensive and which table is accumulating dead tuples without installing any agent.

PostgreSQL’s drawbacks you have to accept

Vacuum is not optional. This is the real operational cost. UPDATE and DELETE leave dead rows behind. Autovacuum is usually enough, but once you have a table updated constantly, a long transaction, or a replica holding back xmin, vacuum falls behind and the table bloats. You need to watch n_dead_tup and last_autovacuum. That is routine work, not theory.

One process per connection. PostgreSQL uses OS processes, not threads. Five hundred direct connections mean five hundred processes, each with its own memory. In an app with many workers, you need PgBouncer. That is one more component to maintain.

Major upgrades need a plan. There is no safe apt upgrade across major versions. You use pg_upgrade with downtime, or logical replication to move with minimal downtime. Both require rehearsal, not improvisation at eleven at night.

The planner can be wrong. PostgreSQL has a far smarter optimizer than MySQL for complex queries, but “smarter” does not mean “never wrong”. A bad selectivity estimate on a correlated table can produce a nested loop that destroys performance. You need to know how to read EXPLAIN (ANALYZE, BUFFERS).

Identifiers are case-sensitive when quoted. "User" and user are two different things. Developers coming from MySQL are often surprised, and an ORM that generates mixed-case column names will make your life difficult.

Logical replication is incomplete. DDL is not replicated, sequences are not replicated, and conflicts can happen. For CDC into Kafka through Debezium this is usually fine, but do not expect to move an entire database with one command and forget about it.

Not every managed service offers it as cheaply as MySQL. In Indonesia, budget VPS plans and hosting panels still tend to list MySQL first. That is not a technical weakness, but it is real when you build a budget.

The short comparison

Aspect MySQL PostgreSQL
Storage model Clustered index, rows inside the PK Heap plus separate indexes
Default isolation REPEATABLE READ, gap locks READ COMMITTED, no gap locks
Transactional DDL No Yes
RETURNING No Yes
Partial indexes No Yes
JSON JSON type, functional indexes jsonb with GIN
Full-text search Available, limited Available, enough for many cases
Extensions Limited Very large
Replication Binlog, GTID, very mature Streaming physical and logical
Sharding Vitess, PlanetScale Citus, or manual
Memory per connection Smaller (threads) Larger (processes)
Routine maintenance Replication and indexes Vacuum, connections, major upgrades
PHP/WordPress ecosystem Dominant Minority

The same code, two databases

The differences show up most in the small things you write every day.

An insert that returns values. In MySQL:

INSERT INTO orders (customer_id, total)
VALUES (?, ?);

SELECT LAST_INSERT_ID();

Two round trips, and LAST_INSERT_ID() depends on being on the same connection. In PostgreSQL:

INSERT INTO orders (customer_id, total)
VALUES ($1, $2)
RETURNING id, created_at;

One round trip, and in Go it becomes this simple:

var id int64
var createdAt time.Time

err := db.QueryRowContext(ctx,
    `INSERT INTO orders (customer_id, total)
     VALUES ($1, $2)
     RETURNING id, created_at`,
    customerID, total,
).Scan(&id, &createdAt)
if err != nil {
    return fmt.Errorf("create order: %w", err)
}

Upsert. MySQL 8.0 and later:

INSERT INTO stock (sku, qty)
VALUES (?, ?) AS new
ON DUPLICATE KEY UPDATE qty = qty + new.qty;

Note the AS new. The old VALUES(qty) form has been deprecated since 8.0.20, and plenty of production code still uses it.

PostgreSQL:

INSERT INTO stock (sku, qty)
VALUES ($1, $2)
ON CONFLICT (sku) DO UPDATE
SET qty = stock.qty + EXCLUDED.qty
RETURNING qty;

JSON payloads whose shape changes. In PostgreSQL this is one column and one index:

CREATE TABLE events (
    id          bigserial PRIMARY KEY,
    type        text NOT NULL,
    payload     jsonb NOT NULL,
    created_at  timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX events_payload_gin ON events USING gin (payload jsonb_path_ops);

SELECT id, payload->>'order_id' AS order_id
FROM events
WHERE payload @> '{"type": "payment.settled"}'
  AND created_at >= now() - interval '1 day';

In MySQL you can do something similar with generated columns and functional indexes, but every field you want indexed needs an extra column defined up front. For a payload that changes every quarter, that hurts.

One more thing that saves me regularly: a partial index for soft deletes.

CREATE UNIQUE INDEX users_email_active_idx
ON users (email)
WHERE deleted_at IS NULL;

Meaning: the email is unique only among users that still exist. In MySQL this needs a generated column that holds email when deleted_at IS NULL and NULL when it is deleted, plus a unique index on top. Possible, but every new developer has to be told why that column exists.

So which one do I pick in this situation?

I should be honest about the phrase “this situation”, because an answer without context is just taste. The situation I mean is the one I keep running into, and the one I think represents a lot of teams here:

  • A Golang or Node backend, one database for both transactions and light reporting.
  • A team of three to five people, with no dedicated DBA.
  • Deployment on an 8 GB VPS or a small managed database, not a cluster.
  • Automatic migrations in CI, with no tolerance for long downtime.
  • Data that grows, but not to billions of rows yet.
  • Occasional JSON payloads whose shape changes.
  • A good chance of needing text or vector search later, and no appetite for three more services.

Under those conditions, I pick PostgreSQL 18.

Why PostgreSQL and not MySQL

First, because migration is my biggest risk, not performance. In six years, the number of production incidents I have had because a migration failed is far larger than the number caused by a query being too slow. Transactional DDL means a failed migration leaves nothing behind. In MySQL, one ALTER TABLE running out of disk halfway can mean a whole night restoring a table. PostgreSQL removes that entire class of problem, and that alone justifies the choice.

Second, because my Go code gets shorter and safer. RETURNING removes LastInsertId, ON CONFLICT removes the “select first, insert if missing” pattern that always has a race condition, and strict types catch mistakes before production. I do not need an extra validation layer to cover for silent coercion.

Third, because one database can do two jobs. For needs that would force me to add Elasticsearch, Redis, or a document database on MySQL, PostgreSQL is often enough: jsonb plus GIN for payloads, full-text search for simple lookups, materialized views for reports, partial indexes for queries that always filter active rows. Every extra service is operational cost, and a small team does not have the budget for it.

Fourth, because the growth path is clear. If a recommendation feature appears tomorrow, I run CREATE EXTENSION vector. If I need geospatial, PostGIS. If the events table grows huge, BRIN and declarative partitioning. If I need CDC into Kafka, logical replication. I do not have to change databases for the next three requirements.

Fifth, because diagnosis is transparent. pg_stat_statements and pg_stat_activity ship with every installation. When the app is slow at two in the morning, I can see which query is expensive and who is holding a lock, without installing a third-party agent.

The cost I accept

This choice is not free, and I will not sell it as if it were.

I have to run PgBouncer from day one, because Go with database/sql opens many connections and every PostgreSQL connection is a process. I have to monitor dead tuples and last_autovacuum, because one audit_log table already ate my disk once. I have to plan major upgrades, because pg_upgrade is not something I run while watching a film. And I have to make sure no transaction hangs, because one idle in transaction connection can hold back vacuum for hours.

The first three are solved with a dashboard and a one-page runbook. The fourth needs discipline in code, and it is still cheaper than one full-disk incident.

When I choose MySQL instead

So this recommendation does not sound like fanaticism:

PHP or WordPress applications. If the ecosystem expects MySQL, fighting it is not a technical decision, it is a hobby.

Thousands of direct connections without a pooler. MySQL with threads is far friendlier. If the architecture is PHP-FPM with hundreds of workers, MySQL removes a component from the diagram.

A real need for horizontal sharding. If you know from the start that you will outgrow a single machine and you need proven sharding, Vitess or PlanetScale is a strong reason to pick MySQL.

A simple schema, heavy read traffic, and a team that already knows it. Team skill is a technical factor. A team fluent in MySQL will ship faster and debug incidents more calmly than a team that just learned PostgreSQL from an article.

Vendor software that requires MySQL. Many commercial products only support MySQL. There is no point arguing.

If one of those five is your main condition, the answer is MySQL, and there is nothing to feel defeated about.

If you are already on MySQL

Do not migrate because of an article. Migrate when you have a problem you actually experience: migrations that keep failing, reports you cannot write without help from the application, or JSON needs that force a new column every month.

If you do need to move, the order is roughly this. Measure the most expensive queries in MySQL first and confirm they are also fast on the PostgreSQL version, because not every query improves automatically. Fix the bad queries and missing indexes first; the bottleneck is often there, not in the engine. Then move service by service, not the whole database at once, with dual writes and result comparison for a few weeks. For the initial load, pgloader is still the fastest route. For a cutover without long downtime, use logical replication into PostgreSQL, move read traffic first, and writes last.

What I see most often: a database migration is done to chase 20% more performance, while 80% of the problem is one missing index. That is not a reason to move, it is a reason to open EXPLAIN.

The checklist I use

Before deciding, I answer these in order:

  1. Does the team have a real problem with the current database? If not, do not touch it.
  2. Has a failed migration ever hurt us? If yes, PostgreSQL.
  3. Does our schema need JSON, text, or geospatial data? If yes and we do not want extra services, PostgreSQL.
  4. Will we open thousands of connections without a pooler? If yes, MySQL is cheaper.
  5. Do we need horizontal sharding within two years? If yes, MySQL with Vitess.
  6. Does the application ecosystem require MySQL? If yes, done, use MySQL.
  7. Does anyone here know how to maintain vacuum and upgrades? If nobody does, use a managed PostgreSQL instead of a self-hosted one.
  8. Are we ready to pay the operational cost of the choice? Every database has a monthly bill, and the expensive part is rarely the licence.

Closing

I do not believe there is a database that wins in general. I believe MySQL and PostgreSQL optimise different things, and that most internet arguments happen because people compare two tools that were not solving the same problem.

MySQL optimises simplicity and presence. It is everywhere, easy to run, and good enough for most applications I have seen. PostgreSQL optimises honesty and completeness. It asks you to manage more, and in return it gives you tools that rarely let you down when the problem gets complicated.

Choose by Workload, Not by Trend

blog-img

If you are deciding right now: look at what wakes you up at two in the morning. If the answer is failed migrations, messy data types, or reports you cannot write in plain SQL, PostgreSQL will pay for itself. If the answer is "nothing, it all runs", then you do not have a database problem, and either choice will feel right. And if you pick MySQL, use it with confidence. A database that is well maintained and understood by its team always beats a fancier one that was installed because it was trending. 🐬🐘

Comments

comments powered by Disqus