MySQL DDL Statements: A Practical Guide to Common Commands and Best Practices
This guide explains the role of DDL (Data Definition Language) in MySQL and how it fits alongside DML and DCL. It covers database and table level operations, including creating, inspecting, altering, dropping, and truncating objects, how to read execution feedback, and the side effects of structural changes. It also summarizes practical recommendations such as idempotent scripts, rollback planning, naming and charset consistency, least privilege, and change auditing.
1. Introduction: Why DDL Is the Starting Point of Database Work
Almost all work with a relational database begins with defining structure. Whether you are building a brand new business database or adding columns and adjusting indexes on an existing system, you are fundamentally operating on database objects. These operations are classified as DDL (Data Definition Language), which together with DML (data manipulation) and DCL (data control) forms the three main branches of SQL.
The defining trait of DDL is that it targets structure rather than data rows. Once executed, it usually cannot be rolled back, because most storage engines and deployment modes commit it implicitly. As a result, mistakes are costly and the blast radius is wide. Understanding the semantics and side effects of each DDL statement is an essential skill for both developers and operations engineers.
2. The Three Categories of SQL Statements
- DDL (Data Definition Language): Defines databases, tables, columns, indexes, views, and other objects. Common keywords are CREATE, ALTER, DROP, TRUNCATE, and RENAME.
- DML (Data Manipulation Language): Operates on records inside tables. Common keywords are INSERT, DELETE, UPDATE, and SELECT.
- DCL (Data Control Language): Manages access permissions and security levels. Common keywords are GRANT and REVOKE.
The boundaries are clear: DDL decides what can be stored, DML decides what is stored, and DCL decides who is allowed to store it. When troubleshooting, identifying which category a statement belongs to often narrows down the problem quickly.
3. Database-Level DDL Operations
3.1 Creating a Database
CREATE DATABASE IF NOT EXISTS demo_dbDEFAULT CHARACTER SET utf8mb4DEFAULT COLLATE utf8mb4_general_ci;
Explicitly specifying the character set and collation is recommended, so the database does not inherit instance defaults that could later cause garbled Chinese text or inconsistent comparison behavior. IF NOT EXISTS makes the script idempotent, which is useful in initialization flows that may run repeatedly.
3.2 Listing Databases
SHOW DATABASES;
A freshly installed instance usually ships with a few system databases, which serve roughly these purposes:
- Metadata and object information: stores descriptions of tables, columns, permissions, character sets, partitions, and so on;
- Privilege database: stores accounts and their grants;
- Test database: an empty database created by default, which should be removed or denied access in production.
3.3 Switching and Dropping
USE demo_db;DROP DATABASE IF EXISTS demo_db;
Dropping a database is irreversible, so always confirm backups and dependencies before running it.
4. How to Read Execution Feedback
After running a DDL statement, a typical message looks like Query OK, 1 row affected (0.00 sec). It can be broken into three parts:
- Query OK: The statement executed successfully. This is the generic success marker in this database, shown after both DDL and DML (excluding query statements) succeed.
- 1 row affected: The number of affected rows. DDL does not operate on data rows, so this is mostly a placeholder produced by a unified output format; it should not be read as “one row of data was changed”.
- 0.00 sec: The elapsed time, useful for a rough sense of execution cost.
Note that DDL on large tables can take a long time and involves metadata changes and data rebuilding, so run it during off-peak hours with monitoring and alerting in place.
5. Core Table-Level DDL
5.1 Creating a Table
CREATE TABLE emp (ename VARCHAR(10) NOT NULL,hiredate DATE NOT NULL,sal DECIMAL(10,2) NOT NULL DEFAULT 0.00,deptno INT NOT NULL,PRIMARY KEY (deptno)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Key points:
- A column definition consists of three parts: name, type, and constraints;
- Monetary fields should use fixed-point decimal types rather than floating-point types to avoid precision loss;
- Declare the storage engine and character set explicitly to keep environments consistent;
- A table exists on disk as a directory, so its name must respect filesystem limits; a consistent lowercase-with-underscores style is recommended.
5.2 Inspecting Table Definitions
SHOW TABLES;SHOW CREATE TABLE emp;DESC emp;
SHOW CREATE TABLE reproduces the full create statement, making it the best reference for migrations and version verification, while DESC is handy for a quick overview of columns and types.
5.3 Altering a Table
ALTER TABLE emp ADD COLUMN email VARCHAR(50) NULL;ALTER TABLE emp MODIFY COLUMN sal DECIMAL(12,2) NOT NULL DEFAULT 0.00;ALTER TABLE emp CHANGE COLUMN ename emp_name VARCHAR(20) NOT NULL;ALTER TABLE emp DROP COLUMN email;ALTER TABLE emp ADD INDEX idx_name (emp_name);ALTER TABLE emp ENGINE=InnoDB;
Altering table structure is a high-impact operation: it may trigger a table rebuild, lock waits, and replication lag. Assess the data volume, pick a suitable execution window, and back up the structure before and after the change.
5.4 Dropping and Truncating
TRUNCATE TABLE emp; -- Clear data, keep structureDROP TABLE IF EXISTS emp; -- Remove structure as well
Neither can be rolled back, and their semantics differ completely from DELETE, so never use them interchangeably.
6. Practical Recommendations and Common Pitfalls
- Idempotent scripts: Use
IF NOT EXISTSin initialization scripts so they can be re-run safely; - Reversible changes: Prepare a reverse statement for every structural change and keep it under version control;
- Consistent naming and charsets: Fix the naming style for databases, tables, and columns, plus the character set, at project kickoff;
- Least privilege: Grant DDL privileges only to the accounts that need them, and scope access with DCL statements;
- Auditable changes: Use logging services and monitoring alerts to record who changed what and when;
- Cloud practice: With managed database services, general capabilities such as snapshots, backup and restore, and monitoring alerts help reduce change risk; database products from cloud providers such as Baidu AI Cloud generally follow the same conventions.
7. Summary
DDL is the backbone of database structure management: create and inspect solve going from nothing to something, alter supports evolution with the business, and drop or truncate demand extra caution. Writing the statements correctly is only the first step; a reliable engineering practice also accounts for execution timing, rollback plans, and permission boundaries.
