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

    This article explains the role of DDL (Data Definition Language) in MySQL and how it differs from DML, focusing on metadata changes, implicit commits, and the higher cost of structural operations. It walks through database-level commands, table creation and alteration, indexes, constraints and views, execution mechanisms for large-table changes, and common mistakes to avoid, offering a practical reference for running schema changes safely.

    In day-to-day MySQL development and operations, DDL (Data Definition Language) is responsible for defining data structures. Unlike DML, which handles inserting, updating, deleting, and querying data, DDL focuses on the skeleton of objects such as databases, tables, indexes, and views. The original material only listed four core database-level commands; this article builds on that foundation and expands it into five layers: database operations, table operations, indexes and constraints, execution mechanisms, and engineering practices, forming a hands-on guide you can apply directly.

    1. Understanding Where DDL Fits in SQL

    SQL statements are usually divided into four categories: DDL defines structures, DML manipulates data, DCL handles permission control, and TCL handles transaction control. There are three key points to understand about DDL.

    First, the target of DDL is metadata, the information that describes structure, which is stored in the data dictionary. After a DDL statement runs, what actually changes is the data dictionary and internal object definitions, not the business data inside tables.

    Second, DDL implicitly commits transactions in most cases. This means you cannot roll back a create-table or alter-table operation the way you can with DML, so you must confirm the script is correct before running it in production.

    Third, DDL is usually far more expensive than DML. A column change on a large table may trigger a table rebuild, consuming resources for a long time and affecting reads and writes. This is the fundamental reason DDL needs to be included in a change management process.

    2. Database-Level DDL: The Four Basic Actions

    A database is the namespace for objects, and database-level operations are the starting point for everything that follows.

    • Create: create database demo_db default character set utf8mb4 collate utf8mb4_general_ci; Explicitly specifying the character set and collation is a good habit, as it avoids garbled text caused by inheriting server defaults.
    • Drop: drop database demo_db; This operation cannot be undone, so always confirm the database name and backup status before running it.
    • List: show databases; Lists the databases the current account has permission to access; note that the result depends on permissions.
    • Switch: use demo_db; This only changes the default database for the current session and does not affect other connections.
    • Confirm the current location: select database(); In scripts, it is recommended to use this as a precondition check to avoid running changes against the wrong database.

    In engineering practice, the preferred approach is to use a form with an existence check so the script can be run repeatedly:

    1. create database if not exists demo_db
    2. default character set utf8mb4 collate utf8mb4_general_ci;

    3. Table-Level DDL: The Real High-Frequency Battleground

    Tables are the core carrier of data structures and the place where DDL is used most intensively.

    When creating a table, you should be clear about three things: the field type and length, whether NULL is allowed, and the default value. At the same time, design the primary key, unique constraints, and normal indexes during modeling rather than adding them after going live.

    1. create table if not exists t_user (
    2. id bigint unsigned not null auto_increment comment 'Primary key',
    3. user_name varchar(64) not null comment 'Username',
    4. email varchar(128) null comment 'Email',
    5. status tinyint not null default 1 comment 'Status',
    6. created_at datetime not null default current_timestamp,
    7. primary key (id),
    8. unique key uk_user_name (user_name),
    9. key idx_email (email)
    10. ) engine=innodb default charset=utf8mb4 comment='User table';

    To modify a table structure, use alter table. Common forms include: add column to add a field, modify column to adjust a definition, change column to rename and change the type at the same time, drop column to remove a field, add index and drop index to maintain indexes, and rename to to rename a table. To delete a table, use drop table; to clear data while keeping the structure, use truncate table — the latter falls under DDL, cannot be rolled back, and does not preserve the auto-increment progress. To inspect structure, rely on show create table, desc t_user, and data dictionary queries.

    4. Indexes, Constraints, and Views

    Indexes are the part of DDL with the most obvious benefits. When building composite indexes for fields that are frequently filtered and sorted, follow the leftmost prefix principle, put the columns with high cardinality first, and avoid applying functions to indexed columns, which makes the index ineffective.

    For constraints, a primary key guarantees uniqueness and non-null values, a unique constraint guarantees business uniqueness, and foreign keys are often replaced by application-level validation in distributed and high-concurrency scenarios to reduce lock contention and operational complexity. This is a widely adopted trade-off in the industry.

    Views, stored procedures, functions, and triggers are also created by DDL. They are updated with create or replace or by dropping and then creating them again; pay attention to dependencies and permission requirements.

    5. Execution Mechanisms and Risk Control

    For large-table changes, it is recommended to follow a gradual path of “add first, then modify, then clean up”: add a new field and write to both, backfill historical data, switch reads and writes, and finally remove the old field. Before the change, confirm disk space, backups, and rollback scripts; during the change, watch for lock waits and replication lag; after the change, verify table structure and data consistency.

    If you use a managed database service in the cloud, you can combine monitoring alerts and log services to observe resource metrics during the change window, bringing DDL into an observable and traceable process. General practices on cloud platforms such as Baidu AI Cloud also emphasize: validate structure changes in a staging environment first, then run them gradually during off-peak business hours.

    6. A Checklist of Common Mistakes

    First, assuming DDL can be rolled back; second, omitting the character set, which causes garbled text in multilingual scenarios; third, allowing meaningless NULL values in fields, which increases query complexity; fourth, over-building indexes, which slows down writes; fifth, lacking an if not exists check, which makes scripts fail when run repeatedly; sixth, typing commands directly by hand on the production database, with no review or audit trail.

    Mastering the complete semantics, cost, and conventions of the database-level and table-level DDL above turns structural changes from “operating by feel” into an engineering action that is predictable, verifiable, and reversible.