DDL & DML
Define tables with constraints (CREATE, ALTER, DROP), change rows safely (INSERT, UPDATE, DELETE, upsert), and change a live schema without locking it up.
Overview
SQL statements come in two main groups. DDL (data definition language) changes the shape of the database: tables, columns, constraints and indexes. DML (data manipulation language) changes the rows inside those tables.
The DDL statements are CREATE, ALTER, DROP and TRUNCATE. They change the schema, or, in the case of TRUNCATE, remove all rows at once. The DML statements are INSERT, UPDATE, DELETE and MERGE, and they change individual rows. A query, SELECT, changes nothing; it only reads.
In interviews this topic shows up as schema design ('design the tables for an online store'), as small data-fix problems ('delete the duplicate emails'), and as operations questions ('add a NOT NULL column to a busy table without downtime').
The two groups meet at the constraints. DDL sets the rules once, and every change DML makes is checked against them.
Create tables with constraints
A constraint is a rule the database itself checks on each insert and update, so no program, script or manual fix can store rows that break it.
These two tables use six column clauses. Five are rules the database enforces, and most have a catch worth knowing. The sixth only fills in a value.
- PRIMARY KEY: the value must be unique and not null, and the database builds a unique index for it. A table can have only one.
- UNIQUE: no two rows may hold equal values. By default it still allows many NULLs.
- NOT NULL: a value is required. This is the simple one, with no catch.
- CHECK (expr): the expression must not be false. A NULL makes the expression unknown, and unknown passes.
- REFERENCES (a foreign key): the value must exist in the parent table. The child column gets no index automatically.
- DEFAULT: the value used when an INSERT leaves the column out. It is not a rule; it never rejects anything.
GENERATED ALWAYS AS IDENTITY is the standard way to make an auto-numbered key. The column gets its own sequence and is NOT NULL, and an INSERT cannot set it by accident. In PostgreSQL, text and varchar(n) perform the same (varchar(n) only adds a length check on write), so a length limit is a business rule, not a speed trick.
Sign up free to read the full topic
More Databases & SQL topics
Start free on Cariara · Coding problems · System design studio