Lesson

MySQL DATABASE() Function

10 min reading
Free Course

MySQL DATABASE() Function

The MySQL DATABASE() function returns the name of the current default (selected) database in utf8mb3/utf8mb4 string format. Database administrators and migration scripts call it to verify they are connected to the right schema before altering tables or inspecting INFORMATION_SCHEMA.

Syntax

DATABASE()
-- Synonym:
SCHEMA()
  • Takes zero arguments. Calling DATABASE(anything) raises a syntax error.

If you connected to MySQL without specifying a database and have not run a USE db_name; command yet, DATABASE() returns NULL!

Practical Example

Before running destructive maintenance or querying metadata on demo_orders, verify the active schema name and inspect table metadata in INFORMATION_SCHEMA.

SELECT
    DATABASE() AS current_database,
    TABLE_NAME,
    TABLE_ROWS
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = DATABASE()
  AND TABLE_NAME IN ('demo_orders', 'demo_customers');
current_database TABLE_NAME TABLE_ROWS
koder_demo demo_customers 120
koder_demo demo_orders 450

Common Mistakes & NULL Behavior

  • NULL when no database is selected: Unlike VERSION() or USER(), DATABASE() can return NULL! That happens whenever a client connects without a default database and has not executed USE schema_name;.
  • Filtering INFORMATION_SCHEMA with NULL: Writing WHERE TABLE_SCHEMA = DATABASE() returns zero rows if no database is selected because TABLE_SCHEMA = NULL is always unknown.
  • Stored routines use the routine's schema: Inside a stored function or procedure, DATABASE() returns the schema where the routine is defined, which may differ from the caller's selected USE database.
  • Passing arguments fails: DATABASE() takes zero parameters; passing a table name or NULL triggers an invalid parameter count error.

Frequently Asked Questions

Why did MySQL DATABASE() return NULL?

Your connection has no default database selected yet. Run USE your_database; or specify the database name in your connection string.

What is the difference between DATABASE() and SCHEMA() in MySQL?

In MySQL, SCHEMA() is an exact synonym for DATABASE(). Both return the same active database name or NULL.

Does DATABASE() change when I query another database with db2.table?

No. Querying other_db.demo_orders using a qualified table name does not change the active default database returned by DATABASE().

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum