MySQL CONNECTION_ID() Function
MySQL CONNECTION_ID() Function
The MySQL CONNECTION_ID() function returns the unique integer connection identifier (thread ID) assigned to the current client session. Every active MySQL connection receives a distinct ID that matches the Id column in SHOW PROCESSLIST.
Syntax
CONNECTION_ID()
- Takes zero arguments. Calling
CONNECTION_ID()requires parentheses and returns an unsignedBIGINT(orINTdepending on server version) identifying the current thread.
This function is especially helpful when tracing pooled application connections, debugging InnoDB row locks, or writing session IDs into audit log tables.
Practical Example
You can log the current database thread ID alongside an order status change in demo_orders or inspect your session context directly.
SELECT
CONNECTION_ID() AS session_thread_id,
order_id,
status
FROM demo_orders
LIMIT 3;
| session_thread_id | order_id | status |
|---|---|---|
| 4821 | 1001 | paid |
| 4821 | 1002 | pending |
| 4821 | 1003 | shipped |
Common Mistakes & NULL Behavior
- NULL behavior:
CONNECTION_ID()takes no parameters and never returnsNULLduring an active database connection. Passing any argument (evenNULL) causes a syntax error (Incorrect parameter count). - Connection pooling reuse: Web apps using persistent connections or connection pools share threads across HTTP requests. Do not treat
CONNECTION_ID()as an end-user ID; it identifies the TCP/socket session to MySQL, not the application user. - Replication safety: Because
CONNECTION_ID()depends on the server thread executing the query, statement-based replication handles it via binary log metadata, while row-based replication writes the resolved values directly. - Processlist correlation: Match
CONNECTION_ID()againstperformance_schema.threads.PROCESSLIST_IDorSHOW FULL PROCESSLISTto inspect orKILLa stuck query.
Frequently Asked Questions
Does CONNECTION_ID() accept any arguments?
No. CONNECTION_ID() takes zero arguments. Passing NULL or any expression raises an error.
Does CONNECTION_ID() stay the same for the whole session?
Yes. It remains constant from the moment the client connects until the connection closes or reconnects.
How does CONNECTION_ID() relate to SHOW PROCESSLIST?
The number returned by CONNECTION_ID() is the exact same value shown in the Id column of SHOW PROCESSLIST for your session.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.