How do you ensure data integrity in a relational database?

Instruction: Discuss mechanisms and constraints used to maintain data integrity.

Context: This question assesses the candidate's understanding of data integrity principles and their ability to apply them through SQL constraints and other means.

Updated

Official answer

Start with explicit invariants and enforce them at the appropriate boundary:

  • A primary key uniquely identifies a row. It does not prevent two different keys from representing the same real-world entity; a separate business-key uniqueness rule may be needed.
  • Foreign keys enforce the configured relationship. A nullable foreign key can still be absent, so combine it with NOT NULL when every row must have a parent.
  • UNIQUE, NOT NULL and CHECK constraints encode other permitted states. In PostgreSQL, a check that evaluates to unknown because of NULL does not reject the row; use explicit nullability rules.
  • Transactions and suitable concurrency control keep related changes consistent. Checking a condition in application code before writing is insufficient if another transaction can change it between the check and write.

Normalize where it prevents update anomalies, while recognizing that a schema cannot prove source facts are true. Validate inputs, restrict write privileges, track actionable changes and investigate reconciliation failures. Avoid automatic repairs that invent an unknown value.

Backups support recovery rather than preventing incorrect writes. Test restoration and identify a trustworthy recovery point; a backup can contain the same bad data as the live system.

Assessment: Give concrete invariants, explain null and concurrency behavior, and distinguish structural validity from business accuracy.

Related Questions