What Happens Inside a Database After You Press Enter: The 14 Stages of an SQL QueryBrief · digest for December 2
Brief≈ 1 min

What Happens Inside a Database After You Press Enter: The 14 Stages of an SQL Query

You hit Enter on a short SELECT and wait three seconds for a reply. A familiar moment. Every SQL query travels through 14 steps inside the database, and a bottleneck can hide at any one of them.

First, the client sends the query text over the network (1). The server accepts the connection, verifies permissions, and assigns a worker—a process in PostgreSQL or a thread in MySQL (2). The parser breaks the text into tokens, checks syntax (3), and builds an internal AST (4). Next comes catalog lookup: confirming that tables, columns, types, and permissions exist (5). If the query hits any VIEW, the engine expands it into underlying tables (6).

Then the optimizer weighs execution strategies (7): whether to use an index or scan the whole table, and which JOIN algorithm to pick (hash, merge, or nested loop). Using ANALYZE statistics, it picks the cheapest plan (8)—the exact plan EXPLAIN prints.

Execution starts (9) with reads, WHERE, JOIN, GROUP BY, and ORDER BY. Pages are checked in the memory buffer pool first and fetched from disk only on a cache miss (10). Locks and MVCC (multi-version concurrency control) decide which row versions your transaction can see (11), and finished rows stream back to the client in batches (12). In a live database, steps 9–12 run in a pipelined stream. Finally, the engine updates stats and logs (13) and frees temporary memory (14).

Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 3