Quick revision
The short answer
I would focus where errors cost the most: inventory the critical flows (money, inventory, identity) and add constraints there first, incrementally and without downtime (NOT NULL, CHECK, foreign keys added NOT VALID and then validated, unique indexes built concurrently). Alongside that, automated data quality checks with alerts and owners catch what constraints cannot, schema changes go through reviewed Flyway or Liquibase migrations with a constraints checklist, and progress is reported as fewer data incidents and fewer manual finance fixes.
What to remember
In this answer, we raised integrity standards without a delivery freeze: inventory the money, inventory and identity flows and constrain them first; add NOT NULL, CHECK, foreign keys and unique indexes using NOT VALID, VALIDATE and CONCURRENTLY so writes keep flowing; add automated reconciliation and orphan checks with owners for rules constraints cannot express; make reviewed migrations with a checklist and CI linter the normal path; and measure success as fewer data incidents and manual finance fixes.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
I would focus where errors cost the most: inventory the critical flows (money, inventory, identity) and add constraints there first, incrementally and without downtime (NOT NULL, CHECK, foreign keys added NOT VALID and then validated, unique indexes built concurrently). Alongside that, automated data quality checks with alerts and owners catch what constraints cannot, schema changes go through reviewed Flyway or Liquibase migrations with a constraints checklist, and progress is reported as fewer data incidents and fewer manual finance fixes.
Why this question is asked
When finance reports are wrong, the problem has become visible to the people who trust engineering least, and the temptation is a big integrity programme that freezes feature work. That rarely survives a quarter. Interviewers ask this question to see whether a senior engineer can improve a systemic weakness while delivery continues. In this answer, we will see why application-only integrity leaks, decide where to start, add constraints safely to live tables, add checks for what constraints cannot express, make the change part of the normal workflow, and measure the outcome.
1Why Integrity in Application Code Leaks
An integrity rule is a statement that must always be true about the data, for example 'every payment belongs to an existing invoice' or 'an invoice total is never negative'. When such rules live only in application code, they hold only for writes that go through that code path, at that version, without races. Every SQL fix, data migration, batch job, new service and concurrent request is a chance to break them.
Constraints declared in the database hold for every writer and are checked atomically with the write. That is why they are the cheapest long-term protection. But a company with many databases cannot add them everywhere at once, and adding them carelessly to large live tables causes outages. So the plan has to be prioritized and incremental.
2Start Where Errors Reach the Money
We begin with an inventory, not a schema crawl. Which data flows feed finance reports? Typically payments, invoices, refunds, orders, inventory movements and customer identity. For each flow we trace the tables involved and ask which incidents of the past year came from them. That gives a short, ranked list.
| Table | Missing rule | Recent impact |
|---|---|---|
| payments | FK to invoices, amount > 0 | Refunds booked against nothing |
| invoice_lines | NOT NULL tax_code, FK to invoices | Tax report off by a few percent |
| customers | Unique tax_id per country | Duplicate customers in revenue split |
| stock_moves | CHECK quantity <> 0, FK to warehouses | Inventory value drift |
Notice the list is small. Ten well-chosen constraints on the money path are worth more than a thousand added to tables nobody reports from, and they produce visible results quickly, which buys support for the next wave.
3Adding Constraints Without Stopping the System
Each kind of constraint has a safe way to add it to a large live PostgreSQL table, so that writes are never blocked for long. The pattern is the same for all of them: first enforce the rule for new data, then check the old data separately.
Before validating, we fix the existing bad rows with the business owners, the same way we would for any data cleanup: classify, decide, record. Validation then proves the cleanup is complete. A useful side effect of NOT VALID is that the bleeding stops on day one, because new bad rows are rejected even while old ones are still being cleaned.
4Checks for What Constraints Cannot Express
Some rules span tables, systems or time: 'payments received today equal the bank statement', 'every shipped order has an invoice within an hour', 'row counts in the warehouse match the source'. No column constraint can say that. So the second track is automated data quality checks: scheduled queries that reconcile against ledgers, detect orphans across databases and compare counts, each with a threshold, an alert and a named owner.
These checks are also how we find out which constraints to add next. If the orphan check on refunds fires every week, that is a candidate for a foreign key in the next wave.
5Making It Part of Normal Delivery
The way to avoid stopping delivery is to fold integrity into work that happens anyway. Schema changes are code: every change is a reviewed Flyway or Liquibase migration in the service's repository, never a manual SQL session. The pull request template for migrations asks a few questions: does every new reference have a foreign key, does every business uniqueness rule have a unique index, are required columns NOT NULL, are amounts checked? A CI linter can enforce the mechanical parts, such as flagging a new _id column without a foreign key or a non-concurrent index build on a large table.
Then each team's next feature that touches a critical table also adds that table's missing constraints. No big-bang project, no freeze, but every sprint the money path gets a little stronger.
- Feature touches a critical tableTicket links the integrity backlog
- Migration adds missing constraintsNOT VALID, then VALIDATE
- Review checklist and CI linterReferences, uniqueness, nullability
- Data quality check added or updatedAlert with an owner
- Incident and fix counts reviewed monthlyReported to finance
5 steps in order. Play them, or step through them one at a time.
6Measuring the Outcome
Leadership and finance care about outcomes, not constraint counts. So we track the number of data incidents reaching finance per month, the number of manual data fixes finance or support had to request, and the hours spent on month-end reconciliation. We report constraint coverage on the critical tables as the leading indicator and incidents as the result. When the month-end close takes one day less, that is the story that keeps the programme going.
7Follow-up questions
What if a team pushes back that constraints will break their releases?
I would show them the NOT VALID approach: the constraint rejects only new bad writes, so if their code produces bad data we learn about it immediately, in a test or staging environment first, rather than in a finance report a month later. I would also pair with them on the first migration so the pattern is proven on their own tables.
Should constraints replace validation in application code?
No, they complement it. Application validation gives users friendly messages and handles complex rules, while constraints are the final guarantee. If both exist, the constraint should almost never fire in production; when it does, it has caught a real bug.
How do you handle databases where the owning team no longer exists?
They go on the inventory with an interim owner, usually the team that consumes the data most. We start with read-only data quality checks there, because they need no schema change, and add constraints once someone can own the migrations.
8Conclusion
In this answer, we raised integrity standards without a delivery freeze: inventory the money, inventory and identity flows and constrain them first; add NOT NULL, CHECK, foreign keys and unique indexes using NOT VALID, VALIDATE and CONCURRENTLY so writes keep flowing; add automated reconciliation and orphan checks with owners for rules constraints cannot express; make reviewed migrations with a checklist and CI linter the normal path; and measure success as fewer data incidents and manual finance fixes.
Open with
I would avoid a big integrity programme that stops delivery and instead make it targeted and continuous. First, an inventory of the flows that feed finance: payments, invoices, refunds, inventory movements and customer identity.
Then, if they want more
For each, I would look at the past year's incidents and rank the missing rules, so the first wave is maybe ten constraints on the money path. Second, add them incrementally in ways that do not block writes.
In PostgreSQL, check constraints and foreign keys go in as NOT VALID, which stops new bad rows immediately, and after cleaning up old rows with the business owners I run VALIDATE CONSTRAINT, which scans without blocking normal writes. Unique rules get a unique index built concurrently and attached as a constraint, and NOT NULL goes through a validated check first.
Third, constraints cannot express cross-system rules, so I would add automated data quality checks, like reconciliation against the payment ledger, orphan detection and row count comparisons, each with an alert and an owner.
Fourth, treat schema as code: every change is a reviewed Flyway or Liquibase migration, with a checklist and a CI linter for foreign keys, uniqueness and nullability, and teams add missing constraints whenever a feature touches a critical table. Finally, I would report outcomes finance cares about: fewer data incidents reaching reports, fewer manual fixes and a shorter month-end close.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, MySQL reference manual
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Your company has many databases where integrity is enforced only in application code...": https://scrivio-interview-library.netlify.app/databases/data-modeling/4be4f32bcd/