DDL - MySQL (DATABASE)
Use to define database, tables, index, ...
Shows all database (SHOW)
Syntax
sql
SHOW DATABASES;Usage
cmd
mysql> SHOW DATABASES;Output:
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sakila |
| sys |
| world |
+--------------------+
6 rows in set (0.06 sec)Create a Database (CREATE)
Syntax
sql
CREATE DATABASE IF NOT EXISTS <db_name>;IF NOT EXISTScan safely create a database, as it will only create the database if it's not exist.- If we re-create an existed database without
IF NOT EXISTS, we will geterrormessage.
Example Usage
cmd
mysql> CREATE DATABASE IF NOT EXISTS testing1;Output:
Query OK, 1 row affected (0.01 sec)Validate if database is created
cmd
mysql> show databases;Output:
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sakila |
| sys |
| testing1 |
| world |
+--------------------+
7 rows in set (0.00 sec)INFO
Database testing1 has been created.
Delete (Drop) a database (DROP)
Syntax
sql
DROP DATABASE IF EXISTS <db_name>;IF EXISTScan safely drop a database, as it only run drop database operation if the database is existed.- If we try
drop an non-exists databasewithoutIF EXISTS, we will geterrormessage.
Example Usage
cmd
mysql> DROP DATABASE IF EXISTS testing1;Output:
Query OK, 0 rows affected (0.01 sec)Validate if database is dropped
cmd
mysql> show databases;Output:
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sakila |
| sys |
| world |
+--------------------+
6 rows in set (0.00 sec)INFO
Database testing1 has been dropped (removed/deleted).
Use a Database (USE)
Syntax
sql
USE <db_name>;Usage
- Create a
testdatabase.
sql
CREATE DATABASE IF NOT EXISTS test;- Use
testdatabase
cmd
mysql> USE test;Output:
Database changedSelect Database (SELECT)
- We using
select database();when weforgetwhat current database has beenusenow.
Syntax
sql
SELECT DATABASE();Usage
- Continue to the step we
use test;.
cmd
mysql> select database();Output:
+------------+
| database() |
+------------+
| test |
+------------+
1 row in set (0.00 sec)