Understanding the PS_CURRENT_THREAD_ID() Function in MySQL

In MySQL, we can use the PS_CURRENT_THREAD_ID() function to get the Performance Schema thread ID assigned to the current connection.

The PS_CURRENT_THREAD_ID() function was added in MySQL 8.0.16, and it does the same thing as PS_THREAD_ID(CONNECTION_ID()).

Syntax

The syntax goes like this:

PS_CURRENT_THREAD_ID()

So no arguments are required or accepted.

Example

Here’s an example to demonstrate:

SELECT PS_CURRENT_THREAD_ID();

Result:

137

This tells us that the current connection has a thread ID of 137.

We can check the performance_schema.threads table for the actual thread:

SELECT
    thread_id,
    name,
    processlist_id,
    processlist_user,
    processlist_host
FROM performance_schema.threads
WHERE thread_id = 137;

Result:

+-----------+---------------------------+----------------+------------------+------------------+
| thread_id | name                      | processlist_id | processlist_user | processlist_host |
+-----------+---------------------------+----------------+------------------+------------------+
|       137 | thread/sql/one_connection |             82 | root             | localhost        |
+-----------+---------------------------+----------------+------------------+------------------+

An Alternative

The PS_CURRENT_THREAD_ID() function does the same thing as the following code:

SELECT PS_THREAD_ID( CONNECTION_ID() );

Result:

137

The PS_THREAD_ID() returns the thread ID for a given connection ID. In this case, I passed the CONNECTION_ID() function, which returns the connection ID of the current connection.