The Database Is the Last Line of Defence

D
Dick Edidiong Bassey
·

Application code has bugs. This is not a criticism — it is a fact of engineering. The question is whether that bug can corrupt your data.

Database constraints are the answer. NOT NULL means no application bug can insert null where a value is required. UNIQUE prevents duplicates. FOREIGN KEY prevents orphaned references. CHECK prevents values outside valid ranges.

I add database constraints that mirror application-layer validation for every field with correctness requirements. The application validates for user experience. The database validates for correctness.

Trust the database more than the application. The database is still there after every code deployment.

— Dick Bassey | DevDick | 2023