MySQL | DATABASE() and CURRENT_USER() Functions (original) (raw)

Last Updated : 3 Sep, 2024

In **MySQL, certain functions provide crucial information about the current session which can be particularly useful when working with multiple databases or managing user permissions. Two such important functions areDATABASE() and CURRENT_USER().

In this article, We will learn about the **MySQL DATABASE() and CURRENT_USER() Functions with the help of various examples and so on.

**MySQL DATABASE() Function

The**DATABASE()** function in **MySQL returns the name of the current database selected in the session. If no **database is selected, it returns NULL.

**Syntax:

SELECT DATABASE();

**Explanation: The SELECT DATABASE(); query in MySQL is used to retrieve the name of the currently selected database in the session. If no database has been selected the function will return NULL and allowing us to confirm whether we are working within a specific database or not.

Example of **DATABASE() Function

**MySQL query that identifies the current database in use. If a database name **my_database**is selected in the current session, the query should return my_database. If no database has been selected, the query should return NULL.

**Syntax:

SELECT DATABASE();

If the current session is using a database named my_database, the result will be:

my_database

If no database has been selected, the result will be:

NULL

This function is useful when we want to check or confirm which database you are working with, particularly in scripts or applications that interact with multiple databases.

MySQL CURRENT_USER() Function

The CURRENT_USER() function in **MySQL returns the user name and host name combination of the MySQL account that the server used to authenticate the current client session. Essentially, it tells us the MySQL account that is currently being used for our connection.

**Syntax:

SELECT CURRENT_USER();

**Key Points:

Example of CURRENT_USER() Function:

Let us consider the username of MySQL account used by the server to authenticate the current client is 'root' and the hostname is 'localhost'. Therefore to know the username and hostname for the MySQL account used by the server to authenticate the current client, the CURRENT_USER() function can be executed in the following way:

**Output:

'root@localhost'

Conclusion

The DATABASE() and CURRENT_USER() functions in MySQL are essential for obtaining session-related information, such as the current database in use and the authenticated user. These functions can be particularly useful when working with multiple databases or managing user permissions in MySQL.