Databases are the backbone of any application, enabling you to store, manage, and retrieve data efficiently. Whether you are setting up a new project or managing an existing one, understanding how to create and select databases is crucial.

In this tutorial, we will walk you through the essential steps of creating and selecting MySQL databases.

Prerequisites

Before we begin, ensure you have MySQL installed on your system. You should also have access to the MySQL command line.

Step 1 – Creating a MySQL Database

1. First, open your terminal or command prompt. If you have MySQL installed, you can access the MySQL command line by typing:

mysql -u root -p

Press Enter and provide your MySQL root password when prompted. You will see the MySQL prompt:

mysql>

2. Use the CREATE DATABASE command followed by the name of the database to create a database. For example, to create a database named test_db, you would type:

CREATE DATABASE test_db;

You should see a message confirming the database has been created:

Query OK, 1 row affected (0.00 sec)

3. To verify that your new database has been created, you can list all databases using the SHOW DATABASES command:

SHOW DATABASES;

The output will include your newly created database:

+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| test_db            |
+--------------------+
5 rows in set (0.00 sec)

Step 2 – Selecting a MySQL Database

1. Once you have created your database, you need to select it before performing any operations like creating tables or inserting data. To select a database, use the USE command followed by the database name. For example, to select the test_db database, you would type:

USE test_db;

You should see a confirmation message:

Database changed

2. To confirm which database is currently selected, you can use the SELECT DATABASE() function:

SELECT DATABASE();

The output will show the name of the selected database:

+------------+
| DATABASE() |
+------------+
| test_db    |
+------------+
1 row in set (0.00 sec)

Conclusion

In this article, we covered the fundamental steps for creating and selecting MySQL databases. You learned how to access the MySQL command line, create a new database, verify its creation, and select it for use. These basic operations are essential for managing your data effectively in MySQL. Try to use MySQL on dedicated server hosting from Atlantic.Net!