Sub topic 1
DDL: statements that change the schema
Data Definition Language (DDL) is the group of SQL statements that create, change and remove the structures that hold your data. Every later chapter in this tutorial, from ALTER TABLE to DROP TABLE, builds on the ideas here.
Prerequisites
This chapter assumes you can already do the following:
- Write basic
SELECT,INSERT,UPDATEandDELETEstatements. - Use
CREATE TABLEwith common data types. - Explain what primary keys and foreign keys are.
- Run SQL against a test database such as PostgreSQL, MySQL, SQL Server or SQLite. Use a throwaway database, not production.
What DDL is
SQL statements fall into groups by what they act on. DDL statements act on the schema. The schema is the set of definitions that describe how data is organized: tables, columns, data types, constraints, indexes and views. The statements you already know, SELECT, INSERT, UPDATE and DELETE, are Data Manipulation Language (DML). They act on the rows stored inside those structures.
The core DDL statements are:
CREATEmakes a new object, such as a table, index or view.ALTERchanges the definition of an existing object.DROPremoves an object and everything stored in it.
Many systems also treat TRUNCATE as DDL, and some treat RENAME as DDL too. This tutorial focuses on ALTER TABLE and DROP TABLE.
Some people put SELECT in its own group (DQL, for queries). The grouping is a teaching convention, not part of the SQL standard's behavior. What matters in practice is the difference in effect, which the next section covers.
DDL versus DML
| Aspect | DML | DDL |
|---|---|---|
| Acts on | Rows | Table and column definitions, constraints, indexes |
| Typical statements | `INSERT`, `UPDATE`, `DELETE` | `CREATE`, `ALTER`, `DROP` |
| Scope of one statement | Some or all rows, chosen by `WHERE` | The whole object. There is no `WHERE` |
| Transaction behavior | Always part of the current transaction | Depends on the database (see below) |
| Locking | Usually row-level locks | Often a table-level lock |
| Undo | `ROLLBACK` before `COMMIT` | Sometimes `ROLLBACK`, sometimes only a restore from backup |
Two consequences follow from the table. First, a DDL statement affects every row in a table at once, so its effect on the data can be much larger than that of a single UPDATE. Second, you cannot count on ROLLBACK to undo it.
How DDL treats transactions
A transaction groups statements so they succeed or fail together. DML works the same way in every major database. DDL does not.
- PostgreSQL and SQLite support transactional DDL. You can run
ALTER TABLEinsideBEGIN ... ROLLBACK, and the change disappears. - MySQL and Oracle commit the current transaction implicitly before and after most DDL statements. The change is permanent as soon as the statement finishes, and any DML you ran earlier in that transaction is committed too.
- SQL Server supports transactional DDL for many statements, but some operations are not allowed inside a transaction.
A later chapter covers running schema changes inside transactions in detail. For now, treat every DDL statement as potentially permanent.
A first look at DDL in action
The script below uses DDL to create a table, DML to fill it, then DDL again to change it. It runs on PostgreSQL, MySQL and SQLite. SQL Server omits the COLUMN keyword in ADD.
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
INSERT INTO customers (id, name) VALUES (1, 'Ada'), (2, 'Grace');
ALTER TABLE customers ADD COLUMN email VARCHAR(255);
SELECT id, name, email FROM customers;The INSERT adds two rows. The ALTER TABLE changes the table definition, and the existing rows pick up the new column automatically. Both rows show NULL in email, because the new column is nullable and has no default. The row data was not rewritten by you. The database filled in the missing value according to the new definition.
The system catalog
Where does the database store the schema? In the system catalog, a set of internal tables and views that describe every object in the database. When you run DDL, you are really editing catalog entries, and the database then reshapes stored data to match them.
You can read the catalog with ordinary SELECT statements. The standard information_schema views work in PostgreSQL, MySQL and SQL Server:
SELECT column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_name = 'customers'
ORDER BY ordinal_position;SQLite has no information_schema. Use this instead:
PRAGMA table_info(customers);Reading the catalog before and after a change is a good habit. It confirms that the change did what you intended, and it shows the exact column names and types you are about to alter.
Why DDL needs extra care
DDL deserves more caution than everyday queries for four reasons.
- No row filter.
DROP TABLE customershas noWHEREclause. It removes the table and all of its data in one step. - Dependencies. Foreign keys, views, indexes and application code all depend on the schema. Changing a table can break them, or the database may refuse the change.
- Locks. Many DDL statements need an exclusive lock on the table, which blocks other sessions. On a large, busy table this can stall an application.
- Weak undo. Depending on the database, there may be no
ROLLBACK. The only recovery is a backup.
These four points drive the rest of the tutorial. The chapters on DROP TABLE and CASCADE address dependencies. The chapter on locking addresses large tables. The chapters on transactions and safe migrations address undo.
Dialect differences to expect
DDL is the area where SQL dialects differ most. The SELECT and INSERT statements you know are close to portable. ALTER TABLE is not. The same change may need different keywords in each database:
- Changing a column's type uses
ALTER COLUMN ... TYPEin PostgreSQL,MODIFY COLUMNin MySQL, andALTER COLUMNwith the full definition in SQL Server. - SQL Server omits the
COLUMNkeyword inADD. - SQLite supported only a few
ALTER TABLEoperations for many years, and some changes still require rebuilding the table.
Later chapters show each form side by side. Before you run any DDL script, confirm which database and version you are connected to.
Exercises
Exercise
You run UPDATE customers SET name = 'X' followed by ALTER TABLE customers ADD COLUMN phone VARCHAR(30) inside one transaction on MySQL, then run ROLLBACK. Is the change to name undone? Explain which statement is DDL and which is DML.
Show answer
No. The UPDATE is DML and the ALTER TABLE is DDL. MySQL commits the current transaction implicitly when it runs most DDL statements, so the UPDATE is committed before ALTER TABLE runs. The later ROLLBACK has nothing left to undo. On PostgreSQL the whole transaction, including the ALTER TABLE, would be rolled back.
Exercise
Name two reasons a DDL statement such as DROP TABLE needs more care than a DELETE with a WHERE clause.
Show answer
Any two of these: it has no WHERE clause, so it affects the whole table and all its data at once; other objects such as foreign keys and views may depend on the table; it can take an exclusive lock that blocks other sessions; and in some databases it cannot be rolled back.