As I believe I've mentioned in an earlier video, a constraint is basically a rule we can put in our database that prevents someone from putting the wrong data in. It protects our relationships and data integrity. Because the goal of these constraints are to protect our data integrity, you may hear them called integrity constraints.
There are many integrity constraints we are going to talk about:
There is also the DEFAULT attribute.
These are all keywords we can add to our columns that will change the way the database works with our data and also prevents incorrect data.
NOT NULL is a constraint you can put on a column that prevents nulls. A null is the absence of a value. When we say null, we are saying that every single row has to have a value for this column.
UNIQUE is a constraint that makes every row have a unique value for this column. Now note, this does not require values to be put it, and it will allow multiple rows to be null.
Next, we are going to talk about primary keys. What qualifies a column as a candidate key? First, not a single row should have a null for that column. Second, every row must be unique. The primary key constraint is essentially a combination of the NOT NULL constraint and the UNIQUE constraint.
The foreign key constraint sets the requirement that any value in this column for any row must match a row in another column.
Check constraints allow us to be more strict with what data is allowed in our database. NOT NULL and UNIQUE give some level of restriction, but what if we want something more specific? For example, what if we only want values between 0 and 100? That is where check constraints come in. When using check constraints, you give a boolean expression. A boolean expression is something that can be evaluated to true or false. It will only insert the row if the value you try to put into the row makes the expression evaluate to true. So if you put in a value too great or small, the expression will be false and the data is not allowed to be entered.
The default constraint is a value you can give a column, and if for any reason when the row is created in the table a value is not provided, the default value will be given. So for example, we could have a bank account table where the balance defaults to 0.
How do you actually implement these constraints when you are creating a table? In the next video we are going to be adding these to our users table. Please be sure to subscribe!
Support me on Patreon: http://www.patreon.com/calebcurry
Subscribe to my newsletter: http://bit.ly/JoinCCNewsletter
More content: http://CalebCurry.com
Amazing Web Hosting - http://bit.ly/ccbluehost (The best web hosting for a cheap price!)