← Back to MySQL Course | Chapter 2: Databases & Tables | Lesson 3 of 7

USE Database

Selecting a Database

USE followed by a database name sets that database as the active context for your current session, so every unqualified table reference afterward resolves inside it automatically. This means you no longer need to prefix every table name with the database name in subsequent queries during that session.

Example: Selecting a Database

sql
USE shop;
SELECT * FROM products;

⚠️ This is MySQL-specific syntax. It cannot run in the browser editor. Practice this on your local MySQL installation.

Checking the Selected Database

Running SELECT DATABASE() returns the name of whichever database is currently active, which is a quick way to confirm you're about to run a destructive query against the right target.

Example: Checking the Selected Database

sql
SELECT DATABASE();

⚠️ This is MySQL-specific syntax. It cannot run in the browser editor. Practice this on your local MySQL installation.

Switching Databases

You can call USE again at any point in a session to switch to a different database entirely, without needing to close and reopen your connection. This is especially common in scripts or admin tools that need to operate across several databases in sequence.

Example: Switching Databases

sql
USE shop;
USE reporting;

⚠️ This is MySQL-specific syntax. It cannot run in the browser editor. Practice this on your local MySQL installation.

Querying Tables Without Selecting

Prefixing a table name with database_name.table_name lets you query across databases without switching context, which is handy for one-off joins between separate schemas on the same server.

Example: Querying Tables Without Selecting

sql
SELECT * FROM shop.products;

Managing the Active Session

A fresh connection often starts with no database selected at all, so running a bare query before calling USE can fail with a 'no database selected' error — always confirm your context first.

Example: Managing the Active Session

sql
-- A fresh connection has no database selected; a bare query first can fail
USE shop;
SELECT * FROM products;

⚠️ This is MySQL-specific syntax. It cannot run in the browser editor. Practice this on your local MySQL installation.

🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.