17
DB Programming Section 10 Lesson 1: Defining NOT NUL and UNIQUE Constraints CONSTRAINTS IN GENERAL So, what exactly is a constraint? Think of constraints as database rules. Their definitions are stored in the data dictionary. Constraints prevent the deletion of a tab le if there are dependencies from other tables. Constraints enforce rules on the data whenever a row is inserted , updated , or deleted  from a table. Constraints are important and naming them is also important. Although you could name a constraint "bubbles" or "squeak," you'd soon find it difficult to distinguish one constraint from another and would end up redoing a lot of work. Recall the SQL syntax for creating a table. In the CREATE TABLE statement shown below, each column and its data type i s defined. However, can you tell from this statement what column is the primary key, unique key, or foreign key? CREATE TABLE clients (client_number NUMBER(4), first_name VARCHAR2(14), last_name VARCHAR2(13)); What is not included in this example are the constraints for each column in the table. In this lesson and subsequent lessons, you will learn how to define the column constraints in two different places in the CREATE TABLE statement: - At the column level next to the name and data type - At the table level after all the column names are listed CONSTRAINTS AT THE COLUMN LEVEL  A column-level constraint referen ces a single column. To accomplish this, the constraint must be defined in the CREATE TABLE statement when the column is defined. Look at the following SQL statement. What has been added to our CREATE TABLE statement? CREATE TABLE clients (client_number NUMBER(4) CONSTRAINT clients_client_num_pk PRIMARY KEY, first_name VARCHAR2(14), last_name VARCHAR2(13)); When the constraint is created, it can be given a name, such as clients_client_num_pk , or given no name, in which case the system gives the constraint a name, such as SYS_C00585417. Note: If the word CONSTRAINT is used in the CREATE TABLE definition, you must give the constraint a name. It is best to name constraints yourself. Why? The system- generated names are not intuitive. You can do better than the database when it comes to naming! The following examples are two varieties of a column-level constraint definition. System-named constraint: Generates a SYS_Cn, where n is an integer so the name is unique. column_name datatype () TYPE OF CONSTRAINT client_number NUMBER(7) NOT NULL 1

Constrangeri

  • Upload
    gefinna

  • View
    403

  • Download
    0

Embed Size (px)

DESCRIPTION

DB Oracle

Citation preview

Page 1: Constrangeri

7/16/2019 Constrangeri

http://slidepdf.com/reader/full/constrangeri 1/17

DB Programming Section 10

Lesson 1: Defining NOT NUL and UNIQUE Constraints

CONSTRAINTS IN GENERAL

So, what exactly is a constraint? Think of constraints as database rules. Their definitions arestored in the data dictionary.

Constraints prevent the deletion of a table if there are dependencies from other tables.Constraints enforce rules on the data whenever a row is inserted , updated , or deleted  

from a table. Constraints are important and naming them is also important. Although you couldname a constraint "bubbles" or "squeak," you'd soon find it difficult to distinguish one constraintfrom another and would end up redoing a lot of work.

Recall the SQL syntax for creating a table. In the CREATE TABLE statement shown below,each column and its data type is defined. However, can you tell from this statement what column is the primary key, unique key, or foreign key?

CREATE TABLE clients(client_number NUMBER(4),first_name VARCHAR2(14),last_name VARCHAR2(13));

What is not included in this example are the constraints for each column in the table. In thilesson and subsequent lessons, you will learn

how to define the column constraints in two different placesin the CREATE TABLE statement:- At the column level next to the name and data type- At the table level after all the column names are listed

CONSTRAINTS AT THE COLUMN LEVEL A column-level constraint references a single column.To accomplish this, the constraint must be defined in the CREATE TABLE statement when thecolumn is defined.Look at the following SQL statement. What has been added to our CREATE TABLE statement

CREATE TABLE clients(client_number NUMBER(4) CONSTRAINT clients_client_num_pk PRIMARY KEY,first_name VARCHAR2(14),last_name VARCHAR2(13));

When the constraint is created, it can be given a name, such as clients_client_num_pk, or given no name, in which case the system gives the constraint a name, such asSYS_C00585417. Note: If the word CONSTRAINT is used in the CREATE TABLE definition,you must give the constraint a name. It is best to name constraints yourself. Why? The systemgenerated names are not intuitive. You can do better than the database when it comes tonaming!

The following examples are two varieties of a column-level constraint definition.

System-named constraint: Generates a SYS_Cn, where n is an integer so the name is unique.

column_name datatype () TYPE OF CONSTRAINT

Page 2: Constrangeri

7/16/2019 Constrangeri

http://slidepdf.com/reader/full/constrangeri 2/17

Page 3: Constrangeri

7/16/2019 Constrangeri

http://slidepdf.com/reader/full/constrangeri 3/17

DB Programming Section 10

User-named constraint: Naming convention can be the combination of the tablenameabbreviated and a column name abbreviated followed by the constraint abbreviation. 

column_name datatype () CONSTRAINT constraint_name TYPE OF CONSTRAINTclient_number NUMBER(7) CONSTRAINT client_num_d_clients_nn NOT NULL

CONSTRAINTS AT THE TABLE LEVEL

Table-level constraints are listed separately from the column definitions in the CREATE TABLEstatement. Table-level constraint definitions are stated after all the table columns have beendefined. In the example shown, the constraint is listed last in the CREATE TABLE statement.

CREATE TABLE tablename(columnname datatype [DEFAULT expression],columnname datatype [DEFAULT expression]...;

Add table constraints here ......

CONSTRAINT constraint_name TYPE OF CONSTRAINT (column_name)CONSTRAINT clients_client_num_nn NOT NULL(client_number));

-Is there a way to make sure a value is always provided for the customer’s last name?-Sure-We just need to add a non null constraint to that column.-Can we make sure that if a value is provided for the customer mail address … that it is not arepeat of another email address?-We just need to add a unique constraint to the email address column.

BASIC RULES FOR CONSTRAINTS

- The NOT NULL constraint can be specified only at the column level, not the table level.- If the word CONSTRAINT is used in a CREATE TABLE statement, you must give theconstraint a name.- UNIQUE, PRIMARY KEY, FOREIGN KEY, and CHECK constraints can be defined at either the column or table level.- Constraints that include more than one column (a composite key) must be defined at the tablelevel.

Page 4: Constrangeri

7/16/2019 Constrangeri

http://slidepdf.com/reader/full/constrangeri 4/17

Page 5: Constrangeri

7/16/2019 Constrangeri

http://slidepdf.com/reader/full/constrangeri 5/17

DB Programming Section 10

NOT NULL CONSTRAINT

 A column defined with a NOT NULL constraint requires that for every row entered into the tablethere must be a value for that column. For example, if the email column in an employees tablewas defined as NOT NULL, every employee entered into the table MUST have a value in theemail column.

When defining NOT NULL columns, it is customary to use the suffix _nn in the constraint nameFor example, the constraint name for the NOT NULL email column in the employees table coube emp_email_nn.

UNIQUE CONSTRAINT

 A UNIQUE constraint requires that every value in a column or set of columns (a composite keybe unique; that is, no two rows of a table can have duplicate values. For example, it may beimportant for a business to ensure that no two people have the same email address. The emaicolumn could be defined using a UNIQUE constraint. The column or set of columns that isdefined as UNIQUE is called the unique key. If the combination of two columns must not be thesame for any entry, the constraint is said to be a composite unique key. Stating that all

combinations of email and last name must be UNIQUE is an example of a composite uniquekey. The word "key" refers to the columns, not constraint names.

Page 6: Constrangeri

7/16/2019 Constrangeri

http://slidepdf.com/reader/full/constrangeri 6/17

Page 7: Constrangeri

7/16/2019 Constrangeri

http://slidepdf.com/reader/full/constrangeri 7/17

DB Programming Section 10

if two clients live in the same householdand share an email address?

Page 8: Constrangeri

7/16/2019 Constrangeri

http://slidepdf.com/reader/full/constrangeri 8/17

Page 9: Constrangeri

7/16/2019 Constrangeri

http://slidepdf.com/reader/full/constrangeri 9/17

DB Programming Section 10

UNIQUE constraints allow the input of nulls unless the column also has a NOT NULL constraindefined. A null in a column (or in all columns of a composite unique key) always satisfies aUNIQUE constraint because nulls are not considered equal to anything. To satisfy a constraintthat designates a composite unique key, no two rows in the table can have the samecombination of values in the key columns. Also, any row that contains nulls in all key columnsautomatically satisfies the constraint. However, two rows that contain nulls for one or more keycolumns and the same combination of values for the other key columns violate the constraint.

When defining UNIQUE columns, it is customary to use the suffix _uk in the constraint name.For example, the constraint name for the UNIQUE email column in the employees table couldbe emp_email_uk.

To define a composite unique key, you must define the constraint at the table level rather thanthe column level. An example of a composite unique-key constraint name is:

CONSTRAINT clients_phone_email_uk UNIQUE(email,phone).

Try it Global Fast Foods has been very successful this past year and has opened several new storesThey need to add a table to their database to store information about each of their store'slocations. The owners want to make sure that all entries have an identification number, dateopened, address, and city and that no other entry in the table can have the same email addresBased on this information, answer the following questions about the global_locations table. Usethe table for your answers.

1. Based on the information provided bythe owners, choose a data type for each column. Indicate the length,

precision, and scale for each NUMBER data type.

2. Use "(nullable)" to indicate thosecolumns that can have null values.

3. Write the CREATE TABLE statement for the Global Fast Foodslocations table to define the constraintsat the column level.

4. Execute the CREATE TABLE statement in HTML DB.

5 Execute a DESCRIBE command to view the Table Summary information

Page 10: Constrangeri

7/16/2019 Constrangeri

http://slidepdf.com/reader/full/constrangeri 10/17

Page 11: Constrangeri

7/16/2019 Constrangeri

http://slidepdf.com/reader/full/constrangeri 11/17

DB Programming Section 10

6. Rewrite the CREATE TABLE statement for the Global Fast Foods locations table to definethe UNIQUE constraints at the table level. Do not execute this statement.

Page 12: Constrangeri

7/16/2019 Constrangeri

http://slidepdf.com/reader/full/constrangeri 12/17

Page 13: Constrangeri

7/16/2019 Constrangeri

http://slidepdf.com/reader/full/constrangeri 13/17

DB Programming Section 10

Lesson 2: PRIMARY KEY, FOREIGN KEY and CHECK Constraints

In this lesson, you will learn to:

• Define and give an example of a PRIMARY KEY, FOREIGN KEY, and CHECK constrai

• Explain the purpose of defining PRIMARY KEY, FOREIGN KEY, and CHECK constraint

Demonstrate the creation of constraints at the column level and table level in a CREATETABLE statement

• Evaluate a business problem requiring the addition of a PRIMARY KEY and FOREIGN

KEY constraint and write the code to execute the change

• Evaluate a business problem requiring the addition of a PRIMARY KEY and FOREIGN

KEY constraint and write the code to execute the change

• Query the data dictionary for USER_CONSTRAINTS and interpret the information

returned

Why learn it? As discussed in the last section, constraints are used to prevent invalid data entry into databas

tables. What would happen if, surreptitiously or just through a careless mistake, your personalunique identification was given to another person? What if tomorrow at school someone elsewas credited with your classes for graduation or was able to eat lunch using your lunch-cardnumber?

Ensuring data integrity is what constraints are all about. After all, you're unique!

Tell mePRIMARY KEY CONSTRAINTS

 A PRIMARY KEY constraint is a column or set of columns that uniquely identifies each row in atable. No primary-key value can appear in more than one row in the table. To satisfy aPRIMARY KEY constraint, both of the following conditions must be true:

- No column that is part of the primary key can contain a null.- A table can have only one primary key.

PRIMARY KEY constraints can be defined at the column or the table level. However, if acomposite PRIMARY KEY is created, it must be defined at the table level.

When defining PRIMARY KEY columns, it is customary to use the suffix _pk in the constraintname. For example, the constraint name for the PRIMARY KEY column named id in the DJ onDemand d_events table could be d_events_id_pk.

In a CREATE TABLE statement, the column-level PRIMARY KEY constraint syntax is stated

CREATE TABLE clients(client_number NUMBER(4) CONSTRAINT client_client_num_pk PRIMARY KEY,first_name VARCHAR2(14),last_name VARCHAR2(13));

To define a composite PRIMARY KEY, you must define the constraint at the table level rather than the column level. An example of a composite unique-key constraint name is:

CONSTRAINT id_venue_id_pk UNIQUE (id, venue_id)

FOREIGN KEY (REFERENTIAL INTEGRITY) CONSTRAINTSFOREIGN KEY constraints are also called "referential integrity" constraints.

Page 14: Constrangeri

7/16/2019 Constrangeri

http://slidepdf.com/reader/full/constrangeri 14/17

Page 15: Constrangeri

7/16/2019 Constrangeri

http://slidepdf.com/reader/full/constrangeri 15/17

DB Programming Section 10

CREATE TABLE clients(client_number NUMBER(4) CONSTRAINT client_client_num_pk PRIMARY KEY,first_name VARCHAR2(14),last_name VARCHAR2(13),department_id VARCHAR2(4,0),CONSTRAINT clients_dept_id_fk FOREIGN KEY(department_id) REFERENCESdepartments(department_id));

These constraints designate a column or combination of columns as a foreign key. Itestablishes a relationship between a primary key or unique key in the same table or a differenttable with the foreign key.The table containing the foreign key is called the "child" table and the table containing the referenced key is called the "parent" table. In the tables shown, D_CLIENTS primary-key client_number also appears in D_EVENTS as a foreign-key column.

To satisfy a referential-integrity constraint, a foreign-key value must match an existing value inthe parent table or be NULL. In the example, note that a primary-key value can exist without a

corresponding foreign-key value; however, a foreign-key must have a corresponding primarykey.

The rule is: before you define a referential-integrity constraint in the child table, the referencedUNIQUE or PRIMARY KEY constraint on the parent table must already be defined. In other words, you must first have a parent primary key defined before you can create a foreign keyin a child table.

To define a FOREIGN KEY constraint, it is customary to use the suffix _fk in the constraintname. For example, the constraint name for the FOREIGN KEY column song_id in the DJ onDemand table named d_track_listings could be named d_track_list_ song_id_fk.

The syntax for defining a FOREIGN KEY constraint requires a reference to the table andcolumn in the parent table. A FOREIGN KEY constraint in a CREATE TABLE statement can bdefined as follows.

Column-level syntax:song_id NUMBER(5) CONSTRAINT d_track_list_ song_id_fk REFERENCES

d_songs(id)

Table-level syntax:CONSTRAINT d_track_list_ song_id_fk FOREIGN KEY (song_id)REFERENCES d_songs(id)

ON DELETE CASCADE

- MAINTAINING REFERENTIAL INTEGRITY: Using the ON DELETE CASCADE option whendefining a foreign key enables the dependent rows in the child table to be deleted when a row ithe parent table is deleted. If the foreign key does not have an ON DELETE CASCADE optionreferenced rows in the parent table cannot be deleted. In other words, the child table FOREIGNKEY constraint includes the ON DELETE CASCADE permission allowing its parent to deleterows that it refers to.

Page 16: Constrangeri

7/16/2019 Constrangeri

http://slidepdf.com/reader/full/constrangeri 16/17

DB Programming Section 10

Page 17: Constrangeri

7/16/2019 Constrangeri

http://slidepdf.com/reader/full/constrangeri 17/17

DB Programming Section 10

DELETE CASCADE option was not specified when the song_id column inD_TRACK_LISTINGS was created, the attempt to delete song_id = 47 will fail.

Column-level syntax:song_id NUMBER(5) CONSTRAINTd_track_list_ song_id_fkREFERENCES d_songs(id) ONDELETE CASCADE

Table-level syntax:CONSTRAINT d_track_list_ song_id_fk FOREIGN KEY (song_id)REFERENCES d_songs(id) ONDELETE CASCADE