Full answer
Arguments for the database:
- Every client, script and admin tool is subject to the same rules.
- Set-based operations (recalculating totals for a million rows) run without network round trips.
- Constraints are declarative and cannot be bypassed.
Arguments for the application:
- Familiar languages, test frameworks, debugging and code review.
- Easier deployment and rollback than coordinated database migrations.
- Logic involving external services (email, payments) cannot live in the database anyway.
- Fewer database-specific features, which eases migrations between engines.
A balanced rule: declare integrity in the schema (NOT NULL, CHECK, UNIQUE, foreign keys, exclusion constraints), keep business workflows in the application, and use database functions selectively for performance-critical set operations or for security boundaries (functions that expose a narrow operation instead of table access). Keep database code in version control with migrations either way.
Key points
- Integrity rules belong in constraints
- Workflows fit application code
- Procedures help set-based heavy work
- Database code needs version control too
- Functions can narrow access for security
Common mistakes
- Putting all logic in procedures that nobody can test
- Enforcing integrity only in one application
Follow-ups
- How would you test a stored function?
- When do triggers become a maintenance problem?
Tips
- Separate integrity from workflow