How to Use Database in MySQL (Step-by-Step Guide)

Introduction

When working in MySQL, you may have multiple databases on your server. For example:

  • SchoolDB

  • LibraryDB

  • ShopDB

Before you create tables, insert data, or run queries, you must tell MySQL which database you want to work with.
This is done using the USE command.

Think of it like choosing a folder on your computer before saving files inside it.

Syntax of USE Command

USE database_name;

database_name → Name of the database you want to work with.

Example 1: Switch to a Database

USE SchoolDB;

 Now all commands (like creating tables or inserting data) will happen inside SchoolDB.

Example 2: Show All Databases Before Using One

SHOW DATABASES;

+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| SchoolDB           |
| LibraryDB          |
+--------------------+

If you want to work inside LibraryDB:

 
USE LibraryDB;

Example 3: Create a Table After Selecting Database

USE SchoolDB;

CREATE TABLE Students (
    student_id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    age INT,
    grade VARCHAR(10)
);

Since we used USE SchoolDB;, the Students table will be created inside SchoolDB.

Example 4: Error Without Using Database

If you forget to use a database and try creating a table:

CREATE TABLE Teachers (
    teacher_id INT PRIMARY KEY,
    name VARCHAR(100)
);

You may get an error:

ERROR 1046 (3D000): No database selected

 Always run USE database_name; first.

Best Practices

  •  Always double-check which database is active with:   SELECT DATABASE();

  •  Use clear database names (e.g., school_db, shop_db).

  •  If you frequently switch databases, always confirm before running UPDATE/DELETE commands (to avoid deleting data from the wrong database).

  •  In scripts, include USE db_name; at the beginning for clarity.

Quick Recap (Cheat Sheet)

-- Show all databases
SHOW DATABASES;

-- Use a database
USE SchoolDB;

-- Confirm active database
SELECT DATABASE();

-- Now create a table inside selected database
CREATE TABLE Students (
    student_id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    age INT,
    grade VARCHAR(10)
);