MySQL CONNECTION_ID() Function

The CONNECTION_ID() function returns the unique connection ID for the current connection to the MySQL server. This ID is useful for identifying the connection in use by a specific query or session.


Syntax

CONNECTION_ID()

Parameters

  • This function does not take any parameters.

Definition and Usage

  • The CONNECTION_ID() function returns a unique identifier (a numeric value) that corresponds to the current session or connection.
  • This value is automatically generated by the MySQL server when a connection is established.

Technical Details

  • Works in: From MySQL 4.0.
  • Return Type: An integer representing the unique connection ID for the current connection.

Example Usage

Example 1: Return the Current Connection ID

SELECT CONNECTION_ID();

This query will return the unique connection ID for the current MySQL session.

Example 2: Using CONNECTION_ID() in a Query

If you're monitoring or debugging, you can use the connection ID to track queries executed by specific sessions:

SELECT CONNECTION_ID(), User(), NOW();

This query returns the connection ID, the current user, and the current timestamp for the session.


Use Cases

  • Connection Tracking: Useful for identifying and monitoring active connections to the database.
  • Session Management: Can be used in logs or debugging to track the actions of specific sessions.

Was this article helpful?