views:

35

answers:

3

Should items like Foreign Keys, Constraints, Default Values, etc be handled by the Database management system (in this case, MS Sql 2005) or the Application? I have heard opinions from both sides and I'm honestly not sure which way to go.

I originally was going to build it into the database, however I have discovered this is not always possible with the current database design I have. For example, some tables contain circular references and cannot be linked using ON UPDATE CASCADE. Another problem I'm encountering is there is a possibility we will be using multiple databases/servers and Foreign key constraints don't work across linked servers.

I had some developers recommend I do the data validation on the application layer and leave the database as just that - a place to store data. I like the idea, but I've read in a lot of places that it is better to build referential integrity into the database to allow for transactions that don't get passed through the application layer. I agree with that, although when we are finished all database transactions should be going through the application. Even if we decide to build addins later on, we are using an ObjectModel framework so insert/update/delete queries should never need to be rewritten.

So my question is, in this situation would you still recommend building the referential integrity into the database or is it OK to build it into the application layer instead? And why?

+1  A: 

Database management system when you can, application when you can't. You want enforcement on the farthest back technology possible so anything built on top of it can leverage it.

Beth
+4  A: 

You should do as much data integrity maintenance as possible in the database. It's "free" once you declare it, and guaranteed to apply no matter how the data reaches the database. That, to me, seems a no-brainer.

You brought up several instances of types of database integrity that cannot be declaratively specified in a database. In those cases, obviously, you must program the integrity into the middle layer or front-end and hope for the best.

Larry Lustig
+2  A: 

Use the database for what it does best. Referential integrity included - it is built into the database and ensures that your data is in a consistent state.

If this is not suitable for something specific in your application, build around it in your application logic/domain model.

Personally, if possible I would make sure to add referential logic to both application and database (defense in depth).

Oded