الانتقال إلى المحتوى
قواعد البياناتالـ Data Modeling· 7 دقائق للقراءة

Why Constraints Belong in the Database Even When Your App Validates

Validation explains errors to users. A constraint is the only rule that holds for every writer and every pair of requests that arrive together.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
محتويات المقال

The signup endpoint checks whether an email is taken before it inserts the user, and the validator has unit tests. Still, the users table has two accounts for the same address, created by a double tap on "Create account". In a test on SQL Server 2022, two sessions reproduced it: each checked the email and saw 0 rows, then each inserted, and the table held two rows for mona@example.com. Wrapping each session's check and insert in a transaction at the default isolation level didn't help: the same interleaving committed two rows again.

The common misconception

The belief: if the application validates data before saving it, UNIQUE, FOREIGN KEY and CHECK constraints are redundant.

The reasoning sounds solid. The validation layer is where the rules live in code, covered by tests and returning clear messages per field. A database error arrives late, as an ugly exception. Constraints look like the same rule written twice, in migrations nobody likes to touch, and some teams treat the database as plain storage behind an ORM. Validation is genuinely needed. It just can't do a constraint's job.

What actually happens

A check and a write are two separate moments

The application's check reads the table at one moment, and the insert writes at another. Two requests for the same email can both read before either one writes: a classic . A transaction doesn't close that gap at READ COMMITTED, SQL Server's default: Microsoft's table lists phantoms as allowed at that level, and a row that appears after you looked for it is exactly that. A UNIQUE constraint closes the gap because the database checks uniqueness as part of the insert itself, against a unique index it creates for the constraint. In the test, with the constraint in place, the second session's insert failed with error 2627 and the table kept one row.

Your application isn't the only writer

Data arrives through admin scripts, bulk imports, a second service, a background job, a support tool, a migration that backfills a column, or a new endpoint whose author forgot the validator. Validation protects the code path it lives in. A constraint applies to every statement, whoever sends it: PostgreSQL's docs say an error is raised whenever someone tries to store data that violates a constraint, even when the value came from a column default. Constraints also outlive the code. Applications get rewritten; the data stays.

What each constraint guarantees

  • PRIMARY KEY and UNIQUE: no two rows share the key. SQL Server creates a unique index to enforce each one.
  • FOREIGN KEY: . In the test, inserting an order for a missing customer and deleting a customer who still had orders both failed with error 547.
  • CHECK: a condition each row must meet. In the test, CHECK (Quantity > 0) rejected a quantity of 0 with error 547.
  • NOT NULL: the column always has a value.

Where constraints stop

A CHECK rejects only expressions that evaluate to false, and a comparison with NULL evaluates to unknown, so NULL passes. A CHECK also sees one row at a time: SQL Server doesn't validate CHECK constraints on DELETE, and PostgreSQL doesn't support CHECK constraints that read other rows. Rules across rows, like "the order total equals the sum of its lines", stay in your code. NULL in a unique column differs by database: SQL Server allowed one NULL and rejected the second with error 2627 in the test, while PostgreSQL treats nulls as distinct unless you add NULLS NOT DISTINCT. And neither database creates an index on the referencing columns of a foreign key. The PostgreSQL behavior here comes from its docs; only SQL Server ran for this article.

Keep the validation, add the guarantee

C#
using Microsoft.EntityFrameworkCore;static async Task<IResult> SignUp(SignUpRequest req, AppDb db){    // Check, then insert: two concurrent requests both pass the check    if (await db.Users.AnyAsync(u => u.Email == req.Email))        return Results.Conflict("Email already registered");    db.Users.Add(new User { Email = req.Email });    await db.SaveChangesAsync(); // SQL test: both inserts succeeded    return Results.Created();}

In EF Core, HasIndex(u => u.Email).IsUnique() creates a unique index rather than a constraint, so SQL Server reports error 2601 instead of 2627; the test produced both, and the filter catches either. For a table that already exists, find the violations before you add the rule:

SQL constraints.sql
-- Adding the constraint over duplicates failed in the test with Msg 1505SELECT Email, COUNT(*) AS CopiesFROM dbo.Users GROUP BY Email HAVING COUNT(*) > 1;ALTER TABLE dbo.Users ADD CONSTRAINT UQ_Users_Email UNIQUE (Email);ALTER TABLE dbo.OrderLines ADD CONSTRAINT CK_OrderLines_Quantity    CHECK (Quantity > 0);ALTER TABLE dbo.Orders ADD CONSTRAINT FK_Orders_Customers    FOREIGN KEY (CustomerId) REFERENCES dbo.Customers (Id);
SituationApplication validationDatabase constraint
Two requests at the same momentBoth can pass (tested: two rows)The second write fails (tested: error 2627)
Scripts, imports, other servicesSkipped unless they call your codeChecked on every statement
Message for the userFriendly, per fieldGeneric; you translate it
Rules across rows or external systemsCan express anythingRow-level CHECK, plus UNIQUE and foreign keys
A rewrite of the applicationRules leave with the old codeRules stay with the data

How to apply it in your project

  1. List the invariants of each tableWrite down what must always be true: unique emails, positive quantities, orders that point at real customers, an end date after the start date. Each one is a candidate for UNIQUE, CHECK, FOREIGN KEY or NOT NULL.
  2. Find existing violations firstBy default, adding a constraint checks the rows already there: in the test, UNIQUE failed on a duplicate, and CHECK and FOREIGN KEY failed on a bad row. Query for duplicates, orphans and out-of-range values, and clean them up in the same migration.
  3. Declare the rules where the schema livesIn EF Core, use HasIndex(...).IsUnique() and ToTable(t => t.HasCheckConstraint(...)). A foreign key constraint doesn't index its column; EF Core adds that index by convention, but hand-written schemas need their own.
  4. Translate violations into responsesCatch unique violations (2601, 2627) and turn them into a 409 Conflict, and map error 547 by constraint name. Keep the friendly validation in front; the constraint is the backstop.

Key takeaways

  • Validation and constraints aren't duplicates: one explains errors to users, the other keeps the data true for every writer.
  • A check followed by an insert is a race; in the test, two sessions both inserted the same email, even inside transactions.
  • A UNIQUE constraint checks during the insert itself, so the second session failed with error 2627.
  • Constraints have limits: CHECK passes NULL and sees one row, and NULL in a unique column differs between SQL Server and PostgreSQL.
  • Add constraints after cleaning existing violations, name them, and map their errors to clear responses.

📚 المصادر

  1. Unique constraints and check constraints — SQL Server, Microsoft Learn
  2. Primary and foreign key constraints — SQL Server, Microsoft Learn
  3. Constraints — PostgreSQL documentation
  4. Indexes (uniqueness and check constraints) — EF Core, Microsoft Learn

التعليقات (0)