Many MySQL and MariaDB statements assume a default schema for the current session, so the same SQL can either work cleanly or fail (or target the wrong objects) depending on which database is selected.

The “current database” is a per-connection setting used when a statement references an unqualified object name, such as SHOW TABLES or SELECT * FROM users. USE <db_name> sets that default for the active session, and SELECT DATABASE() returns the database currently selected.

Database context changes apply only to the current connection and reset after disconnecting, so new sessions start with no selected database unless one is chosen at login. Selecting the wrong database is a common cause of accidental changes in shared environments, so confirming context before running destructive statements (DROP, TRUNCATE) is a sensible habit.

Steps to view and change the current database:

  1. Connect to the server using the MySQL or MariaDB client.
    $ mysql --user=app --host=db.example.net --password
    Enter password:
    
    mysql>

    To select a database at login, add --database=appdb (or --database appdb) to the client command.

  2. Check the current database for the session.
    mysql> SELECT DATABASE();
    +------------+
    | DATABASE() |
    +------------+
    | NULL       |
    +------------+
    1 row in set (0.00 sec)

    NULL means no database has been selected yet for this session.

  3. List databases visible to the current account to identify the schema name.
    mysql> SHOW DATABASES;
    +--------------------+
    | Database           |
    +--------------------+
    | information_schema |
    | appdb              |
    +--------------------+
    2 rows in set (0.00 sec)

    SHOW DATABASES only returns schemas the account can access.

  4. Select a database for the current session.
    mysql> USE appdb;
    Database changed

    Use backticks for names with special characters, for example USE `app-db`;.

  5. Confirm the database change.
    mysql> SELECT DATABASE();
    +------------+
    | DATABASE() |
    +------------+
    | appdb      |
    +------------+
    1 row in set (0.00 sec)
  6. Run a command that relies on the selected database context.
    mysql> SHOW TABLES;
    +-----------------+
    | Tables_in_appdb |
    +-----------------+
    | users           |
    | sessions        |
    +-----------------+
    2 rows in set (0.00 sec)

    Fully qualify objects to avoid relying on session state, for example SELECT COUNT(*) FROM appdb.users;.

Discuss the article:

Comment anonymously. Login not required.