14 / 17 · Changing Data
Tables and constraints
Declare identities and admissible values in a PostgreSQL schema, then add a rule to a table that already contains rows.
Two imports send position 101/1. The first says the order contains two units of tea, the second says three. Both fit the column types. If both rows enter the table, a later sum can count five units. The store treats the pair of order number and position number as one identity. We need a table declaration that rejects a second row with that identity.
Declare a table and its identities#
We use two tables in a fresh PostgreSQL session. One row in orders represents one order. One row in order_lines represents one position. A receipt code is optional and must be unique when assigned. The line number is local to the order. The store allows free items, so their price can be zero.
CREATE TEMP TABLE orders (
order_id integer PRIMARY KEY,
receipt_code text UNIQUE
);
CREATE TEMP TABLE order_lines (
order_id integer,
line_no integer CONSTRAINT line_no_positive CHECK (line_no > 0),
product text NOT NULL,
quantity integer NOT NULL
CONSTRAINT quantity_positive CHECK (quantity > 0),
unit_price_cents integer NOT NULL
CONSTRAINT unit_price_nonnegative CHECK (unit_price_cents >= 0),
CONSTRAINT order_lines_pk PRIMARY KEY (order_id, line_no),
CONSTRAINT order_lines_order_fk
FOREIGN KEY (order_id) REFERENCES orders (order_id)
);
CREATE TABLE describes the shape of future rows even when the table is empty. Here TEMP scopes each table to the current session. A constraint adds a rule about which states the table may hold. A PRIMARY KEY requires the listed columns to be non-null and their combination to be unique. A table can have one primary key. Other combinations can have their own UNIQUE constraints. Declaring the key on both fields makes (101, 1) and (102, 1) compatible. It rejects a second (101, 1) even if the quantity differs. PostgreSQL 18, §5.5 and CREATE TABLE
A column constraint such as CHECK (quantity > 0) is written beside the column. A table constraint can refer to several columns, as the primary key does here. We give names to several constraints so that we can refer to them in error reports or schema changes.
INSERT INTO orders (order_id, receipt_code) VALUES
(101, 'R-101'),
(102, NULL),
(103, NULL);
INSERT INTO order_lines (
order_id, line_no, product, quantity, unit_price_cents
) VALUES
(101, 1, 'tea', 2, 350),
(101, 2, 'coffee', 1, 600),
(102, 1, 'tea', 1, 350);
PostgreSQL’s default UNIQUE rule treats missing values as distinct for this check, so orders 102 and 103 may both lack a receipt code. A second 'R-101' is rejected. If the desired rule is at most one row with a missing receipt code, PostgreSQL supports UNIQUE NULLS NOT DISTINCT. A single-column UNIQUE constraint in SQL Server already allows at most one NULL. The null policy matters when moving a schema between engines. PostgreSQL 18, §5.5.3 Microsoft, Unique constraints
Check values and references#
SQL’s CHECK and WHERE use the same three truth values. They use different acceptance rules. A filter retains rows for which the condition is true. A check rejects a row when the condition is false. For an unknown quantity, quantity > 0 is unknown, so CHECK (quantity > 0) alone would allow it. NOT NULL expresses the separate requirement that we have a quantity. PostgreSQL 18, §§5.5.1–5.5.2
One predicate for reading and writing
A foreign key requires the non-null reference in a position to match a row of orders. The primary key of orders guarantees that the match is unique. Here order_id in order_lines must be present because it is part of the primary key. For a foreign-key column outside the primary key, add NOT NULL if the relationship is mandatory. A nullable single-column foreign key can represent an optional relationship. PostgreSQL 18, §§5.5.4–5.5.5
These attempted inserts illustrate the rules on the same starting data. Run them separately to see each rejection.
INSERT INTO order_lines VALUES (101, 1, 'tea', 3, 350);
INSERT INTO order_lines VALUES (101, 3, 'tea', 0, 350);
INSERT INTO order_lines VALUES (101, 3, 'tea', NULL, 350);
INSERT INTO order_lines VALUES (109, 1, 'tea', 1, 350);
INSERT INTO orders VALUES (104, 'R-101');
| Proposed value | Reason for rejection |
|---|---|
| Second position 101/1 | Duplicate primary key |
| Quantity 0 | quantity_positive check fails |
Quantity NULL | Quantity is required |
| Position in order 109 | Referenced order is absent |
Order 104 with code R-101 | Receipt code already in use |
Deleting order 101 would also fail because positions still reference it. The default action in this schema is ON DELETE NO ACTION with an immediate check. A declared ON DELETE CASCADE would instead delete the referencing positions as part of the parent deletion. The desired action depends on whether the store must retain those positions. In SQLite, foreign-key enforcement is a connection setting. With a build that supports foreign keys, set PRAGMA foreign_keys = ON outside a transaction and check the setting on each connection. PostgreSQL 18, §5.5.5 SQLite, §§1–2
The constraint on each position does not require that every order have a position. Order 103 is already an example with none. A rule such as “a paid order has at least one position” spans tables and a change in order state. A PostgreSQL row check cannot inspect rows in another table to enforce this. The databases course develops how to separate rules about references from rules about the model as a whole. PostgreSQL 18, §5.5.1
Add a rule to existing rows#
The store now wants to record a channel on each order. Adding a column changes the schema of existing rows as well as future ones. The first command adds a nullable column without a default, so all three existing values start as NULL. At this point a command to set NOT NULL would fail. We know the channels from the toy import, so we fill them in before requiring the value.
ALTER TABLE orders ADD COLUMN sales_channel text;
UPDATE orders SET sales_channel = 'web' WHERE order_id IN (101, 102);
UPDATE orders SET sales_channel = 'shop' WHERE order_id = 103;
ALTER TABLE orders
ADD CONSTRAINT orders_sales_channel_check
CHECK (sales_channel IN ('web', 'shop'));
ALTER TABLE orders ALTER COLUMN sales_channel SET NOT NULL;
The check verifies that each known channel belongs to the accepted set. The final command verifies that no order lacks a channel. After both succeed, a new order must supply either 'web' or 'shop'. With real historical data, the backfill has to come from a source that can justify those values. On a large PostgreSQL table the usual validation of a new constraint may scan existing rows, and changing the schema can require locks. The example runs on three rows in one session. PostgreSQL 18, ALTER TABLE
Next#
The table can now tell which states are admissible. It still needs instructions for choosing which rows to change and what to do when the incoming key already exists. Changing rows and handling conflicts applies those instructions to the order lines.
References#
- PostgreSQL Global Development Group. PostgreSQL 18 documentation. Constraints, §5.5, CREATE TABLE and ALTER TABLE define the constraint syntax, its null rules and validation against existing data.
- SQLite Project. SQLite Foreign Key Support, §§1–2. Gives the connection setting and the effects of enabling foreign keys.
- Microsoft. Unique constraints and check constraints. Describes uniqueness and its treatment of nulls in SQL Server.