Select Database :
The USE statement is used to select a particular database in SQL.
Syntax
Following is the syntax of the USE DATABASE statement in SQL -
USE DatabaseName;
Here, the DatabaseName is the name of the database that we want to select. The database name is always unique within the RDBMS.
By executing this SQL statement, you switch the current database context to sample_database. Subsequent queries will operate within this selected database until you change the context by selecting a different database or disconnecting.
Remember, selecting the right database is essential for running queries, accessing tables, and performing operations within a specific database environment. It helps in organizing and managing data efficiently.
If you ever need to switch to a different database, you can simply use the USE statement with the desired database name.
Example
First of all we will create a database using the following SQL CREATE DATABASE query -
CREATE DATABASE sample_DB;
Now, we can list all the available databases as follows -
SHOW DATABASES;
The output will be displayed as -
Database |
---|
master |
performance_schema |
information_schema |
mysql |
sample_DB |
Example: Select/Switch Database
Following query is used to select/switch the current database to Sample_DB -
USE Sample_DB;
Output
Database changed
Once we finish switching to the database Sample_DB we can perform operations such as creating a table, and inserting data in that table as shown below -.
CREATE TABLE Order(MONTHS DATE NOT NULL);
Now, let us insert some records in the ORDER table using SQL INSERT statements as shown in the query below -
INSERT INTO Order(MONTHS) VALUES('2023-01-01'); INSERT INTO Order(MONTHS) VALUES('2023-02-01'); INSERT INTO Order(MONTHS) VALUES('2023-03-01'); INSERT INTO Order(MONTHS) VALUES('2023-04-01'); INSERT INTO Order(MONTHS) VALUES('2023-12-01');
Let's verify the operation by listing all the records from ORDER table using SQL SELECT statement as shown below -
SELECT * FROM ORDER;
Output
The output will be displayed as -
MONTHS |
---|
2023-01-01 |
2023-02-01 |
2023-03-01 |
2023-04-01 |
2023-12-01 |
Selecting a Non Existing Database
An attempt to select a non-existent database will result in an error. In the following query we are trying to switch to the database which does not exist -
Example
USE unknownDatabase;
Output
On executing the above query, the output will be displayed as -
ERROR 1049 (42000): Unknown database 'unknownDatabase'