MySQL Connections, Cursors, and SQL Cache
On this topic, MySQL is the simplest. One connection is one thread, and each time a statement arrives it is parsed, optimized, and executed. There is no execution plan cache, and the query cache that stored the result of the same SELECT was removed in 8.0. The only things the server keeps across sessions are table definitions, open table handles, and pages in the InnoDB buffer pool. This structure works because the optimizer is relatively light, and in exchange a complex statement pays the optimization cost on every execution.
Key Specs
| Item | Value |
|---|---|
| Protocol | MySQL client/server protocol. Default TCP port 3306, Unix socket. The X protocol uses 33060 |
| One connection | One thread (Memory and Thread Architecture) |
| Maximum connections | max_connections (151) + 1 for an administrator. Per account max_user_connections (0 = unlimited) |
| Authentication | Authentication plugins. Default caching_sha2_password since 8.0 |
| Idle connection timeout | wait_timeout and interactive_timeout, both 28,800 seconds (8 hours) by default |
| Connect timeout | connect_timeout, default 10 seconds |
| Query modes | Text protocol (COM_QUERY), binary protocol (COM_STMT_PREPARE, COM_STMT_EXECUTE) |
| Execution plan cache | None. Optimizes on every execution |
| Query (result) cache | None. Removed in 8.0 |
| Prepared statements | Separate per session. Server-wide total limit max_prepared_stmt_count (16,382) |
| Cursors | DECLARE … CURSOR in stored programs (read-only, forward-only), protocol cursors (COM_STMT_FETCH) |
| Default result delivery | Sends the entire result to the client |
| Table cache | table_open_cache (4,000), table_definition_cache (automatic) |
| Statement execution time limit | max_execution_time (milliseconds, default 0). Applies only to read-only SELECT |
Connections
Figure. From connect to the first query
sequenceDiagram
participant C as Client
participant L as Connection manager thread
participant T as Connection thread
C->>L: TCP connection
L->>T: Assign a thread (reuse one from the thread cache if available)
T->>C: Initial handshake (server version, connection ID, authentication plugin, nonce)
C->>T: Handshake response (user, authentication value, default schema), switch to TLS first if needed
T->>C: Extra exchange depending on the authentication plugin
T->>C: OK
C->>T: COM_QUERY (SQL text)
T->>C: Column definitions, rows, OK
C->>T: COM_QUIT
T->>L: Return the thread to the cache or terminate
Diagram notes: Time flows from top to bottom.
- The
Connection manager threadaccepts the TCP connection and assigns aConnection thread. The assigned connection thread performs authentication. - Unlike PostgreSQL, the server speaks first. It sends an initial handshake containing the server version, connection ID, the authentication plugin to use, and a nonce, and the client returns the user name and an authentication value built from that nonce. For
caching_sha2_password, the server caches the account's authentication result in memory; if it is cached, one exchange is enough, and if not, a full authentication using TLS or an RSA key takes place. - After receiving
OK, the client sends commands. A command starts with a type byte such asCOM_QUERY(SQL text) orCOM_STMT_PREPARE. - When the connection ends, the thread returns to the thread cache (
thread_cache_size) if there is room and waits for the next connection.
One command at a time. The client cannot send the next command on the same connection before it has received the whole response. To stop a running statement, run KILL QUERY <connection ID> from another connection. KILL CONNECTION (or KILL) also drops the connection.
Connection pools and session state. The server has no connection pool, so you use an application-side pool or a proxy (ProxySQL, MySQL Router). To make sure the previous user's session variables, temporary tables, prepared statements, and open transactions do not remain when a pool reuses a connection, send COM_RESET_CONNECTION. It resets only the session state without authenticating again.
| Limit | Setting (default) | Description |
|---|---|---|
| Idle connection | wait_timeout (28,800 seconds) | The server drops the connection if there is no command for this long. Keep the pool's connection lifetime shorter than this |
| Read and write wait | net_read_timeout (30 seconds), net_write_timeout (60 seconds) | When the client stalls while sending or does not read the result |
| Connect errors | max_connect_errors (100) | Blocks a host when this many consecutive connection failures accumulate from it |
| Wait queue | back_log | Number of connection requests before a connection thread is assigned |
| Per account | CREATE USER … WITH MAX_USER_CONNECTIONS n | Limits the number of concurrent connections per account |
Statement Processing
Figure. Text protocol and prepared statements
flowchart LR
Q["COM_QUERY<br/>SQL text"] --> P["Parse"]
SP["COM_STMT_PREPARE<br/>SQL text with question marks"] --> P
P --> R["Resolve names, prepare<br/>tables, columns, privileges"]
R --> PS["Prepared statement<br/>session memory, statement ID"]
SE["COM_STMT_EXECUTE<br/>statement ID and parameter values"] --> PS
PS --> O["Optimize<br/>on every execution"]
R -->|"COM_QUERY goes directly"| O
O --> E["Execute"]
E --> RS["Result"]
Diagram notes: It proceeds from left to right.
COM_QUERYtakes SQL text and performsParse,Resolve names, prepare,Optimize, andExecuteevery time. Nothing remains after execution.COM_STMT_PREPAREparses text containing?placeholders, keeps the parsed and prepared result as aPrepared statementin that session's memory, and returns a statement ID.COM_STMT_EXECUTEsends only that ID and the parameter values, so it skips parsing.- On either path,
Optimizeruns on every execution. A prepared statement also does not store an execution plan; it re-chooses the join order and indexes using the parameter values and statistics at that time. So there is no problem like other DBMSs' parameter sniffing, but the only things a prepared statement saves are parsing and preparation.
You can also use prepared statements from SQL.
PREPARE ord_by_cust FROM 'SELECT * FROM orders WHERE cust_id = ?';
SET @id = 101;
EXECUTE ord_by_cust USING @id;
DEALLOCATE PREPARE ord_by_cust;
| Topic | Description |
|---|---|
| Scope | A prepared statement is visible only to the session that created it and disappears when the connection ends |
| Limit | PREPARE fails when the total across all sessions exceeds max_prepared_stmt_count. You hit it if an application does not close statements |
| Client-side emulation | Many drivers by default do not have the server prepare statements; they embed values in the text and send it with COM_QUERY (Connector/J's useServerPrepStmts defaults to false, and PHP PDO's emulation is on by default) |
| Value passing | The binary protocol sends values as typed binary and receives results as binary. Values are not mixed into the text, which prevents SQL injection |
| Stored programs | Procedures and functions cache the parsed form in that session the first time the session calls them (stored_program_cache, 256 per connection) |
What the Server Caches
Figure. What is cached and what is not
block-beta
columns 6
t1["Caches shared server-wide"]:6
bp["InnoDB buffer pool<br/>data and index pages"]:2 tc["Table cache<br/>open table handles"] td["Table definition cache<br/>dictionary object cache"] ac["Privilege cache<br/>authentication cache"] hc["Host cache"]
t2["Per session"]:6
ps["Prepared statements<br/>parse and prepare result"]:2 sp["Stored program cache"]:2 sv["Session variables<br/>temporary tables"]:2
t3["Not cached"]:6
n1["Execution plans"]:3 n2["Query results (removed in 8.0)"]:3
class t1,t2,t3 plain
class bp data
class tc,td,ac,hc meta
class ps,sp,sv slot
class n1,n2 warn
Diagram notes: From top to bottom the sharing scope narrows, and the last row is what does not exist.
- The
Table cacheholds the open handles a connection thread needs when it uses a table. Since a handle is needed for each session using the same table at once, many tables and many concurrent connections maketable_open_cachetoo small, and tables get opened and closed repeatedly. - The
Table definition cacheand thedictionary object cachehold table structure. Since 8.0 the data dictionary lives in InnoDB tables, and this cache reduces reads of those tables. - The
Privilege cacheholds accounts and privileges in memory, and theHost cacheholds the name resolution results for client IPs and connect error counts. Execution plansare not cached. The query cache, which storedquery resultsby text, had to discard all results of a table whenever the table changed and was protected by a single lock, so it became a bottleneck as core counts grew; it was deprecated in 5.7 and removed in 8.0. To cache results, do it in the application or a proxy.
performance_schema.events_statements_summary_by_digest holds execution statistics per statement shape (digest) with literals removed. It is statistics, not a cache, and you use it to see how often and for how long each shape of statement runs.
Result Sets and Cursors
| Mode | How to open | Behavior |
|---|---|---|
| Buffered (default) | mysql_store_result in the C API, default in most drivers | The server sends the whole result, and the client receives all of it in memory before returning. A large result uses up client memory |
| Streaming | mysql_use_result, setFetchSize(Integer.MIN_VALUE) in Connector/J | The client reads rows one at a time. Other commands cannot be sent on that connection until all rows are read. The server drops the connection if reading stalls longer than net_write_timeout |
| Protocol cursor | Run a prepared statement with the cursor flag, then COM_STMT_FETCH (Connector/J's useCursorFetch=true and a fetch size) | The server builds the result in an internal temporary table and sends the requested number of rows at a time |
| Stored program cursor | DECLARE … CURSOR inside a procedure or function | Receives one row at a time into variables and processes it |
Stored program cursors are fixed by the following three properties.
| Property | Meaning |
|---|---|
| Read-only | Rows read through the cursor cannot be updated with WHERE CURRENT OF |
| Forward-only | One row at a time in one direction. You cannot skip or go back |
| Asensitive | The server may make a copy of the result or read the original directly. Whether changes after opening are visible is not defined |
CREATE PROCEDURE sum_by_cust(IN p_cust INT, OUT p_total BIGINT)
BEGIN
DECLARE v_amt INT;
DECLARE done INT DEFAULT 0;
DECLARE c CURSOR FOR SELECT amt FROM orders WHERE cust_id = p_cust;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
SET p_total = 0;
OPEN c;
read_loop: LOOP
FETCH c INTO v_amt;
IF done = 1 THEN LEAVE read_loop; END IF;
SET p_total = p_total + v_amt;
END LOOP;
CLOSE c;
END
- A cursor is closed when the
BEGIN … ENDblock where it was declared ends. There is noDECLARE CURSORfor SQL outside stored programs. - To read a large result in pieces, key-based pagination (
WHERE id > last value read ORDER BY id LIMIT n) is more common than a cursor. It does not hold the connection and does not build a temporary table on the server.
Configuration and Checks
-- Connections and running statements
SHOW FULL PROCESSLIST;
SELECT id, user, host, db, command, time, state, info FROM performance_schema.processlist;
-- Connection counts and connect failures
SHOW GLOBAL STATUS WHERE Variable_name IN
('Threads_connected', 'Threads_running', 'Max_used_connections', 'Connections',
'Aborted_connects', 'Aborted_clients', 'Connection_errors_max_connections');
-- Prepared statements: count and per-session contents
SHOW GLOBAL STATUS LIKE 'Prepared_stmt_count';
SELECT statement_name, sql_text, owner_thread_id, count_execute, count_reprepare
FROM performance_schema.prepared_statements_instances;
-- Is the table cache sufficient? (if Opened_tables keeps growing, it is too small)
SHOW GLOBAL STATUS LIKE 'Open%tables';
SHOW GLOBAL STATUS LIKE 'Table_open_cache%';
-- Statistics per statement shape
SELECT digest_text, count_star, sum_timer_wait / 1e12 AS total_s, sum_rows_examined
FROM performance_schema.events_statements_summary_by_digest
ORDER BY sum_timer_wait DESC LIMIT 10;
-- Stop a running statement
KILL QUERY 1234;
- If
Aborted_clientsgrows, clients disappeared without closing the connection or hitwait_timeout; ifAborted_connectsgrows, authentication failed or the connection dropped during connect. - If the ratio of
Com_stmt_preparetoCom_stmt_executeis close to 1, statements are prepared, executed once, and discarded. This only adds round trips, so client-side emulation is better.
Comparison with Other DBMSs
| MySQL | PostgreSQL | Oracle | SQL Server | KDBS | |
|---|---|---|---|---|---|
| Execution plan cache | None | Session-local, prepared statements only | Shared pool (all sessions) | Plan cache (all sessions) | None. Remembers only the join order |
| What a prepared statement saves | Parsing, preparation | Parsing, analysis, (if a generic plan) planning | The whole parse | The whole compile | Parsing |
| Stopping execution | KILL QUERY from another connection | Cancel request on a new connection | ALTER SYSTEM CANCEL SQL from another session | Attention on the same connection | Cancel request on a new connection |
| SQL-level cursors | Only inside stored programs | DECLARE, FETCH | PL/SQL, every statement is a cursor | T-SQL cursors | None |
| Result cache | None (removed in 8.0) | None | Server result cache | None | None |
The full comparison is in DBMS Architecture at a Glance.
NOTE Defaults are for MySQL 8.0 and 8.4 and can vary with the version. This site has no MySQL sandbox, so the values in this document were not measured. For a driver's default behavior, check the driver version.
Related pages
- DBMS Architecture at a Glance
- MySQL (InnoDB)
- MySQL memory and thread structure
- InnoDB Buffer Pool
- InnoDB Gap Locks and Next-Key Locks
- PostgreSQL connections, cursors, and SQL cache
- Oracle Connections, Cursors, and the SQL Cache
- SQL Server Connections, Cursors, and Plan Cache
- KDBS connections, portals, and statement cache