CHECK Constraint Regex Format Guard

Enforce code formats at the database boundary with a CHECK constraint on a POSIX regex pattern, so malformed tracking codes are rejected on write.

SqlSecurity Boundaries

Code

snippet
-- CHECK constraints can use regex matching with ~; anchor with ^ and $ yourself or only a prefix matches
-- Shipment-code rule: three uppercase letters, a dash, four digits (SHP-2026); the constraint is the last guard before a row lands
CREATE TABLE shipments (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    tracking_code text NOT NULL CHECK (tracking_code ~ '^[A-Z]{3}-[0-9]{4}$'),
    weight_kg numeric(8,2) NOT NULL CHECK (weight_kg > 0)
);

INSERT INTO shipments (tracking_code, weight_kg) VALUES ('SHP-2026', 2.50);

-- A wrong-case write is rejected at the statement level: application and database share one rule
INSERT INTO shipments (tracking_code, weight_kg) VALUES ('shp-2026', 2.50);

-- Validate before inserting: keep this expression identical to the constraint's regex
SELECT 'SHP-2026' ~ '^[A-Z]{3}-[0-9]{4}$' AS valid_code;

What the code does

Several statements share this file — INSERT / CREATE, with shipments among the objects involved.

The pieces that do the work: a CHECK constraint that rejects out-of-domain values at write time; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Using it

The shipments table is the working surface here.

Key statements

CREATE TABLE shipments (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    tracking_code text NOT NULL CHECK (tracking_code ~ '^[A-Z]{3}-[0-9]{4}$'),
    weight_kg numeric(8,2) NOT NULL CHECK (weight_kg > 0)
);
INSERT INTO shipments (tracking_code, weight_kg) VALUES ('SHP-2026', 2.50);
INSERT INTO shipments (tracking_code, weight_kg) VALUES ('shp-2026', 2.50);

Interactive Tools for This Topic

FAQ

Which tables does this file reference?
`shipments`.