RienSQL
LESSON 38 / 62 · Creating and deleting databases

Creating and deleting databases

SQL syntax for creating and dropping databases in MySQL and PostgreSQL: CREATE DATABASE, DROP DATABASE, IF EXISTS, and IF NOT EXISTS.

When writing SQL queries, we actively use tables. The tables themselves are stored within specific databases, which will be discussed in this article.

Database creation

Database creation has the following syntax:

MySQL 8.4

CREATE DATABASE database_name;
database_name
The name of the new database.

Database names usually use letters, numbers, and the characters "_" and "$". The maximum name length is 64 characters.

You can control the creation of the database using the SHOW DATABASES operator.

SHOW DATABASES;
Database
user_table_1
user_table_2
information_schema
mysql
performance_schema
sys

Note that the SHOW DATABASES operator, in addition to user databases, also displays service databases: information_schema, mysql, performance_schema, sys.

Deleting database

Deleting a database is done using the DROP DATABASE operator:

MySQL 8.4

DROP DATABASE database_name;
database_name
The database to delete together with all its tables.

IF EXISTS and IF NOT EXISTS

When creating or deleting a database, an error may occur. For example, the database may already exist or, on the contrary, may not exist yet. In such cases, the IF EXISTS and IF NOT EXISTS constructions are used.

That is, if we want to create a database only on the condition that it does not exist yet, then we use following syntax:

MySQL 8.4

CREATE DATABASE IF NOT EXISTS database_name;

Create the database only if there is no database with this name yet. Otherwise the query does nothing and doesn't fail.

IF NOT EXISTS
Keyword
database_name
The name of the new database.

If we want to delete the database only if it exists, then we use following syntax:

MySQL 8.4

DROP DATABASE IF EXISTS database_name;

Delete the database only if it exists. Otherwise the query does nothing and doesn't fail.

IF EXISTS
Keyword
database_name
The database to delete.

Test yourself

The shop database has tables with data. What happens when you run this query?

DROP DATABASE shop;

There is no shop database on the server. What happens when you run this query?

DROP DATABASE IF EXISTS shop;