October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

I Made PostgreSQL Refuse to Store a Lie: Enforce Data Rules with Constraints

PostgreSQL constraints turn defined data rules into schema-level enforcement, rejecting writes that violate them across application paths.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

PostgreSQL can reject a write that violates a rule you have encoded in the database schema. The practical move is to express the business invariant as a constraint, so inserts and updates from any application path must satisfy it—not just the one you remembered to validate.

That “lie” is a value that breaks a defined rule, not necessarily a deliberate falsehood. Constraints cannot determine whether data is true in the real world; they can enforce precise conditions you specify.

As an Amazon Associate I earn from qualifying purchases.

What it means to make PostgreSQL refuse a lie

A constraint makes a data rule part of the table definition. PostgreSQL’s version 18 documentation says that a write violating a constraint raises an error, rather than storing the offending row. That gives the rule a single enforcement point even when data arrives through different application code paths. PostgreSQL 18: Constraints

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Start with the invariant in ordinary language: for example, “a product price must be zero or greater.” Then choose the constraint whose scope matches that statement. A schema rule can reject a value that is impossible under your model; it cannot verify that the price matches a real-world invoice or that a person entered an honest name.

Choose the constraint that matches the rule

Rule Constraint What it enforces
A value must be present NOT NULL Rejects null for that column.
A row’s value or combination of values must meet a condition CHECK Evaluates a condition against the row being inserted or updated.
A value or combination must not repeat UNIQUE Rejects duplicate key values according to the constraint’s null semantics.
A table needs a unique, non-null row identifier PRIMARY KEY Combines uniqueness and non-null requirements; a table can have only one primary key.
A reference must identify an existing key in another table FOREIGN KEY Maintains referential integrity, subject to null behavior and the declared update/delete action.
Two rows must not conflict under selected operators EXCLUDE Requires at least one specified operator comparison for each row pair to be false or null.

A primary key is usually a useful row identifier, but PostgreSQL does not require every table to have one. Both primary keys and unique constraints are backed by indexes that enforce their uniqueness; a primary key gets a unique B-tree index. A foreign key does not automatically create an index on its referencing columns. PostgreSQL 18: Constraints

Write the invariant as a row-level check

For a simple numeric rule, a check constraint can make the invariant explicit in the schema:

CREATE TABLE products (
    product_id bigint PRIMARY KEY,
    price numeric NOT NULL,
    CONSTRAINT products_price_nonnegative CHECK (price >= 0)
);

Now a write with a negative price violates the check and PostgreSQL raises an error:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
INSERT INTO products (product_id, price)
VALUES (1, -5.00);

The example uses two distinct rules. NOT NULL rejects a missing price, while CHECK (price >= 0) rejects a negative one. This distinction matters because PostgreSQL treats a check expression that evaluates to null as satisfied. A check alone therefore does not guarantee presence.

Use other constraint types for relationships and conflicts

Prevent duplicate values

Use UNIQUE when a value or combination of values must not be duplicated. PostgreSQL creates an index to enforce uniqueness. Be deliberate about whether null values are meaningful in the column, because uniqueness semantics concern key values and do not make a column required; use NOT NULL separately when every row needs a value.

Require a referenced row

A foreign key is the appropriate tool when a row must refer to an existing key in another table. The referenced columns must be backed by a primary key, unique constraint, or non-partial unique index. By default, a referencing row can satisfy the foreign key with null in its referencing column or columns, so pair the foreign key with NOT NULL if an absent reference is not allowed. For a composite reference, MATCH FULL requires the referencing columns to be either all null or all non-null.

Choose the foreign key’s update and delete behavior to match the relationship’s lifecycle. Also consider an index on the referencing columns: PostgreSQL does not create one automatically, and it can help when referenced rows are updated or deleted. PostgreSQL 18: Constraints

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Prevent pairwise conflicts

An exclusion constraint can express conflicts that ordinary uniqueness cannot, such as two rows whose values overlap under chosen operators. It is suited to rules about pairs of rows, rather than a simple condition on one row. Choose the operators to represent the conflict precisely; the constraint requires that, for every pair, at least one specified comparison be false or null.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Know what a check constraint cannot guarantee

A CHECK constraint is for a condition on the row being checked. Do not use a check expression that queries other rows or tables to enforce a cross-row invariant: PostgreSQL documents that such checks are not a reliable constraint mechanism. Use a suitable unique, exclusion, or foreign-key constraint when it can model the rule. PostgreSQL 18: Constraints

The key design question is scope: is the rule about one value, one row, a unique key, a related row, or a pair of rows? Selecting a constraint at the same scope as the invariant lets PostgreSQL enforce what it can actually guarantee, without suggesting that the database knows whether arbitrary input is truthful.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.