MySQL DDL Statements: A Complete Guide to Database and Table Operations

    This guide covers the core MySQL DDL (Data Definition Language) statements for working with database and table structures. It explains how DDL differs from DML, the shared traits of DDL commands, and the four actions applied at both the database and table levels: create, inspect, modify, and drop. You will find practical SQL examples for creating databases with explicit character sets, inspecting and deleting databases, switching the active schema, creating and altering tables, and clearing or dropping tables, along with key design and safety recommendations for production environments.

    In relational database learning and day-to-day engineering, DDL (Data Definition Language) is the first hurdle you cannot avoid. Unlike DML, which handles inserting, updating, deleting, and querying data, DDL operates on the structure itself: databases, tables, columns, indexes, and constraints. It determines how data is organized and directly affects query performance and data consistency. Put simply, DML decides how data flows, while DDL decides what kind of container holds it.

    MySQL’s DDL system is highly consistent in its logic. For both databases and tables, the actions are the same four: create, inspect, modify, and drop. Only the level at which they apply differs. Once you understand this correspondence, the amount you need to memorize drops significantly.

    1. The Overall DDL Framework

    DDL statements in MySQL share three common traits:

    • Core verbs are CREATE, ALTER, DROP, and TRUNCATE, paired with SHOW statements for inspecting structure;
    • After execution, autocommit takes effect, and most DDL statements implicitly commit the transaction, so they cannot be rolled back as easily as DML;
    • The granularity is object-level: a single statement affects an entire database or table, not a handful of rows.

    So the first principle of DDL is not “write it correctly,” but “think through the consequences before you write it.”

    2. Database-Level DDL Operations

    2.1 Creating a Database

    The most basic form creates a database by name and raises an error if one with the same name already exists:

    1. CREATE DATABASE demo_db;

    Engineering scripts favor an idempotent form to avoid interruptions on repeated runs:

    1. CREATE DATABASE IF NOT EXISTS bigdata_db;

    Declaring the character set and collation explicitly at creation time is a key step in avoiding garbled Chinese text:

    1. CREATE DATABASE bigdata_db
    2. DEFAULT CHARACTER SET utf8mb4
    3. DEFAULT COLLATE utf8mb4_general_ci;

    It is recommended to standardize on utf8mb4 rather than the older utf8 family, because the former is a complete multibyte implementation that covers four-byte characters such as emoji. Once the character set is set at the database level, tables and columns that do not specify one explicitly will inherit it. It is a “configure once, benefit everywhere” decision.

    2.2 Inspecting Databases

    List the databases that exist in the instance:

    1. SHOW DATABASES;

    View the full definition of a database, which outputs attributes such as the creation statement, character set, and collation:

    1. SHOW CREATE DATABASE bigdata_db;

    The value of this statement is leaving a structural trace: when you need to replicate a test environment’s structure to a new environment, you can copy the output directly, which is more reliable than writing it by hand from memory.

    2.3 Dropping a Database

    1. DROP DATABASE IF EXISTS demo_db;

    This is a typical irreversible, high-risk operation. The database and all its tables and data are permanently removed, and permission grants may be invalidated as well. In production, this kind of action is usually constrained by both the permission system and a change-approval process, and ordinary accounts should not be granted this privilege at all. The necessary steps before executing it are: confirm the database name spelling, confirm a backup exists, and confirm no business connection is actively using the database.

    2.4 Switching to and Locating the Current Database

    1. USE bigdata_db;
    2. SELECT DATABASE();

    Beginners often overlook the need to switch databases. Statements such as table creation and queries, if not qualified with a database name, rely on the “current database” to determine the target. It is like two classes each having a student with the same name: you must say which class you are calling roll in, otherwise the target is ambiguous. A newly established session has no current database by default, so any unqualified table operation will fail. Putting a USE statement at the top of a script is a good habit. You can also use the fully qualified “database_name.table_name” form directly in a statement, so the script does not depend on session state.

    3. Table-Level DDL Operations

    3.1 Creating a Table

    The basic syntax structure is:

    1. CREATE TABLE [IF NOT EXISTS] table_name (
    2. column1 type(length) [constraint],
    3. column2 type(length) [constraint],
    4. ...
    5. );

    A relatively complete example:

    1. CREATE TABLE IF NOT EXISTS student (
    2. id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'Primary key',
    3. name VARCHAR(64) NOT NULL COMMENT 'Name',
    4. class_id INT NOT NULL COMMENT 'Class ID',
    5. score DECIMAL(5,2) DEFAULT NULL COMMENT 'Score',
    6. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    7. PRIMARY KEY (id),
    8. KEY idx_class (class_id)
    9. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Student information';

    Several design points are worth emphasizing: the primary key should preferably be an auto-increment or ordered integer with no business meaning, avoiding mutable fields such as names or phone numbers; precise numeric values such as amounts and ratings should use DECIMAL rather than floating-point types; every column should have a comment, and the table itself should have one too, which is the lowest-cost investment for future maintenance; declare the storage engine and character set explicitly rather than relying on defaults.

    3.2 Inspecting Tables

    List all tables in the current database:

    1. SHOW TABLES;

    View a single table’s structure, which outputs column names, types, nullability, default values, indexes, and comments:

    1. DESC student;
    2. -- or
    3. SHOW CREATE TABLE student;

    The difference is that the former is convenient for quickly browsing the column layout, while the latter provides a complete, reusable CREATE TABLE statement including index and engine information, making it better suited for structural migration and version comparison.

    3.3 Modifying Table Structure

    ALTER is the most frequently used and most caution-demanding verb in DDL. Common scenarios include:

    1. -- Add a column
    2. ALTER TABLE student ADD COLUMN phone VARCHAR(20) NULL COMMENT 'Contact phone';
    3. -- Modify a column's type and constraint
    4. ALTER TABLE student MODIFY COLUMN score DECIMAL(6,2) DEFAULT NULL;
    5. -- Rename a column
    6. ALTER TABLE student CHANGE COLUMN phone mobile VARCHAR(20) NULL;
    7. -- Add an index
    8. ALTER TABLE student ADD INDEX idx_name (name);
    9. -- Drop a column
    10. ALTER TABLE student DROP COLUMN mobile;

    Be aware that some ALTER operations hold a metadata lock for a long time on large tables and may even trigger a full table rebuild, blocking business traffic. So production changes are usually scheduled during off-peak hours and carried out with online change schemes or platform-based database change capabilities to reduce impact. Keeping the original structure definition before a change is the prerequisite for rollback.

    3.4 Dropping and Truncating Tables

    1. DROP TABLE IF EXISTS tmp_table;
    2. TRUNCATE TABLE student;

    The two have completely different semantics: DROP removes the table structure itself, while TRUNCATE keeps the structure, clears all data, and resets the auto-increment starting point. Neither performs row-by-row deletion, so both are fast but essentially irreversible, and TRUNCATE does not fire row-level triggers. If you only want to delete part of the data, you should use the DML DELETE with conditions and a transaction.

    4. Practical Recommendations

    First, put all database and table creation scripts under version control so structural changes are traceable, reviewable, and replayable. Second, stick to idempotent forms; IF NOT EXISTS and IF EXISTS significantly reduce failures from repeated execution. Third, standardize the character set on utf8mb4, set once at the database level. Fourth, treat DROP and TRUNCATE as actions that require approval, with least-privilege access. Fifth, always back up before a structural change and always verify after it.

    In cloud environments, these conventions still apply; the difference is that backup, change review, and monitoring and alerting are handled by the database service and general-purpose monitoring and alerting capabilities, turning DDL execution from an “individual operation” into a “controllable process.” Master the commands above and the reasoning behind them, and you have grasped the fundamentals of MySQL structure definition.