Sub topic 12
Column-level and table-level constraint syntax
This chapter shows the two places where a constraint can be written in CREATE TABLE, and how to choose between them. It assumes you can write a basic CREATE TABLE. It also assumes you know what NOT NULL, PRIMARY KEY, UNIQUE, FOREIGN KEY, and CHECK do. The examples use PostgreSQL-style syntax. Notes mark where other systems differ.
Two places to write a constraint
A constraint can appear in one of two positions inside the parentheses of CREATE TABLE.
- A column-level constraint sits on the same line as one column, after its data type. It describes that column.
- A table-level constraint is its own item in the list, after all the column definitions. It names the columns it applies to in parentheses.
Both forms create the same kind of rule. The difference is only syntax and how many columns the rule can involve.
CREATE TABLE products (
product_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
sku VARCHAR(30) NOT NULL UNIQUE,
price NUMERIC(10, 2) NOT NULL CHECK (price >= 0)
);Every constraint above is column-level. Here is the same design written with table-level constraints. The table is called products_tl so you can run both examples in one database.
CREATE TABLE products_tl (
product_id INTEGER GENERATED ALWAYS AS IDENTITY,
sku VARCHAR(30) NOT NULL,
price NUMERIC(10, 2) NOT NULL,
CONSTRAINT pk_products_tl PRIMARY KEY (product_id),
CONSTRAINT uq_products_tl_sku UNIQUE (sku),
CONSTRAINT ck_products_tl_price CHECK (price >= 0)
);The database enforces both tables identically. Only the layout differs.
What each form can express
A rule that involves more than one column must be a table-level constraint. Some rules can be written in either form. A few things can only be written at column level.
| Rule | Column-level | Table-level |
|---|---|---|
| `NOT NULL` | Yes | No (in most systems) |
| `DEFAULT` | Yes | No |
| Single-column `PRIMARY KEY` | Yes | Yes |
| Composite `PRIMARY KEY` | No | Yes |
| Single-column `UNIQUE` | Yes | Yes |
| Composite `UNIQUE` | No | Yes |
| Single-column `FOREIGN KEY` | Yes (`REFERENCES`) | Yes |
| Composite `FOREIGN KEY` | No | Yes |
| `CHECK` on one column | Yes | Yes |
| `CHECK` on several columns | Avoid | Yes |
DEFAULT is strictly a property of a column, not a constraint, but it lives in the same place in the syntax. NOT NULL is also written only on the column line in most systems. Recent PostgreSQL versions have started to accept named NOT NULL constraints at table level, but you cannot rely on that elsewhere.
Rules that need the table-level form
Composite keys
A composite key spans several columns. The parentheses list the columns, so there is no way to write it on one column's line. This is the junction table from the schema you are building:
CREATE TABLE order_items (
order_id INTEGER NOT NULL,
product_id INTEGER NOT NULL,
quantity INTEGER NOT NULL CHECK (quantity > 0),
PRIMARY KEY (order_id, product_id),
FOREIGN KEY (order_id) REFERENCES orders (order_id) ON DELETE CASCADE,
FOREIGN KEY (product_id) REFERENCES products (product_id)
);Here quantity > 0 is column-level because it concerns one column. The key and both foreign keys are table-level. The two foreign keys are single-column rules, but they are written at table level so they can carry ON DELETE actions beside the column list. Column-level REFERENCES also accepts those actions in most systems, so this is a style choice.
A composite foreign key must reference a matching composite key, with the same number of columns in the same order:
CREATE TABLE shipment_lines (
shipment_id INTEGER NOT NULL,
order_id INTEGER NOT NULL,
product_id INTEGER NOT NULL,
qty_shipped INTEGER NOT NULL,
CONSTRAINT pk_shipment_lines
PRIMARY KEY (shipment_id, order_id, product_id),
CONSTRAINT fk_shipment_lines_item
FOREIGN KEY (order_id, product_id)
REFERENCES order_items (order_id, product_id),
CONSTRAINT ck_shipment_lines_qty CHECK (qty_shipped > 0)
);This rejects a shipment line for a product that is not part of that order. Two single-column foreign keys would not catch that, because each column could match some row independently.
Checks across columns
A CHECK that compares two columns belongs at table level:
CREATE TABLE promotions (
promotion_id INTEGER GENERATED ALWAYS AS IDENTITY,
code VARCHAR(20) NOT NULL,
starts_on DATE NOT NULL,
ends_on DATE NOT NULL,
discount_pct NUMERIC(5, 2) NOT NULL DEFAULT 0,
CONSTRAINT pk_promotions PRIMARY KEY (promotion_id),
CONSTRAINT uq_promotions_code UNIQUE (code),
CONSTRAINT ck_promotions_dates CHECK (ends_on >= starts_on),
CONSTRAINT ck_promotions_pct CHECK (discount_pct BETWEEN 0 AND 100)
);Some systems allow a column-level check to mention other columns, and some do not. Writing the cross-column rule at table level works everywhere and tells the reader that the rule is about the row, not one value.
Composite uniqueness
If each customer may use a coupon code once, neither column is unique alone. The pair is:
CREATE TABLE coupon_redemptions (
customer_id INTEGER NOT NULL,
coupon_code VARCHAR(20) NOT NULL,
redeemed_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT uq_redemption UNIQUE (customer_id, coupon_code)
);Putting UNIQUE on each column separately would be a different and much stricter rule. Each customer could redeem only one coupon, and each coupon could be redeemed by only one customer.
Layout rules and common errors
- Commas. Column definitions and table-level constraints are separated by commas. Column-level constraints are not, because they belong to the column definition. A comma between a column's type and its constraint ends the column early and causes a syntax error.
- Order. Table-level constraints conventionally come after all columns. Most systems accept them between columns, but a consistent layout is easier to read.
- One primary key. A table can have only one primary key. Declaring one at column level and another at table level fails. PostgreSQL reports
multiple primary keys for table "..." are not allowed. - Composite key at column level. Writing
PRIMARY KEYon two separate column lines does not create a composite key. It declares two primary keys, which is the error above. UsePRIMARY KEY (a, b)at table level. - Unknown columns. A table-level constraint can only name columns defined in the same statement. A misspelled name raises an error such as
column "..." named in key does not exist.
Names and error messages
A column-level constraint can be named too, with CONSTRAINT name placed before the constraint keyword:
CREATE TABLE warehouses (
warehouse_id INTEGER GENERATED ALWAYS AS IDENTITY
CONSTRAINT pk_warehouses PRIMARY KEY,
code VARCHAR(10) NOT NULL
CONSTRAINT uq_warehouses_code UNIQUE,
capacity INTEGER NOT NULL
CONSTRAINT ck_warehouses_capacity CHECK (capacity > 0)
);Without CONSTRAINT name, the database generates a name. PostgreSQL produces names like warehouses_pkey, warehouses_code_key, and warehouses_capacity_check. Generated names differ between systems and are awkward to use in ALTER TABLE ... DROP CONSTRAINT. Violation messages quote the name, so a name such as ck_warehouses_capacity tells you what failed.
Reading a failure
Suppose promotions contains no rows and you run this:
INSERT INTO promotions (code, starts_on, ends_on)
VALUES ('SPRING', '2026-04-10', '2026-04-01');The row is rejected because ends_on is earlier than starts_on. PostgreSQL's message names the table and the constraint: new row for relation "promotions" violates check constraint "ck_promotions_dates". The statement changes nothing. The name ck_promotions_dates points you at the table-level rule directly.
Exercise
You are designing enrollments(student_id, course_id, enrolled_on, dropped_on). Each student may enroll in a course only once, and a drop date, when present, must not be earlier than the enrollment date. Write the table-level constraints that enforce both rules, with names, and say why neither can be a column-level constraint on a single column.
Show answer
Add these items after the column definitions: CONSTRAINT uq_enrollments_student_course UNIQUE (student_id, course_id) and CONSTRAINT ck_enrollments_dates CHECK (dropped_on IS NULL OR dropped_on >= enrolled_on). Uniqueness applies to the pair of columns, and a column-level UNIQUE on either column would limit each student to one course or each course to one student. The check compares two columns, so it describes the row and belongs at table level. A comparison with a NULL dropped_on evaluates to unknown, which CHECK accepts, so the IS NULL branch is optional but makes the intent explicit.
Exercise
A teammate writes order_id INTEGER PRIMARY KEY, product_id INTEGER PRIMARY KEY to make a composite key. What happens, and what is the fix?
Show answer
The table declares two primary keys, and the database rejects it, for example with multiple primary keys for table ... are not allowed in PostgreSQL. The fix is to remove both column-level PRIMARY KEY clauses, mark the columns NOT NULL, and add PRIMARY KEY (order_id, product_id) as a table-level constraint.