Introduction
In this chapter, we'll learn how to create a database in MySQL using the command line. Creating a database is the first step in organizing and storing your data. Let's dive in and see how to do it.
Creating a Database
To create a new database, we use the CREATE DATABASE
statement. This command sets up a new database with the name you choose.
Syntax
CREATE DATABASE database_name;
database_name
: The unique name you want to give your database.
Example
CREATE DATABASE mydatabase;
This example creates a new database called mydatabase
.
Using the New Database
After creating a database, we need to select it for use. We do this with the USE
statement.
Syntax
USE database_name;
Example
USE mydatabase;
This command selects the mydatabase
database so we can start working with it.
Full Example
Let's walk through a full example where we create a database and then use it to create a table.
- Create the Database:
CREATE DATABASE company;
- Use the Database:
USE company;
- Create a Table:
CREATE TABLE employees (
id INT PRIMARY KEY AUTO_INCREMENT,
first_name VARCHAR(50),
last_name VARCHAR(50),
email VARCHAR(100)
);
Full Example Script
Here's a complete script that creates a database and a table within it:
CREATE DATABASE company;
USE company;
CREATE TABLE employees (
id INT PRIMARY KEY AUTO_INCREMENT,
first_name VARCHAR(50),
last_name VARCHAR(50),
email VARCHAR(100)
);
Checking the Database
To check if our database was created, we can list all databases on the server using the SHOW DATABASES
command.
Example
SHOW DATABASES;
Output
+--------------------+
| Database |
+--------------------+
| information_schema |
| company |
| mysql |
| performance_schema |
| sys |
+--------------------+
Conclusion
Creating a database is a key step in using MySQL to manage your data. In the next chapter, we'll learn how to delete the existing database.
Comments
Post a Comment
Leave Comment