Select Database

To work with a database in SQL, we need to first select the database we want to work with. After selecting the database, we can perform various operations on it such as creating tables, inserting data, updating data, and deleting data.

The USE DATABASE Statement

The SQL USE DATABASE statement is used to select a database from a list of databases available in the system. Once a database is selected, we can perform various operations on it such as creating tables, inserting data, updating data, and deleting data.

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.

Example

First of all we will create a database using the following SQL CREATE DATABASE query −

CREATEDATABASE testDB;

Now, we can list all the available databases as follws −

SHOWDATABASES;

The output will be displayed as −

Database
master
performance_schema
information_schema
mysql
testDB

Example: Select/Switch Database

Following query is used to select/switch the current database to testDB −

USE testDB;

Output

Database changed

Once we finish switching to the database testDB we can perform operations such as creating a table, and inserting data in that table as shown below −.

CREATETABLE CALENDAR(MONTHS DATENOTNULL);

Now, let us insert some records in the CALENDAR table using SQL INSERT statements as shown in the query below −

INSERTINTO CALENDAR(MONTHS)VALUES('2023-01-01');INSERTINTO CALENDAR(MONTHS)VALUES('2023-02-01');INSERTINTO CALENDAR(MONTHS)VALUES('2023-03-01');INSERTINTO CALENDAR(MONTHS)VALUES('2023-04-01');INSERTINTO CALENDAR(MONTHS)VALUES('2023-12-01');

Let’s verify the operation by listing all the records from CALENDAR table using SQL SELECT statement as shown below −

SELECT*FROM CALENDAR;

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'

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *