Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Database constraints - keep or ignore?

When I was learning in university, they taught us the database fundamentals, basics and rules, and one of the most important rules is the constraints (primary key, foreign key), and how to make 1-m, 1-1, m-n relationships.

Now when I move to real business environment they tell me: you should forget all you have been taught; no constraints, all those relationships are logical, no primary keys, no foreign keys, you can make your constraints through the code.

I don't know who is right: what I learned in my academic life or what I will learn in my new real business life. What do you think?

like image 485
Anyname Donotcare Avatar asked Sep 13 '10 13:09

Anyname Donotcare


People also ask

Should I use database constraints?

There are others, of course, but the reasons for using constraints are quite varied, and can be a helpful tool for database administrators and developers alike. Typically, it is recommended to use constraints over more complex, procedural logic-enforcement, such as triggers, rules, stored procedures, or jobs.

What are the 3 three database constraints?

DEFAULT Constraint − Provides a default value for a column when none is specified. UNIQUE Constraint − Ensures that all values in a column are different. PRIMARY Key − Uniquely identifies each row/record in a database table. FOREIGN Key − Uniquely identifies a row/record in any of the given database table.

Why do we apply database constraints?

Constraints are used to limit the type of data that can go into a table. This ensures the accuracy and reliability of the data in the table. If there is any violation between the constraint and the data action, the action is aborted. Constraints can be column level or table level.


2 Answers

If somebody told me to ignore keys and constraints on my databases, I would promptly ignore them and go about my business.

Primary keys, foreign keys, and constraints are there for a reason. Use them. They'll make your life easier and your database easier to understand (and, quite often, more performant).

like image 57
Justin Niessner Avatar answered Oct 15 '22 15:10

Justin Niessner


The longer I work with databases, the more I appreciate constraints. In the long run, they save me a lot of time. Only trusted constraints ensure 100% validity of data.

I wrote a chapter on usage of constraints vs. other ways of ensuring data integrity, available as free download here

like image 25
A-K Avatar answered Oct 15 '22 16:10

A-K