SQL Select Database
The USE DATABASE statement allows users to select the database on which they want to work. Users can select a specific database to edit/work from a list of databases.
To use a database and create tables, we need to first select the database, and here we will learn how to select a database in SQL.
Syntax to Select a Database in SQL
The syntax to select a database in SQL is:
USE DATABASE_NAME;
SQL Select Database Example
Let’s look at an example of how to select a database in SQL.
First, let’s create a database using CREATE DATABASE statement.
Query
CREATE DATABASE w3wiki;
Now we will verify whether the new database that we have just created has been successfully added to our system or not. We use the SHOW DATABASES command and it will return a list of databases to our system.
Query
SHOW DATABASES;
Output
Select Database
Now to select the database, we use the USE DATABASE command. So now we will select our database w3wiki.
Query
USE w3wiki;
Output
After this, we can create table in this database, and do our work.
Create Table Without Selecting a Database
Now let’s take a case where we haven’t selected the database but we are creating a new table. In this case, we will get an error from MYSQL stating ‘No database selected’ meaning that as no database was selected MYSQL cannot figure out in which database we are creating this table.
Conclusion
In SQL, always select the database before starting to work with the database. To select a database in SQL, use the USE database command.
After creating a database we need to select that database first to tell SQL which database we are working on. If we directly start creating tables then SQL will give an error stating that ‘No Database Selected‘.
SQL Select Database – FAQs
Why do we need to Select a Database?
We need to Select a Database to state SQL about the database we will be using for storing the data.
What if we don’t select the database?
In case you don’t select the database and start working with it, MYSQL we give you an error ‘No database selected’.
How to select a database in MYSQL?
To select a database in MYSQL we take help of USE command.