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.
Code
-- 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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
FAQ
- Which tables does this file reference?
- `shipments`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.