In the previous video we talked about adding constraints at the column-level. We made it nice and simple by only requiring a few keywords, but the problem we were having is that we could not assign a name to the constraint, which many people like to do so we can reference easily if we need to at a later time. To do this, it requires a little bit more typing, but it will give us extra flexibility and many consider it to be the higher quality approach to adding constraints.
Let's go though a simple example. Let's say we have a users table with a user_id column that we want to make a primary key. We will create the table like this:
user_ id NUMBER PRIMARY KEY
Instead of adding the PRIMARY KEY keywords after the data type, we add:
CONSTRAINT user_pk PRIMARY KEY
Now, we have assigned the name user_pk to this constraint. You can do the same with other constraints, such as UNIQUE. The syntax would be CONSTRAINT username_un UNIQUE.
The other way to create constraints requires to put all of our constraints at the bottom of our table creation rather than inline with the column. This type of constraint is known as a table-level constraints. To make a column a primary key using table-level constraints, we add it to the CREATE TABLE command as if it is another row and use the CONSTRAINT keyword to tell Oracle that what is coming is a constraint, not a column in our table.
CREATE TABLE users(
username VARCHAR2(50 CHAR),
CONSTRAINT username_un UNIQUE (username),
CONSTRAINT users_pk PRIMARY KEY (user_id)
The primary differences here is that you have to put the column you are talking about in parenthesis after the PRIMARY KEY keyword. That's because it's at the end of the table and you need a way to tell it what column you are talking about.
The option of putting it at the end of the table has the added benefit in this situation because if we needed to have a primary key that is the combination of multiple columns, we can do that by just adding the other column in the PRIMARY KEY parenthesis right after a comma.
In summary, there are three ways to make constraints. The first is at the column level, unnamed. The second is at the column level, named. The third is at the table level, also named.
In the next video we are going to create a named constraint in Oracle SQL Developer, so stay tuned and be sure to subscribe!
Support me! 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!)