CREATE DATABASE
In TiDB, the CREATE DATABASE statement is used to create a new database. The syntax is the same as MySQL.
Syntax
CREATE DATABASE [IF NOT EXISTS] database_name
[DEFAULT] CHARACTER SET charset_name
[DEFAULT] COLLATE collation_name;
Basic Examples
Creating a New Database
CREATE DATABASE mydb;
Creating a Database with IF NOT EXISTS
CREATE DATABASE IF NOT EXISTS mydb;
IF NOT EXISTS prevents an error if the database already exists.
Creating a Database with a Character Set
CREATE DATABASE mydb
CHARACTER SET utf8mb4
COLLATE utf8mb4_bin;
Viewing Databases
-- Show all databases
SHOW DATABASES;
-- Use a specific database
USE mydb;
-- Show the currently active database
SELECT DATABASE();
Dropping a Database
DROP DATABASE IF EXISTS mydb;
Warning: DROP DATABASE permanently removes all tables and data inside it.
Database Configuration
TiDB Default Character Set
-- Check the default character set
SHOW VARIABLES LIKE 'character_set_server';
-- Output: utf8mb4
-- Check the default collation
SHOW VARIABLES LIKE 'collation_server';
-- Output: utf8mb4_bin
Differences from MySQL
| Aspect | MySQL 5.7 | MySQL 8.0 | TiDB |
|---|---|---|---|
| Default charset | latin1 | utf8mb4 | utf8mb4 |
| Default collation | utf8mb4_general_ci | utf8mb4_0900_ai_ci | utf8mb4_bin |
| lower_case_table_names | 0 (Linux) | 0 (Linux) | 2 |
Practical Example
-- Create a database for an e-commerce application
CREATE DATABASE IF NOT EXISTS ecommerce
CHARACTER SET utf8mb4
COLLATE utf8mb4_bin;
USE ecommerce;
-- Verify
SELECT DATABASE(); -- output: ecommerce
SHOW CREATE DATABASE ecommerce;
In the next chapter, we will learn how to create tables in TiDB.