How to Create a Database in MySQL

08/03/2021

Contents

In this article, you will learn how to create a database in MySQL.

Creating a database in MySQL

Creating a database is one of the basic tasks when working with MySQL. A database is a collection of related tables and data, and it’s used to organize and manage information. Here’s a step-by-step guide on how to create a database in MySQL:

Access the MySQL command line

The first step is to access the MySQL command line, which allows you to execute SQL commands and interact with the database. You can access the command line by opening a terminal or command prompt and entering the following command:

mysql -u username -p

Replace “username” with the username you use to access MySQL. You will be prompted to enter your password.

Create the database

Once you’re in the MySQL command line, you can create a database by entering the following command:

CREATE DATABASE my_database;

Replace “my_database” with the name you want to give your database. This command will create a new database with the specified name.

Check that the database was created

You can check that the database was created by entering the following command:

SHOW DATABASES;

This command will display a list of all the databases on the MySQL server. Make sure that your new database is included in the list.

Switch to the new database

To start using your new database, you need to switch to it by entering the following command:

USE my_database;

Replace “my_database” with the name of your database. This command will set your active database to the one you just created.

Create tables (optional)

Once you have created your database and switched to it, you can create tables to store data. Tables are created using the “CREATE TABLE” command, and they define the columns and data types that the table will contain.

Here’s an example of how to create a simple “users” table with two columns:

CREATE TABLE users (
  id INT(11) NOT NULL AUTO_INCREMENT,
  name VARCHAR(50) NOT NULL,
  PRIMARY KEY (id)
);

This command creates a table called “users” with two columns: “id” and “name”. The “id” column is an integer and will auto-increment for each new record. The “name” column is a string with a maximum length of 50 characters. The “PRIMARY KEY” statement specifies that the “id” column is the primary key for the table.