How to Create a Database in MySQL: Simple Steps
To create a database in MySQL, use the
CREATE DATABASE database_name; command. This command makes a new empty database where you can store tables and data.Syntax
The basic syntax to create a database in MySQL is:
CREATE DATABASE: This keyword tells MySQL to make a new database.database_name: The name you want to give your new database. It should be unique and follow naming rules.;: The semicolon ends the command.
sql
CREATE DATABASE database_name;Example
This example creates a database named my_shop. After running this, you will have a new empty database called my_shop ready to use.
sql
CREATE DATABASE my_shop;Output
Query OK, 1 row affected (0.01 sec)
Common Pitfalls
Some common mistakes when creating databases in MySQL include:
- Using spaces or special characters in the database name without quotes.
- Trying to create a database that already exists, which causes an error.
- Not having the right permissions to create a database.
To avoid errors when the database might already exist, use CREATE DATABASE IF NOT EXISTS database_name;.
sql
/* Wrong: database name with space without quotes */ CREATE DATABASE my shop; /* Right: use underscore or quotes */ CREATE DATABASE my_shop; -- or CREATE DATABASE `my shop`; /* Avoid error if database exists */ CREATE DATABASE IF NOT EXISTS my_shop;
Output
ERROR 1064 (42000): You have an error in your SQL syntax;
Query OK, 1 row affected (0.01 sec)
Query OK, 1 row affected (0.01 sec)
Quick Reference
| Command | Description |
|---|---|
| CREATE DATABASE database_name; | Creates a new database with the given name. |
| CREATE DATABASE IF NOT EXISTS database_name; | Creates a database only if it does not already exist. |
| DROP DATABASE database_name; | Deletes the database and all its data. |
| SHOW DATABASES; | Lists all databases on the MySQL server. |
Key Takeaways
Use the CREATE DATABASE command followed by your database name to create a new database.
Avoid spaces or special characters in database names unless enclosed in backticks.
Use IF NOT EXISTS to prevent errors if the database already exists.
Ensure you have proper permissions to create databases on the MySQL server.
Check your created databases with SHOW DATABASES command.