The DATABASE() function returns the name of the currently selected (default) database in the MySQL session.
If there is no database selected (i.e., no database has been chosen using the USE statement), this function will return NULL or an empty string.
Syntax
DATABASE()
Definition and Usage
- The
DATABASE()function is used to retrieve the name of the database that is currently selected in the session. - If no database is selected, it returns
NULLor an empty string. - This function is helpful to check the active database in a session or query.
Return Value
- If a database is selected, it returns the database name as a string.
- If no database is selected, it returns
NULLor an empty string.
Technical Details
- Works in: From MySQL 4.0
Examples
Example 1: Get the Current Database
If you have selected a database using the USE statement, DATABASE() will return the name of that database:
USE my_database;
SELECT DATABASE();
Example Output:
'my_database'
Example 2: No Database Selected
If no database is selected, DATABASE() will return NULL or an empty string:
SELECT DATABASE();
Example Output:
NULL
Usage Notes
- It's often used in conjunction with conditional queries or for debugging to confirm which database is currently in use.