When we run a query like:
INSERT INTO users (name, email)
VALUES ('Abid', 'abid@example.com');
it is tempting to imagine that PostgreSQL simply writes this row directly to the database file on disk.
But PostgreSQL does something more interesting.
Before modifying the actual data pages on disk, PostgreSQL first records information about the change in a Write-Ahead Log, commonly known as WAL.
This simple idea is one of the fundamental reasons PostgreSQL can provide durability, crash recovery, replication, and point-in-time recovery.
Let’s understand how it works.
What is WAL?
WAL stands for Write-Ahead Log.
The core rule is:
The log describing a change must reach durable storage before the corresponding data page is written to disk.
What actually happens when we insert data into PostgreSQL
What happens if PostgreSQL crashes?
This is where WAL really shines.
Imagine:
But suppose the modified table page was still only in memory.
After restarting, PostgreSQL performs crash recovery.
Conceptually:
So the database can reconstruct the required changes from WAL.
This process is often referred to as WAL replay or redo.