Databases · Flashcard

Why enforce a business invariant in the database rather than only in application code?

  • AEvery client and code path is covered — no service, script, or migration can write around the rule
  • BThe rule runs faster than in the application — the planner rewrites the check into an index scan
  • CThe rule can be changed without a migration — constraints are metadata and skip the DDL path
  • DThe rule removes the need for transactions — constraint checks take the locks that writers need

Why this is the answer

An invariant declared once in the schema holds for the API, the batch job, and the psql session at 2 a.m., with no coordination between teams — that reach is the argument, not raw speed. Constraint checks are not turned into index scans, changing a constraint is itself DDL, and constraints assume transactions rather than replacing them.

Official docs
Study in Gnoseed →