Development

How To Show the Current Database in MySQL

Captain Salem 1 min read

How To Show the Current Database in MySQL

MySQL is one of the most popular, free and open-source relational database management system. MySQL powers a wide range of applications from simple blogs to complex enterprise applications.

However, when working in the MySQL CLI on any MySQL client, you need to switch from one database to another. This can quickly become problematic as you can lose track of which database you are currently in, especially in multi-database environment.

In this tutorial, we will show you the various ways you can use to determine which database is currently active in your MySQL session.

Although this may seem like a simple process, it is entirely crucial as it can prevent you from perform actions on the wrong database.

Prerequisites

Before proceeding with this tutorial, make sure you have the following:

  1. MySQL Server
  2. MySQL Client or MySQL Workbench.
  3. Basic understanding of SQL

Connect to the MySQL Server

The first step is connecting to the MySQL server. You can do this using any client of your choice. For simplicify, we will use the mysql CLI interface.

Run the command:

mysql -u username -p

Replace username with your actual username. For example, to login as the root user, run the command:

mysql -u root -p

Once you run the command above,, you’ll be prompted to enter the password for the specified username.

Select a Database

In MySQL, before you can execute any commands on the target database, you need to select it first. You can do this by running the USEcommand, followed by the name of the database.

The command syntax is as shown:

USE database_name;

Replace database_name with the name of your target database.

For example, to switch to the sakila database, we can run the command:

USE sakila;

Show the Current Database

Once you’ve selected a database, you can check which one is currently in use with the SELECT DATABASE() function.

The syntax is as shown

SELECT DATABASE();

Once you run the command above, MySQL will return the name of the currently selected database.

Conclusion

And that’s it! You can now easily check which database is currently in use in your MySQL session.

Remember, it’s always a good practice to make sure you’re in the right database before running any operations, especially those that modify data or schema. The SELECT DATABASE() function provides an easy way to verify your current database and helps you avoid potential data loss.

Share
Comments
More from Cloudenv

Cloudenv

Developer Tips, Tricks and Tutorials.

Great! You’ve successfully signed up.

Welcome back! You've successfully signed in.

You've successfully subscribed to Cloudenv.

Success! Check your email for magic link to sign-in.

Success! Your billing info has been updated.

Your billing was not updated.