MySQL CURRENT_ROLE() Function

The MySQL CURRENT_ROLE() function returns a string representing the currently active roles for the current session, with multiple roles separated by commas.

CURRENT_ROLE() Syntax

Here is the syntax of the MySQL CURRENT_ROLE() function:

CURRENT_ROLE()

Parameters

The MySQL CURRENT_ROLE() function does not require any parameters.

Return value

The CURRENT_ROLE() function returns a UTF8 string containing the currently active role for the current session.

If the current session user does not have any role, this function will returns a string: NONE.

CURRENT_ROLE() Examples

The following example shows how to use the current user information using the CURRENT_ROLE() function.

First, let’s create a user testuser with the following statement:

CREATE USER 'testuser'@'%' IDENTIFIED BY 'testuser123';

Log in to the MySQL server with the user you just created:

mysql --user=testuser --password=testuser123

Use the following statement to view the current role:

SELECT CURRENT_ROLE();
+----------------+
| CURRENT_ROLE() |
+----------------+
| NONE           |
+----------------+

Here, the function returns NONE, it means that there are no roles in the current session.

Then, let’s create two roles and assign both roles to the user testuser:

CREATE ROLE test_role1, test_role2;
GRANT 'test_role1', 'test_role2' TO 'testuser'@'%';
SET DEFAULT ROLE ALL TO 'testuser'@'%';

Log in to mysql again and view the role:

SELECT CURRENT_ROLE();
+-----------------------------------+
| CURRENT_ROLE()                    |
+-----------------------------------+
| `test_role1`@`%`,`test_role2`@`%` |
+-----------------------------------+

Here, the result we expect is returned. The two roles are separated with a comma.

Let’s modify the roles of the following current session user to be test_role1:

SET ROLE 'test_role1';

To view roles for the current session user:

SELECT CURRENT_ROLE();
+------------------+
| CURRENT_ROLE()   |
+------------------+
| `test_role1`@`%` |
+------------------+

Only one character is returned here. Because we used the statement SET ROLE 'test_role1'; to set the role of the current session to test_role1.