Hive Use Database

When you work with Apache Hive, you usually deal with multiple databases, each containing different sets of tables. To run queries on a particular set of tables, you need to first tell Hive which database you want to work with. This is done using the USE statement.

What is the USE database?

The USE command in Hive is used to select or switch to a specific database. Once you set the database using this command:

  • Any tables you create or query after that will belong to the selected database.
  • You don’t have to keep typing the database name every time.

Why do we use the USE Database?

There are many reasons why using the USE command in Hive is helpful:

  • When you have multiple databases (like sales, hr, finance), you can easily switch between them.
  • It helps you avoid typing full database names every time you write a query.
  • It keeps your queries clean and focused on the right set of tables.
  • It is useful when running scripts or batch jobs where everything should happen inside the same database.
Syntax -
USE databse_name;
Examples -

Scenario1: Assume you have a database called sales_db and you want to work with it.

USE sales_db;

From this point onward, any CREATE TABLE, SELECT, DROP TABLE commands will apply inside sales_db.

SHOW TABLES;

This will now show the tables inside sales_db only.

Scenario2: Switching to Another Database: If you want to switch to another database called hr_db, just run:

USE hr_db;

Now you are inside hr_db and all your work will happen there.

Scenario3: Without Using USE (Fully Qualified Names): If you don’t use the USE command, you have to type the database name every time like this:

SELECT * FROM sales_db.orders;

This works fine, but using the USE command saves you from repeating the database name in every query.