← Back to SQL, page 24

sql-0474 · Medium mid

Should business rules live in stored procedures or in application code?

Rules that protect data integrity for every client (uniqueness, references, valid states, balances never negative) belong in the database as constraints, and sometimes triggers or functions. Workflow and presentation logic usually belongs in application code, where it is easier to test, version and deploy. Stored procedures pay off for set-based operations that would otherwise move lots of data over the network.

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