Covers each SQL Server constraint type, what it enforces and creates (indexes), how they help the optimiser, and why rules belong in the database as well as in application validation.
SQL Server constraints are rules the engine enforces on every write from every client:
Quantity > 0 (NULL passes).I validate in .NET for good error messages, but enforce in the database because other writers exist (scripts, jobs, other services) and race conditions slip past app checks. The cost is a little write overhead and needing to translate constraint errors into friendly responses.
"Constraints are the database's own rules. A primary key guarantees each row is identifiable: unique and not null, and by default SQL Server builds the clustered index on it. A unique constraint stops duplicates in other columns, like a customer's email, and is backed by a unique index. A foreign key says an order's CustomerId must exist in Customers, so you can't create orphans or delete a customer who still has orders, unless you choose cascade. Check constraints enforce row-level rules like quantity greater than zero or end date after start date, and default plus not null make sure a column always has a value.
The reason I put them in the database and not only in my FluentValidation or EF Core model is that the application isn't the only writer. There's a data fix someone runs in SSMS, a nightly import, a second service. And even inside one app, two requests can both check 'is this email free?' at the same moment and both insert. Only a unique index catches that race. A bonus is that the optimiser uses trusted constraints: a trusted foreign key lets it remove a join it doesn't need, and a check constraint can let it skip a table entirely.
The mistake I see is the opposite assumption, that the ORM handles integrity. EF Core will happily generate a schema without the unique index you meant to have. So I validate in the app for friendly messages, enforce in the database for correctness, and map constraint violation errors, like 2627 and 2601 for duplicates and 547 for a foreign key or check failure, to proper 409 or 400 responses."
| Constraint | Enforces | Creates an index? | Notes |
|---|---|---|---|
| PRIMARY KEY | Unique, NOT NULL | Yes, clustered by default | One per table |
| UNIQUE | No duplicate values | Yes, unique non-clustered | One NULL allowed; use a filtered unique index for "unique when not null" |
| FOREIGN KEY | Value exists in parent | No | Index the FK column yourself |
| CHECK | Boolean condition per row | No | NULL evaluates to unknown and passes |
| DEFAULT | Value when none supplied | No | Not a rule; a convenience |
| NOT NULL | A value must exist | No | The cheapest constraint there is |
| Layer | Good for | Cannot do |
|---|---|---|
| FluentValidation / model validation | Friendly messages, early rejection, cross-field rules | Stop other writers, prevent races |
| Database constraints | Guaranteed integrity for every writer, concurrency-safe uniqueness | Pretty error messages, rules needing external data |
| SQL error | Meaning | HTTP response |
|---|---|---|
| 2627 | Unique or primary key constraint violation | 409 Conflict |
| 2601 | Duplicate key in a unique index | 409 Conflict |
| 547 | Foreign key or check constraint conflict | 400 or 409 |
| 515 | Cannot insert NULL | 400 (usually a bug) |
A sign-up endpoint [in a system you worked on] checked for an existing email before inserting. Under a marketing spike, about [0.3]% of sign-ups created duplicate accounts because two requests passed the check at once. A unique index on Email plus mapping error 2627/2601 to 409 Conflict ended the duplicates; the cleanup script merged [N] accounts.
Checks that a junior knows the constraint types, their side effects (indexes) and the reasons to enforce integrity in the database.
Green flags
Red flags
Primary key and unique constraints are indexes with a uniqueness flag; the constraint is metadata on top. Foreign keys, check, default and NOT NULL are checked by the query processor during the write.
INSERT INTO Orders ...
│
├─ NOT NULL / CHECK → evaluated on the new row
├─ UNIQUE / PK → seek in the unique index; duplicate → error 2627/2601
└─ FOREIGN KEY → seek in the parent's PK index; missing → error 547
DELETE FROM Customers WHERE CustomerId = 42
└─ FOREIGN KEY → look for children in Orders(CustomerId)
no index on Orders.CustomerId → table scan
SQL Server does not create an index on the referencing column. Deletes and key updates on the parent then scan the child table to check for references, which is slow and takes many locks. EF Core migrations do create an index for each foreign key by convention, but hand-written DDL often does not.
CHECK (Quantity > 0) lets NULL through unless the column is NOT NULL.CREATE UNIQUE INDEX ... WHERE TaxFileNumberHash IS NOT NULL.When a foreign key is trusted (is_not_trusted = 0), SQL Server knows every child row has a parent, so a query that joins Orders to Customers but selects only Orders columns can skip the join entirely (join elimination). A trusted check constraint such as CHECK (Region = 'AU') lets the optimiser return no rows without reading the table for WHERE Region = 'NZ'. A constraint created or re-enabled WITH NOCHECK is untrusted and gives no such help.
Unnamed constraints get generated names like CK__OrderLine__Quant__3B75D760, which differ on every database. Migration scripts that drop them then fail. Name every constraint: PK_Orders, FK_Orders_Customers, CK_OrderLines_Quantity, UQ_Customers_Email, DF_Orders_CreatedAt.
Each constraint adds a small amount of work per write: a seek per foreign key, an index maintenance per unique constraint. For normal OLTP volumes this is microseconds and worth it. On very large bulk loads, teams sometimes disable constraints and re-enable them WITH CHECK afterwards so they become trusted again.
Customers and Orders with a foreign key, then insert an order for a customer that doesn't exist and read error 547.Orders to Customers but selects only order columns; compare the actual plan with the FK trusted and after ALTER TABLE ... NOCHECK CONSTRAINT.SqlException with Number == 2627 and map it to a 409 result.Named constraints on an orders schema.
CREATE TABLE dbo.Customers
(
CustomerId int IDENTITY CONSTRAINT PK_Customers PRIMARY KEY,
Email nvarchar(256) NOT NULL CONSTRAINT UQ_Customers_Email UNIQUE,
CreatedAt datetime2(3) NOT NULL CONSTRAINT DF_Customers_CreatedAt DEFAULT SYSUTCDATETIME()
);
CREATE TABLE dbo.Orders
(
OrderId int IDENTITY CONSTRAINT PK_Orders PRIMARY KEY,
CustomerId int NOT NULL
CONSTRAINT FK_Orders_Customers REFERENCES dbo.Customers (CustomerId),
Status tinyint NOT NULL CONSTRAINT CK_Orders_Status CHECK (Status BETWEEN 0 AND 4),
StartsOn date NOT NULL,
EndsOn date NULL,
CONSTRAINT CK_Orders_Dates CHECK (EndsOn IS NULL OR EndsOn >= StartsOn)
);
-- Foreign keys don't index themselves: add it, or parent deletes scan Orders.
CREATE INDEX IX_Orders_CustomerId ON dbo.Orders (CustomerId);
Mapping constraint violations to HTTP results in ASP.NET Core.
namespace Shop.Api;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
public static class ConstraintErrors
{
// Validation gives friendly messages; this catches what only the database can see (races, other writers).
public static IResult ToResult(DbUpdateException ex) => ex.InnerException switch
{
SqlException { Number: 2627 or 2601 } => Results.Conflict(new { error = "That email is already registered." }),
SqlException { Number: 547 } => Results.BadRequest(new { error = "A referenced record does not exist or a rule was broken." }),
_ => throw ex
};
}
CHECK (Quantity > 0) on a nullable column and expecting NULL to fail. Why it is wrong: UNKNOWN passes a check. Instead: add NOT NULL.WITH NOCHECK after a bulk load. Why it is wrong: the constraint stays untrusted and the optimiser ignores it. Instead: ALTER TABLE ... WITH CHECK CHECK CONSTRAINT ....WHERE col IS NOT NULL.Constraints are cheap insurance. App validation is for the user; database constraints are for the data. Treat constraint errors as expected outcomes and map them, rather than trying to pre-check everything in code.
The limits matter too: constraints express rules about a row (CHECK), a column set (UNIQUE) or a reference (FOREIGN KEY). Rules across many rows ("no overlapping bookings", "at most 5 active sessions") need an index-backed design or a locked write path; triggers can do it but hide logic and add write latency on every statement.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Database constraint | Rules about the data itself (uniqueness, existence, ranges) | Small per-write cost | Rules needing external systems |
| App validation | User-facing messages, cross-aggregate or external checks | Not race-safe | As the only guard for uniqueness |
| Trigger | Rules spanning rows or tables that constraints cannot express | Hidden logic, harder to test, write latency | Anything a constraint can do |
An nvarchar(max) column cannot be a key column of a B-tree index (clustered or non-clustered); it can only sit in INCLUDE or a full-text index, so a lookup on it scans. Values that do not fit in the row (over 8,000 bytes) move to LOB pages, so reading them costs extra I/O, and online index operations were historically restricted. The optimiser also estimates row size from the declared type, assuming a max column is about half-full of a large value, so sorts and hash joins get oversized memory grants that waste memory and reduce concurrency. EF Core maps an unconfigured string to nvarchar(max), so the fix is to give strings realistic lengths with HasMaxLength, a convention, or [MaxLength], and keep max for genuine documents.
It is SQL Server error 1785: SQL Server refuses a foreign key with ON DELETE CASCADE when the table can already be reached by another cascade path, or the cascade would form a cycle. EF Core makes required relationships cascade by default, so a model like Company → Projects → Tasks plus Company → Employees → Tasks triggers it. Fix it by choosing which path really owns the delete and setting the other relationship to DeleteBehavior.Restrict or DeleteBehavior.NoAction (both emit ON DELETE NO ACTION on SQL Server; ClientCascade is an option if EF Core should delete loaded dependents itself). Then delete the dependents explicitly in the use case, often with ExecuteDelete, or switch to soft delete: an IsDeleted flag or DeletedAt column plus a global query filter, so nothing is physically removed. Wide cascades also lock many rows in one transaction, so avoiding them helps performance.
A constraint is untrusted when is_not_trusted = 1 in sys.foreign_keys or sys.check_constraints. It happens when it is created WITH NOCHECK, or re-enabled with ALTER TABLE ... CHECK CONSTRAINT (which defaults to WITH NOCHECK), typically after a bulk load or a migration that disabled constraints.
Effects: new writes are still checked, but existing rows were never validated, so orphans or invalid values may already be there and reports or joins can return wrong results. The optimiser cannot rely on it, so it loses join elimination and contradiction detection.
Fix: find the violating rows (e.g. LEFT JOIN to the parent where it is NULL), delete, correct or re-parent them, then run ALTER TABLE t WITH CHECK CHECK CONSTRAINT c. It scans the table under a schema lock, so schedule it off-peak on large tables.
Last updated 23 Nov 2026.