SQL statements are often grouped into families. The names look scary, but the idea is simple: what does the statement do?
| Family | Full name | Purpose | Main MySQL statements |
|---|---|---|---|
| DDL | Data Definition Language | Define the structure | CREATE, ALTER, DROP, TRUNCATE, RENAME |
| DML | Data Manipulation Language | Change the data | INSERT, UPDATE, DELETE, REPLACE |
| DQL | Data Query Language | Read data | SELECT |
| DCL | Data Control Language | Control access | GRANT, REVOKE, CREATE USER |
| TCL | Transaction Control Language | Control transactions | START TRANSACTION, COMMIT, ROLLBACK, SAVEPOINT |
Some books count SELECT as part of DML. Both views are common, so you will meet both.
An example of each
-- DDL: define a table
CREATE TABLE notes (id INT AUTO_INCREMENT PRIMARY KEY, body VARCHAR(100));
-- DML: change data
INSERT INTO notes (body) VALUES ('first'), ('second');
UPDATE notes SET body = 'FIRST' WHERE id = 1;
DELETE FROM notes WHERE id = 2;
-- DQL: read data
SELECT * FROM notes;
+----+-------+
| id | body |
+----+-------+
| 1 | FIRST |
+----+-------+
1 row in set
-- TCL: control a transaction
START TRANSACTION;
INSERT INTO notes (body) VALUES ('temporary');
ROLLBACK;
SELECT COUNT(*) AS rows_now FROM notes;
+----------+
| rows_now |
+----------+
| 1 |
+----------+
1 row in set
The ROLLBACK cancelled the INSERT, so the table still has one row.
DCL (GRANT and friends) is shown in the Users, Roles and Security chapter.
DDL is special in MySQL
In MySQL, a DDL statement commits automatically. It ends any open transaction and cannot be rolled back.
START TRANSACTION;
INSERT INTO notes (body) VALUES ('before the DDL');
CREATE TABLE side_effect (id INT);
ROLLBACK;
SELECT body FROM notes;
+----------------+
| body |
+----------------+
| FIRST |
| before the DDL |
+----------------+
2 rows in set
The CREATE TABLE forced a commit, so the ROLLBACK found nothing to undo and the row before the DDL stayed. Many other databases (PostgreSQL, for example) allow DDL inside a transaction. MySQL does not.
DROP and TRUNCATE are final
DROP TABLE, DROP DATABASE and TRUNCATE TABLE cannot be rolled back. The only way back is a backup. Run them in a script only when you are certain of the target.Why the families matter
- Permissions follow them. A reporting user may get only
SELECT. An app user getsSELECT,INSERT,UPDATE,DELETE. Only an admin (or a migration tool) gets DDL rights. - Risk follows them. DQL cannot damage data. DML can. DDL can destroy it.