You enforce relational integrity by defining the rules that keep data consistent as part of the database schema itself—primary keys, foreign keys, unique and check constraints, NOT NULL declarations, and appropriate data types—and then making sure every application path writes through those rules rather than around them. The database, not the application code, should be the final authority on whether a row is valid. In practice, that means two things done together: model the relationships correctly and let the database engine enforce them at write time. Applications still validate input for good user experience, but those checks are a convenience; the constraints are the guarantee.

The phrase "relational integrity" covers several distinct guarantees, and each is enforced by a different mechanism. Understanding the distinctions matters because a schema can look normalized and still permit orphaned rows, duplicate business keys, or null values that break joins.

The constraints that do the actual enforcement

Integrity enforcement in a relational database rests on a small set of constraint types. Each one expresses a rule the engine checks on insert, update, and delete.

Primary keys identify each row uniquely and are declared NOT NULL by definition. Every table that represents an entity should have one, even when a natural key such as an email address seems unique—natural keys change. A surrogate key (an auto-incrementing integer, a sequence-generated value, or a UUID) gives you a stable identifier that foreign keys can point to without cascading updates when business data changes.

Foreign keys are the core of relational integrity. A foreign key on order.customer_id referencing customer.id means the engine rejects an order whose customer doesn't exist. Foreign keys also define what happens when the parent row is deleted or its key changes: RESTRICT or NO ACTION blocks the delete, CASCADE propagates it, SET NULL clears the reference, and SET DEFAULT assigns a fallback. The default is usually NO ACTION, which is often the safest choice—silent cascading deletes are a common source of accidental data loss in production.

Unique constraints prevent duplicate values in a column or combination of columns. They enforce business keys like "one account per email address" at the storage layer. Note that a plain unique constraint typically treats multiple NULLs as distinct; if you need at-most-one-non-null semantics, that requires a partial index (in PostgreSQL, a unique index with a WHERE clause) or a filtered index in SQL Server.

Check constraints encode rules about a single row: quantity > 0, end_date >= start_date, status IN ('pending','shipped','cancelled'). They catch impossible values without application code.

NOT NULL constraints prevent missing data in columns that have no meaningful default. They matter for integrity because a nullable foreign key silently permits a "relationship" that points nowhere.

Data types and domains are constraints too. Storing a date in a DATE column instead of a free-text field, or using a DECIMAL type for money instead of a float, prevents whole categories of corruption before any explicit constraint fires.

A compact comparison helps keep these straight:

Constraint What it guarantees Typical example
Primary key Unique, non-null row identity customer.id
Foreign key Child reference resolves to a parent row order.customer_id → customer.id
Unique No duplicate values (or combinations) One row per email
Check Row-level predicate holds quantity > 0
NOT NULL Value is always present order.placed_at

Model relationships before you add constraints

Constraints enforce the model you give them; they cannot fix a wrong one. Before writing DDL, decide for each relationship whether it is one-to-many, many-to-many, or one-to-one, and whether the child can exist without the parent.

A one-to-many relationship is expressed by a foreign key on the "many" side pointing to the "one" side. A many-to-many relationship needs a junction table with foreign keys to both sides and, usually, a composite primary key or unique constraint on the pair so the same link can't be inserted twice. A one-to-one relationship can be modeled with a foreign key plus a unique constraint on the referencing column, which prevents two child rows from pointing at the same parent.

Optional relationships are where intent must be explicit. If an order must always have a customer, declare customer_id NOT NULL with a foreign key. If an order may be placed by a guest, NULL is legitimate—but then document it, because analytics and joins will need to handle it. The constraint should mirror a business decision, not an accident of defaults.

Use deferrable constraints and transactions for multi-row rules

Some integrity rules span more than one row or table and cannot be expressed as a simple constraint. A classic case: a transfer that debits one account and credits another must not leave the ledger unbalanced, and the intermediate state during the two writes is temporarily inconsistent.

The practical answer is to wrap the related writes in a transaction and rely on the ACID properties—atomicity ensures the whole unit commits or rolls back, and isolation keeps other sessions from observing the partial state. Some engines let you declare foreign keys and unique constraints as DEFERRABLE INITIALLY DEFERRED, which postpones the check until commit; this is useful for circular references, such as two tables that reference each other and must be inserted together. But deferral is a sharp tool: it widens the window during which the database holds an invalid state, so use it narrowly.

For rules that genuinely span tables and are not expressible as constraints (for example, "a shipment cannot exceed the ordered quantity minus prior shipments"), there are three options: a trigger that raises an exception, a stored procedure that owns the write path, or an application-level check inside the same transaction. Triggers guarantee enforcement for every writer but are hard to debug and can surprise developers; application checks are easier to read but fail the moment another service writes to the same table. Many teams choose triggers for critical invariants and application logic for everything else, and that trade-off should be a deliberate decision.

Make the database the boundary, not one of several

The most common way relational integrity breaks in real systems is not a missing constraint—it's an application that bypasses the constraints that exist. A reporting job that bulk-loads with constraints disabled, a migration script that writes directly to a table, a second service with its own ORM that ignores a check constraint, or a developer who "temporarily" drops the foreign key to make a deploy succeed—each of these creates the orphaned and duplicated data the constraints were supposed to prevent.

Enforcement therefore has an operational side. Keep foreign keys and checks in place in every environment that matters, including staging; a constraint that exists only in production will be violated first in development and then discovered late. Grant write privileges narrowly so bulk jobs and ad-hoc queries can't quietly skip the rules. Audit for orphaned rows periodically with queries that look for children without parents, and treat any result as a defect.

On the application side, the right pattern is defensive but not redundant in the wrong direction. Validate input in the application to produce friendly error messages and to reject obviously bad requests early. Then let the database constraints catch anything the application misses, and translate the resulting constraint-violation errors into clear responses. Recognize that some rules—uniqueness under concurrency especially—cannot be reliably enforced in application code alone. Two requests can both check "is this email taken?" and both pass before either inserts. A unique constraint resolves the race; application logic cannot.

Handle deletion and change with explicit intent

Deletion policy is where relational integrity decisions have the most visible consequences. Ask, for each relationship: if the parent disappears, should the child disappear, become orphaned-but-valid, or block the deletion?

CASCADE is convenient for genuinely dependent data—order line items that have no meaning without their order. RESTRICT is appropriate for data with independent value—a customer with historical orders should not vanish because someone deleted the customer record; deactivate the customer instead. SET NULL fits optional associations, such as a task whose assigned user has left the company, if the task itself must survive. Mixed policies within one schema are normal; what matters is that each one was chosen on purpose and documented.

The same reasoning applies to key changes. If you use natural keys as primary keys, updates to those keys must cascade to children or be forbidden. Surrogate keys sidestep this entirely, which is one reason they're the common default.

Recognize where relational integrity stops

Relational integrity is enforced within a single database. The moment data crosses a boundary—a microservice with its own database, a message queue, a data warehouse fed by nightly extracts—the foreign keys no longer apply and integrity becomes a distributed-systems problem. Constraints cannot span two databases, so cross-service consistency requires sagas, outbox patterns, idempotent consumers, and reconciliation jobs. A foreign key between services is a fiction.

The same limit applies to external data. A foreign key can guarantee that order.customer_id exists in customer, but not that it refers to a real person in the CRM. That is referential integrity in the formal sense—the reference resolves inside the schema—and it is worth being precise about the difference, because the search for "enforce relational integrity" sometimes means "make sure the data is true," which no constraint can deliver.

Soft deletes deserve a caution as well. Marking rows with a deleted_at timestamp maintains history but breaks the simple assumption behind foreign keys: the parent still exists physically, so the constraint passes even though the business considers it gone. If you use soft deletes, enforce their semantics with partial indexes and queries, and decide explicitly whether a child may reference a soft-deleted parent.

A practical checklist

For a schema you are designing or reviewing, these steps cover the enforcement decisions that matter:

1: Give every entity table a primary key, preferably a stable surrogate key. 2: Declare every relationship with a foreign key, and choose ON DELETE and ON UPDATE behavior deliberately. 3: Add unique constraints for every business key, including composite ones in junction tables. 4: Add check constraints for range, format, and cross-column rules within a row. 5: Make columns NOT NULL unless null has a defined business meaning. 6: Choose precise data types: dates as dates, money as fixed-precision decimals, enums as constrained values. 7: For multi-row invariants, use transactions plus triggers or a stored-procedure write path, and document why. 8: Keep constraints enabled in all environments, restrict broad write access, and run orphan-detection queries as routine checks. 9: Accept that cross-database and cross-service consistency needs a different toolkit.

Enforcing relational integrity is less about any single feature and more about a discipline: express rules as constraints wherever the engine can check them, choose the constraint that matches the business rule rather than the one that's convenient, and make sure nothing in your operations quietly writes around them. Do that, and the database will refuse to hold data that contradicts its own rules—which is exactly what integrity enforcement is for.