00:00

MySQL Select Database

Last updated:

A MySQL server usually holds several databases, and a table name like students only makes sense once MySQL knows which database you mean. Selecting a database with the USE statement sets the default for your session, so you don't have to type the database name before every table.

1. The Problem: No Database Selected

Right after connecting, no database is selected. A query on a plain table name fails:

query.sql
SELECT DATABASE() AS current_db;

Result: 1 row

current_db
NULL
query.sql
SELECT * FROM students;
Output
ERROR 1046 (3D000): No database selected

2. Selecting a Database with USE

USE sets the default database for a sessionA session points at the school database after USE school. Unqualified table names such as students are looked up in school. A qualified name such as shop.orders reaches another database directly.Your sessionafter USE schoolschool (default)students, coursesshoporders, productsstudentsshop.ordersunqualified namesuse the default DBqualified namesgo anywhere
Figure 1: USE picks the database that plain table names refer to; db.table works regardless.
syntax.sql
USE database_name;
use.sql
USE school;
SELECT DATABASE() AS current_db;
SELECT * FROM students WHERE class = '8A';

Result: 1 row

current_db
school

Result: 2 rows

idnameclass
1Riya8A
3Zoya8A
  • USE affects only your session (connection); other users are unaffected.
  • It stays in effect until you run another USE or disconnect.
  • The semicolon is optional for USE in the mysql client, but it is good practice.

3. Switching Between Databases

switch.sql
USE shop;
SELECT DATABASE() AS now_using, COUNT(*) AS orders FROM orders;

USE school;
SELECT DATABASE() AS now_using, COUNT(*) AS students FROM students;

Result: 1 row

now_usingorders
shop2

Result: 1 row

now_usingstudents
school3

4. Working Across Databases with Qualified Names

You don't have to switch at all if you write database.table. This works from any current database and even lets one query use tables from two databases:

qualified.sql
USE school;
SELECT s.name, o.item, o.qty
FROM school.students s
JOIN shop.orders o ON o.id = s.id;

Result: 2 rows

nameitemqty
RiyaGeometry box2
KabirNotebook10
Qualified names are clearer in scripts and stored procedures, because they don't depend on whichever database happened to be selected.

5. Errors You May See

query.sql
USE schol;   -- typo
Output
ERROR 1049 (42000): Unknown database 'schol'
ErrorMeaningFix
1046 (3D000): No database selectedPlain table name used before USERun USE db; or write db.table
1049 (42000): Unknown databaseThe database doesn't exist (or a typo)Check SHOW DATABASES
1044 (42000): Access denied … to databaseNo privileges on that databaseAsk for a GRANT

6. Choosing the Database When You Connect

Name the database on the command line to select it immediately:

Terminal
mysql -u root -p school          # connect and USE school
mysql -u root -p -D school       # same thing with -D
mysql -u root -p -e "SELECT COUNT(*) FROM shop.orders"   # one-off query, no USE needed

Inside the client, the status (or \s) command shows the current database next to Current database:.

7. Selecting the Database from Java

In JDBC, put the database name in the connection URL. You can also switch later with setCatalog():

SelectDatabaseDemo.java
import java.sql.*;

public class SelectDatabaseDemo {
    public static void main(String[] args) throws SQLException {
        String url = "jdbc:mysql://localhost:3306/school";     // 'school' is selected on connect
        try (Connection con = DriverManager.getConnection(url, "root", "your-password")) {
            System.out.println("Using: " + con.getCatalog());   // school

            con.setCatalog("shop");                             // like USE shop
            try (Statement st = con.createStatement();
                 ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM orders")) {
                rs.next();
                System.out.println("Orders: " + rs.getInt(1));
            }
        }
    }
}
In Spring Boot the database is part of spring.datasource.url, for example jdbc:mysql://localhost:3306/school.

8. Practice Exercises

Exercise 1: Without running USE, count the students in class 8A.
solution.sql
SELECT COUNT(*) AS in_8a FROM school.students WHERE class = '8A';

Result: 1 row

in_8a
2
Exercise 2: Select the shop database and list orders with a quantity above 5.
solution.sql
USE shop;
SELECT item, qty FROM orders WHERE qty > 5;

Result: 1 row

itemqty
Notebook10

9. Summary

  • USE db_name; sets the default database for the current session.
  • SELECT DATABASE(); shows which database is selected (NULL if none).
  • database.table works without USE and allows cross-database queries.
  • Pick a database on connect with mysql -u user -p db_name or in the JDBC URL.