📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What constraints does SQL Server give you — primary key, foreign key, unique, check, default and NOT NULL — and why would you enforce business rules in the database rather than only in your .NET code?

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.

Junior Theory Beginner constraints data-integrity database-design ef-core foreign-keys sql-server

🎯 Key points

  • PRIMARY KEY: unique, NOT NULL, creates a clustered index by default
  • UNIQUE: creates a unique index; allows one NULL in SQL Server
  • FOREIGN KEY: prevents orphans; SQL Server creates no index (EF Core migrations add one)
  • CHECK: same-row rule only; NULL passes; no other rows or tables
  • DEFAULT and NOT NULL: guarantee a value exists
  • Database is the last line of defence for every writer and for races
  • Trusted constraints let the optimiser simplify plans
  • Map errors 2627/2601/547 to 409 or 400 in .NET

⏱ 30-second answer

SQL Server constraints are rules the engine enforces on every write from every client:

  • PRIMARY KEY: unique and NOT NULL; creates a clustered index by default.
  • UNIQUE: no duplicates; backed by a unique index (allows one NULL).
  • FOREIGN KEY: the value must exist in the parent; blocks orphans; does not create an index for you.
  • CHECK: a row-level condition such as Quantity > 0 (NULL passes).
  • DEFAULT and NOT NULL: a value always exists.

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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."


The constraint types

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

App validation vs database constraints

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

Error numbers to map in .NET

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)

Production example

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.

🔍 What the interviewer is checking

Checks that a junior knows the constraint types, their side effects (indexes) and the reasons to enforce integrity in the database.

Green flags

  • Knows a PK creates a clustered index by default and an FK creates no index
  • Gives the race-condition argument for unique constraints
  • Mentions other writers besides the application
  • Knows how to handle constraint errors in .NET

Red flags

  • "The ORM handles that"
  • Thinks constraints are only documentation
  • Does not know what a foreign key prevents

📚 Learn in depth

1. What each constraint is under the hood

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

2. Foreign keys do not index themselves

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.

3. NULL semantics

  • A CHECK passes when it evaluates to UNKNOWN, so CHECK (Quantity > 0) lets NULL through unless the column is NOT NULL.
  • A UNIQUE constraint in SQL Server treats NULLs as equal, so only one NULL is allowed. For "unique when present", use a filtered unique index: CREATE UNIQUE INDEX ... WHERE TaxFileNumberHash IS NOT NULL.

4. Trusted constraints help the optimiser

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.

5. Naming and migrations

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.

6. The cost

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.

Try it yourself

  1. Create Customers and Orders with a foreign key, then insert an order for a customer that doesn't exist and read error 547.
  2. Insert two NULL emails into a table with a UNIQUE constraint, then replace it with a filtered unique index and try again.
  3. Write a query that joins Orders to Customers but selects only order columns; compare the actual plan with the FK trusted and after ALTER TABLE ... NOCHECK CONSTRAINT.
  4. In a .NET test, catch SqlException with Number == 2627 and map it to a 409 result.

💻 Code

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
    };
}

⚠ Common mistakes

  • Mistake: Relying only on app validation to stop duplicates. Why it is wrong: two concurrent requests both pass the check. Instead: a unique constraint or unique index, with error 2627/2601 mapped to 409.
  • Mistake: Assuming a foreign key creates an index. Why it is wrong: SQL Server does not (EF Core migrations add one by convention, hand-written DDL often doesn't); parent deletes then scan the child table. Instead: index every foreign key column you delete or join through.
  • Mistake: Writing CHECK (Quantity > 0) on a nullable column and expecting NULL to fail. Why it is wrong: UNKNOWN passes a check. Instead: add NOT NULL.
  • Mistake: Using a CHECK constraint with a scalar function to look at other rows or tables ("no overlapping bookings"). Why it is wrong: a CHECK only sees the row being written; a UDF-based check runs per row, is slow, and misses concurrent writes and changes to the other table. Instead: a unique or filtered index, an indexed view, or a locked check in the write path.
  • Mistake: Letting SQL Server generate constraint names. Why it is wrong: names differ per database and break drop scripts. Instead: name every constraint.
  • Mistake: Re-enabling constraints 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 ....
  • Mistake: Using a plain UNIQUE constraint for an optional column. Why it is wrong: SQL Server allows only one NULL. Instead: a filtered unique index WHERE col IS NOT NULL.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions column types or lengths while describing NOT NULL and defaults. Why: Checks awareness of how column types affect indexes and constraints.
    How to answer

    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.

  2. When: Candidate mentions cascade delete on foreign keys. Why: Checks understanding of SQL Server's multiple cascade path restriction.
    How to answer

    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.

  3. When: Candidate mentions disabling constraints for a bulk load. Why: Checks knowledge of WITH NOCHECK and the optimiser's use of trusted constraints.
    How to answer

    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.

↩ Usually asked after

More in Database Design

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me