PostgreSQL vs MySQL: differences in transactions, JSON and extensions
How PostgreSQL and MySQL differ in transactions and locking, JSON, types and extensions, with each extension's MySQL equivalent and when to pick each one.
Most new projects that start with MySQL do so because "everyone uses it" or "the tutorial used it." Rarely is it an informed decision about what the system will need. That works until the day an inventory counter goes wrong under concurrency because nobody knew the default isolation level, or the index you created for a JSON field simply isn't used by the query.
This is the comparison I wish I'd read before a few projects I won't name. It focuses on the three areas where the two databases actually diverge — transactions and locking, JSON, and extensions — and every SQL snippet below was run in postgres:18 (18.6) and mysql:8.4 (8.4.13) containers in November 2026. If the question is still whether you need a relational database at all, start with the relational vs NoSQL post.
Side-by-side summary
| PostgreSQL | MySQL (InnoDB) | |
|---|---|---|
| Current versions (Nov 2026) | 18 (Sep 2025); 19 in release candidate, GA planned for 2026-11-19 | 8.4 LTS and 9.7 LTS; Innovation line with calendar versioning (26.x). 8.0 reached end of life in April 2026 |
| Default isolation | READ COMMITTED |
REPEATABLE READ |
| Range locks | No gap locks; a conflict under REPEATABLE READ raises a serialization error |
Gap/next-key locks on locking reads under REPEATABLE READ |
SKIP LOCKED |
Yes | Yes (since 8.0) |
| JSON | Binary jsonb; GIN index for containment (@>) and key existence |
Binary JSON; functional indexes (8.0.13+) and multi-valued indexes for arrays (8.0.17+) |
| Types | Arrays, ranges, uuid, inet, enums as types, geometric types |
No arrays or ranges; per-column ENUM; spatial types |
RETURNING |
Yes | No (MariaDB has it) |
LATERAL |
Yes | Yes, since 8.0.14 |
| Transactional DDL | Yes (CREATE/ALTER inside a transaction can roll back) |
No: DDL causes an implicit commit |
| Extensions | Large ecosystem (PostGIS, pgvector, TimescaleDB, Citus...) | Plugins and components; most equivalents are built in or external |
| License | PostgreSQL License (permissive) | GPLv2 (Community) or Oracle commercial |
| Managed | RDS, Aurora, Cloud SQL, Azure, Neon, Supabase, etc. | RDS, Aurora, Cloud SQL, Azure, HeatWave, etc. |
The rest of the post explains the rows that weigh most in the decision.
Transactions and locking: where they differ most
Both use MVCC: plain reads don't block writes and writes don't block plain reads. The difference lies in the default isolation level and the kind of locks each one takes.
PostgreSQL ships with READ COMMITTED: each statement sees what was committed when it started. InnoDB ships with REPEATABLE READ: the whole transaction reads from a snapshot taken at its first read. But in MySQL that applies to plain SELECT — UPDATE, DELETE, and SELECT ... FOR UPDATE read the latest committed version. That's where counters and inventory surprise people. I ran this on MySQL 8.4, with a second session setting stock to 5 mid-transaction:
-- Session A (MySQL, default REPEATABLE READ)
START TRANSACTION;
SELECT qty FROM stock WHERE id = 1; -- 10
-- Session B: UPDATE stock SET qty = 5 WHERE id = 1; (commit)
SELECT qty FROM stock WHERE id = 1; -- 10 (snapshot)
UPDATE stock SET qty = qty - 1 WHERE id = 1;
SELECT qty FROM stock WHERE id = 1; -- 4 (the UPDATE used the current value, 5)
COMMIT;
Session A "saw" 10 twice and ended with 4. If the application computed something from the 10 it read, the computation is wrong. The same sequence in PostgreSQL under REPEATABLE READ won't let it through: the UPDATE fails with could not serialize access due to concurrent update, and the application must retry the transaction. Under READ COMMITTED (Postgres's default), the UPDATE waits for B's commit and applies qty - 1 to the 5. Neither behavior is "wrong" — but you need to know which one you have before writing inventory, balance, or queue logic.
The other practical difference is gap locks. Under InnoDB's REPEATABLE READ, a SELECT ... FOR UPDATE on a non-unique index also locks the range between records (a next-key lock), blocking other sessions' inserts into that range. That prevents phantom rows but raises the odds of waits and deadlocks on insert-heavy tables. The InnoDB documentation explains that under READ COMMITTED, gap locking is only used for foreign-key and duplicate-key checks — which is why many write-heavy teams switch MySQL to READ COMMITTED. PostgreSQL has no gap locks; to prevent phantoms it uses SERIALIZABLE with conflict detection (SSI), which also requires retries.
For job queues, both offer SELECT ... FOR UPDATE SKIP LOCKED, which lets several workers grab different rows without blocking each other:
SELECT id FROM jobs WHERE status = 'pending'
ORDER BY id
LIMIT 10
FOR UPDATE SKIP LOCKED;
It works the same in both (tested). Deadlocks exist in both databases; both detect them and abort one of the transactions. The rule that works for both: short transactions, a consistent row-access order, and retries in the application.
JSON: JSONB with GIN vs MySQL functional indexes
The old version of this post got this wrong, and it's a common mistake: a GIN index in PostgreSQL does not serve any query on the document. The default operator class, jsonb_ops, indexes the @>, ?, ?|, ?&, @?, and @@ operators (PostgreSQL 18 docs). A ->> comparison isn't on that list.
-- PostgreSQL 18, table with 200k events
CREATE INDEX events_payload_gin ON events USING GIN (payload);
-- Uses the GIN index (Bitmap Index Scan on events_payload_gin):
SELECT * FROM events WHERE payload @> '{"type": "purchase", "user_id": "123"}';
-- Does NOT use the GIN index (Seq Scan, even with enable_seqscan = off):
SELECT * FROM events WHERE payload->>'user_id' = '123';
-- For ->> on a specific field, use a B-tree expression index:
CREATE INDEX events_user_id ON events ((payload->>'user_id'));
-- now: Bitmap Index Scan on events_user_id
Another detail: @> is literal containment. payload @> '{"amount_above": 1000}' looks for a key named amount_above with value 1000 — not "amount above 1000." For ranges, extract and cast: (payload->>'amount')::int > 1000, with an expression index if the query is frequent.
GIN's real win is when you query by key combinations you don't know in advance via @>. If queries always hit the same field, a B-tree expression index is smaller and faster.
In MySQL, "indexing JSON requires a generated column" is outdated: since 8.0.13 there are functional indexes, and the database creates the hidden column itself. The detail that catches everyone is collation. ->> returns utf8mb4_bin; CAST returns the server's default collation. If the two don't match, a query written with ->> won't use the index — I confirmed it on 8.4 with EXPLAIN (type ALL, null key). The CREATE INDEX manual gives the fix:
-- MySQL 8.4: a functional index needs a name
CREATE INDEX idx_events_user_id
ON events ((CAST(payload->>'$.user_id' AS CHAR(36)) COLLATE utf8mb4_bin));
-- This query now uses idx_events_user_id (EXPLAIN: type=ref)
SELECT * FROM events WHERE payload->>'$.user_id' = '123';
-- JSON arrays: multi-valued index (8.0.17+)
CREATE INDEX idx_events_tags ON events ((CAST(payload->'$.tags' AS CHAR(20) ARRAY)));
SELECT * FROM events WHERE 'a' MEMBER OF (payload->'$.tags');
Also note that CREATE INDEX ON events (...), without a name, is PostgreSQL syntax; in MySQL it's error 1064. Bottom line: both index JSON fields. PostgreSQL has the edge with GIN for arbitrary containment queries; MySQL requires knowing the field and the exact expression up front.
Data types: where PostgreSQL still pulls ahead
MySQL covers everyday types well. PostgreSQL adds types that eliminate auxiliary tables and application-side validation:
- Native arrays (
text[],uuid[]): a list of tags without a join table. uuidas a 16-byte type, and since PostgreSQL 18 theuuidv7()function for time-ordered UUIDs.- Ranges (
tstzrange,daterange,int4range) with overlap and containment operators, plus exclusion constraints to prevent overlapping bookings. inet/cidr, enums as reusable types, and geometric types.
CREATE TABLE articles (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
title text NOT NULL,
tags text[],
metadata jsonb,
active_period tstzrange
);
SELECT title
FROM articles
WHERE 'postgresql' = ANY(tags)
AND metadata->>'author' = 'rafael'
AND active_period @> now();
One detail the test caught: with tsrange (no time zone), active_period @> now() fails with operator does not exist: tsrange @> timestamp with time zone. Use tstzrange with now(), or cast explicitly. In MySQL, this schema becomes a separate tags table and two date columns with hand-written overlap logic.
SQL conformance and query features
MySQL was long permissive with GROUP BY: it accepted non-aggregated columns and returned an arbitrary value. ONLY_FULL_GROUP_BY has been the default since 5.7.5, and on 8.4 the query below raises error 1055 — but legacy databases sometimes run with that mode turned off.
SELECT customer_id, total FROM orders GROUP BY customer_id;
-- PostgreSQL: column "orders.total" must appear in the GROUP BY clause...
-- MySQL 8.4 (default sql_mode): ERROR 1055 ... incompatible with sql_mode=only_full_group_by
The rest has converged more than many older comparisons suggest:
- CTEs, including
WITH RECURSIVE: both have them (MySQL since 8.0). The real difference is that PostgreSQL 12+ lets you forceMATERIALIZEDorNOT MATERIALIZED; on MySQL 8.4 that syntax is an error. - Window functions: both (MySQL since 8.0).
LATERAL: MySQL supports lateral derived tables since 8.0.14. The "last two orders per customer" query withCROSS JOIN LATERAL (... LIMIT 2)returned the same result on both databases.RETURNING: PostgreSQL only. In MySQL,INSERT ... RETURNINGis a syntax error; you useLAST_INSERT_ID()or a second query. MariaDB does haveRETURNING, which confuses a lot of people.
-- PostgreSQL: INSERT with RETURNING saves a round-trip
INSERT INTO users (name, email)
VALUES ('rafael', 'rafael@example.com')
RETURNING id, created_at;
PostgreSQL extensions and their MySQL equivalents
The extension system is the difference that matters most in the long run. But "MySQL has nothing like it" is an exaggeration — almost every one has an equivalent, built in or external, with different limitations:
| PostgreSQL extension | What it does | MySQL equivalent |
|---|---|---|
| PostGIS | Full geospatial database: distances, polygons, geofencing, reprojection | InnoDB's native spatial types and indexes (with SRID). Covers the basics; PostGIS has far more functions |
pgvector (vector extension) |
Vectors and similarity search with HNSW/IVFFlat indexes | VECTOR type since MySQL 9.0, but the DISTANCE() function exists only in HeatWave and MySQL AI, not in Community Edition |
| TimescaleDB | Time series with automatic partitioning and compression | Native RANGE partitioning; creating partitions and compression are up to you |
| pgcrypto | Hashing and encryption in the database | Built-in AES_ENCRYPT(), SHA2(), etc. |
| pg_stat_statements | Aggregated per-query statistics | Performance Schema and the sys schema (e.g. events_statements_summary_by_digest) |
| Citus | Horizontal sharding for PostgreSQL | Vitess (external). Group Replication/InnoDB Cluster is high availability, not sharding |
| pg_partman | Automatic partition maintenance | No direct equivalent; scripts or scheduled events |
In practice: if the product depends on serious geospatial work or vector search in the open-source edition, PostgreSQL is ahead. For encryption and query observability, MySQL gets there with built-in features.
When to use MySQL and when to use PostgreSQL
MySQL makes sense when there's a concrete reason:
- An existing system and team on MySQL. Migration is expensive: permissive
GROUP BY, auto-increment vs sequences, engine-specific functions, and stored procedures all need case-by-case review.pgloaderautomates loading the data, not reviewing the queries. "PostgreSQL is better" doesn't justify a six-month migration. - An ecosystem that expects MySQL: some ERPs, CMSs, and BI tools have more mature support for it.
- Replication infrastructure the team already masters (InnoDB Cluster, Vitess).
On performance: MySQL has a reputation for being faster at simple key lookups, but that depends on version, hardware, and configuration. Measure with your workload before using it as an argument.
PostgreSQL is my default for everything else, and especially for:
- transactional data where you want transactional DDL and explicit errors on concurrency conflicts;
- semi-structured JSON queried by containment;
- geospatial (PostGIS) and embeddings (pgvector);
- teams writing queries with CTEs, window functions, and
LATERALwho wantRETURNING.
Frequently asked questions
Is PostgreSQL slower than MySQL?
Not in general. For simple key lookups the two are close, and the result depends more on indexes, hardware, and configuration than on the database. Part of PostgreSQL's "heavy" reputation comes from conservative default configuration — tuning shared_buffers, work_mem, and effective_cache_size to the hardware usually changes the picture a lot. Benchmark with your real workload.
Has MySQL 8.4 closed the gap with PostgreSQL?
A good part of it. Recursive CTEs, window functions, LATERAL, functional and multi-valued JSON indexes, and ONLY_FULL_GROUP_BY by default came with the 8.0 line and carry on in 8.4 LTS. Still on PostgreSQL's side: RETURNING, transactional DDL, arrays and ranges, GIN for JSON, and the extension ecosystem. If you still run MySQL 8.0, it reached end of life in April 2026 (last release: 8.0.46); the upgrade path is 8.4 LTS.
Does PostgreSQL store the time zone in a timestamp?
No. timestamptz converts the value to UTC on write and displays it in the session's time zone on read; the original zone isn't stored. I tested it: wrote 10:00-03, switched the session to UTC, and read 13:00+00. If the original zone matters (a user's calendar, for example), store it in a separate column, such as text with the IANA name (America/Sao_Paulo).
Which database for a new SaaS project?
PostgreSQL as the default. Pick MySQL when a platform constraint, a legacy system, or team expertise outweighs the differences above. And if the project is small, with a single server and little concurrent writing, ask whether you need a database server at all — the post on when to use SQLite covers that. For what's coming in the next Postgres release, see what's new in PostgreSQL 19.
PostgreSQL by default, MySQL when there's a concrete reason
My heuristic hasn't changed: start with PostgreSQL. If a concrete reason for MySQL shows up — a legacy system, a platform constraint, a team with exclusive expertise — consider it. If the reason is "it's more popular" or "the tutorial used it," that doesn't count. Whichever you pick, find out the default isolation level and check your JSON field's index with EXPLAIN before going to production: those are the two places I've seen people get surprised most.
When I'm comparing the same query across both databases, I paste both versions into the SQL Formatter so CTEs and subqueries are readable side by side — it makes it much easier to spot where the dialect changes.
- 01 CPU Cores vs. Threads: What Actually Changes in Practice Understand the difference between CPU cores and threads and what actually changes for performance, multitasking, gaming, and development.
- 02 MIT, Apache, and GPL Licenses: Practical Differences for Developers MIT, Apache 2.0, and GPL are not the same thing. Understand permissive vs copyleft, patent protection, and compatibility before shipping code to production.