Why Select Database or USE Database?

System may contain more than one database. User or a developer should select the database before going to perform their operations or trigger queries.

USE Statement fulfils this requirement.

How to Select database or USE Database?

USE statement is used to select the database before performing operations. Once the database is selected, it acts as a default database until the usage of USE statement with other database name or end of session.

The syntax for selecting the database is –

USE database_name;
  • database_name - Specifies the name of the database that is going to use.

Note:- There is no special privileges are required to execute USE statement. A normal USE with select privileges is sufficient.

Example-

Consider we are going to select the existing database named emptempdb. The code for using the database is -

USE emptempdb; 

After executing the above query, emptempdb sets as a default database and the further operations will perform on emptempdb database.


Verify the Database

To check what are all the databases available before selecting the database, we can use the below statement –

SHOW DATABASES;


Example-

Consider above example, we can check the database list by using the below query -

SHOW DATABASES; 

Once the above query executed, it displays the results like below -

+-------------------+
| Database          |
+-------------------+
|emptestdb          |
| test              |
+-------------------+
2 rows in set (0.00 sec)

What happen if try to use the nonexisting database?

When trying to select a database that does not exist, system throws the error:"Can't use database 'database_name'; database doesn't exist".