0
0
MysqlHow-ToBeginner · 3 min read

How to Use Database in MySQL: Syntax and Examples

In MySQL, you use the USE database_name; command to select a database to work with. This tells MySQL to run your queries on that specific database until you change it or disconnect.
📐

Syntax

The basic syntax to select a database in MySQL is:

  • USE database_name;: This command sets the current database to database_name.
  • After this, all your queries will run on the selected database unless you change it.
sql
USE database_name;
💻

Example

This example shows how to select a database named shop and then list all tables inside it.

sql
USE shop;
SHOW TABLES;
Output
Tables_in_shop products customers orders
⚠️

Common Pitfalls

Common mistakes when using databases in MySQL include:

  • Trying to run queries without selecting a database first, which causes errors.
  • Using the wrong database name or misspelling it.
  • Not ending the USE command with a semicolon.

Always check that the database exists before using it.

sql
/* Wrong way: missing USE command */
SELECT * FROM products;

/* Right way: select database first */
USE shop;
SELECT * FROM products;
📊

Quick Reference

Here is a quick summary of commands related to using databases in MySQL:

CommandDescription
USE database_name;Selects the database to work with
SHOW DATABASES;Lists all databases on the server
SHOW TABLES;Lists all tables in the current database
CREATE DATABASE database_name;Creates a new database
DROP DATABASE database_name;Deletes a database permanently

Key Takeaways

Use USE database_name; to select the database before running queries.
Always end MySQL commands with a semicolon ;.
Check that the database exists to avoid errors.
Use SHOW DATABASES; to see available databases.
Use SHOW TABLES; to list tables in the selected database.