In MySql you will often start by creating and selecting which database to use. You need a database to store data, so this is a logically place to start. In this article, we will learn how to create databases in mysql.
We will be using docker in this article, but feel free to install your database locally instead. Once you have docker installed, create a new file called docker-compose.yml
and add the following.
version: '3'
services:
db:
image: mysql:latest
container_name: db
environment:
MYSQL_ROOT_PASSWORD: root_pass
MYSQL_DATABASE: app_db
MYSQL_USER: db_user
MYSQL_PASSWORD: db_user_pass
ports:
- "6033:3306"
volumes:
- dbdata:/var/lib/mysql
phpmyadmin:
image: phpmyadmin/phpmyadmin
container_name: pma
links:
- db
environment:
PMA_HOST: db
PMA_PORT: 3306
PMA_ARBITRARY: 1
restart: always
ports:
- 8081:80
volumes:
dbdata:
Next, run docker-compose up
.
Now, navigate to http://localhost:8081/
to access phpMyAdmin. Then log in with the username root
and pass root_pass
.
Click the SQL tab and you are ready to go.
To create a database, we can use the CREATE DATABASE
statement. For example, let’s create a database called "sakila" named after the example database we will be using for many tutorial (insert link).
CREATE DATABASE sakila;
Next, in MySql, we must select the database we want to use. We can do this by using the USE
command.
USE sakila;
Now, MySql knows we want to be sending command using the sakila database.
The using sql scripts to import existing schemas, we often want to check if a database exists before we create. We can do this a few ways. First, we can use the SHOW DATABASES
command to list the current databases.
SHOW DATABASES;
The output is as follows:
+--------------------+ | Database | +--------------------+ | sakila| | information_schema | | mysql | | performance_schema | | sys | +--------------------+
Now, if we see the database, we can know to not create it. However, MySQL also has a handy command called IF NOT EXISTS
that we can use when creating a database. If we use this clause, the database will only be created if it does not exists.
CREATE DATABASE IF NOT EXISTS sakila;