Skip to content

SQL - Select Database

SQL: Selecting a Database with the USE Statement

Section titled “SQL: Selecting a Database with the USE Statement”

A single database server (RDBMS) can manage multiple, separate databases. Each database is a self-contained collection of tables, views, and other objects. Before you can perform operations like creating a table or querying data, you must first tell the server which database you intend to work with. This is known as setting the ‘current database’ for your session.

The USE statement is a simple command for selecting a database to be the current one for your interactive session. Once you execute USE, all subsequent SQL commands you run (like SELECT, INSERT, CREATE TABLE) will be executed against that chosen database until you select a different one or end your session.

USE database_name;

Here, database_name must be the name of an existing database on the server.

Note: The USE statement is part of the SQL standard but is primarily used in command-line clients and GUI tools (like DBeaver, MySQL Workbench, or SQL Server Management Studio). Its implementation can vary. For example, some systems might not have a direct USE equivalent and require other methods to switch context.

How Database Selection Works in Applications

Section titled “How Database Selection Works in Applications”

In application code (e.g., using Python, Java, Node.js, or Go), you typically do not execute a USE statement. Instead, the target database is specified directly within the connection string when your application establishes its connection to the database server. This ensures that every query from that connection is correctly routed to the intended database from the start.

A typical connection string might look something like this:

postgresql://username:password@hostname:port/database_name

Let’s walk through a typical workflow in a SQL command-line client.

  1. First, let’s create a new database to work with.
create database company_db;
  1. Now, select this new database to make it the active context.
use company_db;
Database changed
  1. With company_db selected, we can now create a table within it.
create table employees (
id INT primary key,
name VARCHAR(100) not null
);
  1. We can insert data and query it, and all operations will correctly target the employees table inside company_db.
insert into employees (id, name) values (1, 'Alice');
select * from employees;
idname
1Alice

If you try to USE a database that does not exist on the server, SQL will return an error.

use non_existent_db;
ERROR 1049 (42000): Unknown database 'non_existent_db'