How to Select a Database in MySQL

08/03/2021

Contents

In this article, you will learn how to select a database in MySQL.

Selecting a database in MySQL

When working with MySQL, it’s essential to select the database you want to work with before running any SQL commands. Here’s a step-by-step guide on how to select a database in MySQL:

Access the MySQL command line

The first step is to access the MySQL command line, which allows you to execute SQL commands and interact with the database. You can access the command line by opening a terminal or command prompt and entering the following command:

mysql -u username -p

Replace “username” with the username you use to access MySQL. You will be prompted to enter your password.

List the databases

Once you’re in the MySQL command line, you can list all the databases on the server by entering the following command:

SHOW DATABASES;

This command will display a list of all the databases on the MySQL server.

Select the database

To select the database you want to work with, enter the following command:

USE database_name;

Replace “database_name” with the name of the database you want to select. This command will set the active database to the one you specified.

Verify the selected database

To verify that you have selected the correct database, you can enter the following command:

SELECT DATABASE();

This command will return the name of the currently selected database.

Here’s an example of how to select the “customers” database:

mysql -u username -p
SHOW DATABASES;
USE customers;
SELECT DATABASE();

After running these commands, you should see the “customers” database selected as the active database.