Presentation is loading. Please wait.

Presentation is loading. Please wait.

Sections 10 – Constraints

Similar presentations


Presentation on theme: "Sections 10 – Constraints"— Presentation transcript:

1 Sections 10 – Constraints
Database Programming Sections 10 – Constraints 10/3/06 revised 11/16/10 Used/revised 11/19/2013 Dplesson10_Fa13.ppt DP10_F13.txt CREATE TABLE copy_x AS(SELECT * FROM x);

2 CONSTRAINT TYPES NOT NULL Constraints UNIQUE Constraints
PRIMARY KEY Constraints FOREIGN KEY Constraints CHECK Constraints Constraints related to maintaining data integrity Dfn at column and/or table level Require meaningful name We’re now ready to examine constraints. Constraints enforce the contents of columns in a database. The list on this slide, shows constraints that are commonly used in the database including NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, and CHECK. We will look at each constraint individually. Marge Hohly

3 Defining CONSTRAINTS What are constraints?
Database rules Constraints always have a name Given by you/DBA when constraint is created (preferred method because names are meaningful) Given by the system when constraint is created (names are not meaningful) There are two ways to create constraints during table creation. The first is to create the constraint at the table level. This is done in the CREATE TABLE statement after all the columns have been named and created. Composite-key constraints must be defined at the table level. You remember composite primary keys from data modeling. This type of constraint is what is meant by a composite key constraint. The other way to create constraints is at the column level. In this way we name the constraint or define the constraint at the same time we’re defining the column definition in our CREATE TABLE statement. NOT NULL constraints cannot be defined at the table level. If the word CONSTRAINT is used at the time of creation, then you must give a name to the particular constraint. To prevent invalid data Marge Hohly

4 Defining CONSTRAINTS Two Ways to Define Constraints during Table Creation Table-Level NOT NULL cannot be defined at the table-level If the word CONSTRAINT is used in the CREATE TABLE statement, the constraint must be given a name Composite-key constraints must be defined at the table-level Column-Level NOT NULL must be defined at the Column-Level Run command. CREATE TABLE clients (client_number NUMBER(4) CONSTRAINT clients_client_num_pk PRIMARY KEY, first_name VARCHAR2(14), last_name VARCHAR2(13)); Marge Hohly

5 Naming Constraints Every constraint has a name.
User defined constraint name, ex. clients_client_num_pk System named constraint, ex. SYS_C0xxxx Format table-name_column-name_constraint-type Limit of 30 characters If defined at table creation must be named. Constraints can also be considered as rules for the database. All constraints have a name. It is helpful to give a name to a constraint at time of creation. This is the preferred method because then the name has meaning to the database administrator and the owner of the tables. If you do not name a constraint at the time of creation, it is given a name by the database. Database assigned names start with the letters s-y-s and then contain a number, which is pretty much unintelligible. We’ll look at a process for naming constraints as we create some later in this lesson. Marge Hohly

6 Column Level Constraint
Refers to a single column CREATE TABLE clients (client_number NUMBER(4) CONSTRAINT clients_client_num_pk PRIMARY KEY, first_name VARCHAR2(14) NOT NULL, last_name VARCHAR2(13)); Primary key defined at the column level SYS_Cn (where n is a unique integer) NOT NULL constraint CREATE TABLE clients (client_number NUMBER(4), last_name VARCHAR2(13), VARCHAR2(80)); Primary Key – clients_client_no_pk clients_last_name_nn name of NOT NUL constraint for last name clients_ _uk Unique constraint This slide shows the creation of constraints at the column level. A user named constraint named clients_client_num_pk is created on the client_number column and a system named constraint called SYS_Cn is created on the last_names column. Each constraint is named and defined at the same time the column is named. Notice also the placement of commas. A comma is not used until the column definition is completed, including the constraints if they are applied. Marge Hohly

7 Composite key constraint
Composite defined at Table level CREATE TABLE clients ( client_number NUMBER(4) NOT NULL, first_name VARCHAR2(20), last_name VARCHAR2(20), phone VARCHAR2(20), VARCHAR2(10) NOT NULL, CONSTRAINT clients_phone_ _uk UNIQUE ( ,phone)); NOT NULL constraint defined only at column level NOT table level UNIQUE, PRIMARY KEY, FOREIGN KEY and CHECK can be defined at either column or table level Let’s examine the CREATE TABLE statement on this page to examine one convention for naming columns and constraints. The table name is clients. It contains five columns of information: client number, which is numeric, first name, last_name, phone number, and , which are all VARCHAR2. After naming the last column, a NOT NULL constraint is added to the column. Next, a comma is inserted, then the word CONSTRAINT, then the name of the constraint. clients refers to the table name. The underscore separates the table name from the column names: phone_ . Then, another underscore separates the column name from the type of key. In this case, u-k stands for unique. The keyword UNIQUE defines the type of constraint. Then, in parentheses are the names of the columns in the table that the constraint refers to. Practice naming constraints in your Application Express account by creating a clients table. Marge Hohly

8 Note: The words “Foreign Key” are Used at the table level
Defining CONSTRAINTS Table-Level Constraints – at the bottom EXAMPLE: CREATE TABLE copy_employees( employee_id NUMBER(6), first_name VARCHAR2(20), job_id VARCHAR2(10), CONSTRAINT cemp_emp_id_pk PRIMARY KEY(employee_id), CONSTRAINT cemp_job_id_fk FOREIGN KEY(job_id) REFERENCES jobs(job_id), CONSTRAINT cemp_first_name_uk UNIQUE (first_name), CONSTRAINT cemp_emp_id_ck CHECK (employee_id<=999999)); Note: The words “Foreign Key” are Used at the table level Table level constraints are defined after the columns are defined Marge Hohly

9 Review this slide for violations.
Marge Hohly

10 NAMING at TABLE LEVEL Constraint naming format table_col_type
CONSTRAINT constraint_name TYPE OF CONSTRAINT(column_name) CONSTRAINT cemp_emp_id_pk PRIMARY KEY(employee_id) CONSTRAINT cemp_emp_id_lname_pk PRIMARY KEY(employee_id,last_name) CONSTRAINT constraint_name TYPE OF CONSTRAINT(column_name) REFERENCES othertablename(column_name) CONSTRAINT cemp_job_id_fk FOREIGN KEY(job_id) REFERENCES copy_jobs(job_id), Marge Hohly

11 NAMING at COLUMN LEVEL Column Level Assigning A Constraint Name:
System Named: column_name datatype() TYPE OF CONSTRAINT employee_id NUMBER(6) PRIMARY KEY User Named: column_name datatype() CONSTRAINT constraint name TYPE OF CONSTRAINT employee_id NUMBER(6) CONSTRAINT c2emp_emp_id_pk PRIMARY KEY Foreign Key: column_name datatype() CONSTRAINT constraint_name REFERENCES othertablename(column_name) Marge Hohly

12 Defining CONSTRAINTS Column-Level Constraints
Example: CREATE TABLE copy2_employees( employee_id NUMBER(6) CONSTRAINT c2emp_emp_id_pk PRIMARY KEY, CONSTRAINT c2emp_emp_id_ck CHECK(employee_id<=999999), first_name VARCHAR2(20) CONSTRAINT c2emp_first_name_nn NOT NULL, last_name VARCHAR2(20) CONSTRAINT c2emp_last_name_nn NOT NULL, address VARCHAR2(20) CONSTRAINT c2emp_address_ck NOT NULL, job_id VARCHAR2(10) CONSTRAINT c2emp_job_id_fk REFERENCES copy_jobs(job_id)); Walk thru the column dfn and constraint at column levet dfn Marge Hohly

13 NOT NULL Constraint Requires that every row has a value for the NOT NULL column Named with _nn suffix Marge Hohly

14 UNIQUE constraint No two rows have the same value
Every value in the column or set of columns (a composite key) are unique Names with _uk as a suffix If a composite unique key must be defined at Table level Column level unique constraint is defined a column level An error would be issued is you attempted to enter the same (shared) address in a second row. Unique constraint allows the entry of a NULL value for a column. NULL is unique because it is not considered equal to anything. Even when you have a composite key has all values NULL it is still considered unique. Test question. Marge Hohly

15 Primary Key Constraints
Primary key constraint is a column or set of columns that is uniquely identifies each row in a table Must satisfy both conditions: No column that is part of the primary key can contain a null value. A table can have only one primary key. Named with _pk suffix Section 10 lesson 2 Primary key can be defined at the column or table level If the primary key is a composite key it must be defined at the table level only. Example: CONSTRAINT id_venu_id_pk PRIMARY KEY (id,venue_id) Marge Hohly

16 Primary Key Constraints
CREATE TABLE clients (client_number NUMBER(4) CONSTRAINT clients_client_num_pk PRIMARY KEY, first_name VARCHAR2(14), last_name VARCHAR2(13)); Column level dfn of primary key A composite key dfn at table level: CONSTRAINT id_venue_id_pk PRIMARY KEY(id,venue_id) Marge Hohly

17 Foreign Key(Referential Integrity) constraints
CREATE TABLE clients (client_number NUMBER(4) CONSTRAINT clients_client_num_pk PRIMARY KEY, first_name VARCHAR2(14), last_name VARCHAR2(13), department_id VARCHAR2(4,0), CONSTRAINT clients_dept_id_fk FOREIGH KEY(department_id) REFERENCES departments(department_id)); Names _fk suffix Parents is where the primary key is from Child table has foreign key Primary key may exist with out a foreign key but the foreign key may not exist without the Primary key in the parent table. Foreign key must be already have a primary key constraint in the parent table. You MUST first have a primary key before you can define a foreign key in the child table. Marge Hohly

18 Foreign Key syntax Column-level Table-level
song_id NUMBER(5) CONSTRAINT d_track_list_song_id_fk REFERENCES d_songs(id) Table-level CONSTRAINT d_track_list_song_id_fk FOREIGN KEY(song_id) REFERENCES d_songs(id) The client table column named _______with a datatype of _______ has a CONSTRAINT named _____ which references its parent table called _____ which has a column called _____.” Table-level Foreign Key statement: There is a table-level CONSTRAINT named _______ which is a FOREIGN KEY (in the __________table), it REFERENCES the parent ____ table(which has a column named ____). Foreign key constraints are also called ‘referential integrity constraints.’ When you are using constraints or if you enter data that violates a constraint rule, or if you delete tables and violate the constraint rule, you will often see the words ‘parent table’ and ‘child table.’ Or, ‘orphan’ is often used also. The table that contains the foreign key is referenced as the ‘child table.’ The table that contains the primary key is called the ‘parent table.’ In the example on the slide, d_clients is the parent table and d_events is the child table. Marge Hohly

19 ON DELETE CASCADE option
Used when defining the foreign key enables the dependent rows in the child table to be deleted when a row in the parent table is deleted. Without this you can not delete the parent record if there are any rows in the child table with the key value. Use either on definition of FK ON DELETE CASCADE or ON DELETE SET NULL When a DELETE statement is issued for a row in a parent table, the command will not execute if there are rows in a child table that use the row from the parent table. As an example, you could not delete department ten from the departments table, if any employees had data values in their department id column that match the ten you are trying to delete. You can avoid this problem when creating your constraints by adding either the words ON DELETE CASCADE or ON DELETE SET NULL at the time you create the constraint. If a constraint is created with ON DELETE CASCADE then, if a row in a parent table is deleted, all rows in the child table that refer to that row, will be deleted along with the parent row. ON DELETE SET NULL changes the value of any conflicting row in the child table to a null value so that the referential integrity is maintained. DELETE from d_songs WHERE song_id=47; Is executed. Marge Hohly

20 ON DELETE CASCADE option
Column-level song_id NUMBER(5) CONSTRAINT d_track_list_song_id_fk REFERENCES d_songs(id) ON DELETE CASCADE Table-level CONSTRAINT d_track_list_song_id_fk FOREIGN KEY(song_id) REFERENCES d_songs(id) ON DELETE CASCADE Could use ON DELETE SET NULL also Rather than having the rows in the child table deleted you can use ON DELETE SET NULL Marge Hohly

21 CHECK constraints Explicitly defines a condition that must be met.
Condition must be either TRUE or unknown(due to a null) May refer to values in any column in the table, but not columns in other tables Marge Hohly

22 CHECK constraint This slide shows several examples of CHECK constraints. The CHECK constraint explicitly defines a condition that must be met, such as ‘year greater than 1996’ on the year column. To satisfy the constraint, each row in the table must make the condition either true, or unknown due to a null. The condition of a CHECK constraint can refer to any column in the specified table, but not to columns of other tables. That would be a FOREIGN KEY constraint. Marge Hohly

23 Marge Hohly

24 Example 1 (Note: The words “Foreign Key” are used at the table leve
CREATE TABLE copy_employees( employee_id NUMBER(6), first_name VARCHAR2(20), job_id VARCHAR2(10), CONSTRAINT cemp_emp_id_pk PRIMARY KEY(employee_id), CONSTRAINT cemp_job_id_fk FOREIGN KEY(job_id) REFERENCES jobs(job_id), CONSTRAINT cemp_first_name_uk UNIQUE (first_name), CONSTRAINT cemp_emp_id_ck CHECK(employee_id <=999999)); Example 2 (Note: The words “Foreign Key” are not used at the column level): CREATE TABLE copy2_employees( employee_id NUMBER(6) CONSTRAINT c2emp_emp_id_pk PRIMARY KEY CONSTRAINT c2emp_emp_id_ck CHECK(employee_id <=999999), ast_name VARCHAR2(30) NOT NULL, CONSTRAINT c2emp_last_name_nn NOT NULL, address VARCHAR2(20) CONSTRAINT c2emp_address_ck NOT NULL, job_id VARCHAR2(10) CONSTRAINT c2emp_job_id_fk REFERENCES jobs(job_id) Marge Hohly

25 Adding Constraints AFTER Table is created:
First, create a table that does not already have constraints: CREATE TABLE copy3_employees( employee_id NUMBER(6), first_name VARCHAR2(20), last_name VARCHAR2(20), department_id NUMBER(4)); Once we’ve created tables, we can modify the constraints on them in various ways. We can add, drop, enable or disable constraints on a table. Additionally, we can add a NOT NULL constraint to a column. Marge Hohly

26 Alter statement requires:
Name of the table Name of the constraint Type of constraint Name of the column affected by the constraint Example: ALTER TABLE copy1_d_clients ADD CONSTRAINT clients_client_num_pk PRIMARY KEY(client_number); Because the addition of constraints changes the structure and the rules of a table, we use the ALTER TABLE command to add constraints. In this example, a primary key constraint is added to the d_clients table on the client_number column. Marge Hohly

27 Adding Constraints AFTER Table is created:
Secondly, add the constraints: ALTER TABLE copy3_employees ADD CONSTRAINT emp3_emp_id_pk PRIMARY KEY(employee_id); ALTER TABLE copy3_employees ADD CONSTRAINT emp3_emp_id_fk FOREIGN KEY(department_id) REFERENCES copy_departments(department_id); Because the addition of constraints changes the structure and the rules of a table, we use the ALTER TABLE command to add constraints. In this example, a primary key constraint is added to the d_clients table on the client_number column. ALTER TABLE table_name ADD[CONSTRAINT constraint_name] type of constraint(column_name); The next example shows how to add a foreign key constraint to an existing table. Be sure to include the keyword REFERENCES and the table and column name of the parent table. Remember that both the parent and child columns must contain valid values in order for the constraint to be activated. Marge Hohly

28 Adding Constraints AFTER Table is created:
NOTE!!! For NOT NULL constraints, use the MODIFY keyword in the ALTER TABLE statement instead of ADD ALTER TABLE copy3_employees MODIFY (first_name CONSTRAINT emp3_first_name_nn NOT NULL); NOT NULL constraints can only be added if the column does not already contain null values This slide shows some special circumstances for adding a NOT NULL constraint since it is a column-level constraint. We use a MODIFY keyword to modify the column by adding the constraint. ALTER TABLE d_clients MODIFY. We then specify the column name, ‘ ’, the word CONSTRAINT, and then the name of the constraint, in this case, ‘d_clients_ _nn’. The final value is the type of constraint, in this case NOT NULL. Notice this entire MODIFY clause is enclosed in parentheses. You may not add a NOT NULL constraint to a table column that already contains null values. However, if the table is empty or the column contains values for all rows, you can add this constraint. Marge Hohly

29 Miscellaneous Constraint Information ...
If the word CONSTRAINT is used in a CREATE TABLE statement, the constraint must be given a name Constraints that contain more than one column are called composite key constraints and must be specified at the table level by placing a comma between the column names There is no limit to the number of CHECK CONSTRAINTS that can be specified for a column Marge Hohly

30 Miscellaneous FK Constraints Information...
Another name for FOREIGN KEY CONSTRAINTS is REFERENCIAL INTEGRITY CONSTRAINTS When specifying FOREIGN KEY CONSTRAINTS, the table that contains the PRIMARY KEY is called the PARENT TABLE. The table that contains the FOREIGN KEY CONSTRAINT is called the CHILD TABLE. Marge Hohly

31 DISABLING CONSTRAINTS
Constraints can be disabled Examples: ALTER TABLE copy3_employees DISABLE CONSTRAINT emp3_emp_id_pk; ALTER TABLE copy3_employees DISABLE CONSTRAINT emp3_emp_id_pk CASCADE; This will cause any FOREIGN KEY that references this primary key to also be disabled. To enforce the rules defined by integrity constraints, the constraints should always be enabled. In certain situations, however, it is desirable to disable the integrity constraints of a table temporarily for performance reasons, such as: - When loading large amounts of data into a table - When performing batch operations that make massive changes to a table (such as changing everyone's employee number by adding 1,000 to the existing number) In cases such as these, integrity constraints may be temporarily turned off to improve the performance of the operation. Marge Hohly

32 ENABLING CONSTRAINTS EXAMPLES:
ALTER TABLE copy3_employees ENABLE CONSTRAINT emp3_emp_id_pk Note: This does not enable the foreign key in the child tables Marge Hohly

33 DROPPING CONSTRAINTS Examples:
ALTER TABLE table_name DROP CONSTRAINT TYPE (column_name)[CASCADE]; ALTER TABLE table_name DROP CONSTRAINT name[CASCADE]; ALTER TABLE c_clients DROP PRIMARY KEY CASCADE; To drop the primary-key constraint on the D_CLIENTS table, the word CASCADE is used to disable the foreign- key constraint in the child table. ALTER TABLE c_clients DROP PRIMARY KEY CASCADE; Note: Since there is only one primary key for a table, we did not have to specify the column name. Here you can see how to drop a constraint. A constraint can either be dropped by referring to the column name and the constraint type or by referring to the constraint by name. CASCADE is an option that can be used to disable or drop any constraints dependent upon this constraint. This is commonly used when a primary key is being dropped. Marge Hohly

34 Using the DISABLE clause
Use DISABLE clause with ALTER TABLE or CREATE TABLE statement ALTER TABLE copy_d_clients DISABLE CONSTRAINT clients_client_num_pk CREATE TABLE copy_d_clients (client_number NUMBER(5) PRIMARY KEY DISABLE); Constraints created for a database table can be disabled. Some examples of when you may want to disable constraints are 1. If you are loading large amounts of data or 2. If you are performing batch changes to a table. The examples on this page show the syntax. Notice that it would be difficult to disable a constraint if you did not already know its name. However, you can search the Data Dictionary or use the database browser in Application Express to look up the name of constraints. Disabling constraints is sometimes necessary. Disabling must be done before entering data based on a relationship that is mandatory in both directions. Marge Hohly

35 CASCADE clause CASCADE clause disables dependent integrity constrains.
If later enabled, the dependent constraints are not automatically enabled ALTER TABLE table_name DISABLE CONSTRAINT constraint_name [CASCADE]; ALTER TABLE d_clients DISABLE CONSTRAINT clients_client_num_pk CASCADE; Marge Hohly

36 Enabling Constraints Use ENABLE clause in the ALTER TABLE statement
ALTER TABLE table_name ENABLE CONSTRAINT constraint_name; ALTER TABLE d_clients ENABLE CONSTRAINTS clients_client_num_pk; Can use ENABLE clause in both CREATE TABLE and ALTER TABLE Disabling a constraint is temporary. A constraint can be re-enabled by the command ENABLE CONSTRAINT. This page shows an example of using this command. When you re-enable the constraint, that constraint applies to all the data in the table, and all the data in the table must fit that constraint. For example, if you enable a unique constraint on a column, then all its values must be unique. Marge Hohly

37 Cascading Constraints
Used along with DROP COLUMN clause Drops all referential-integrity constraints the refer to primary and unique keys defined on the dropped columns ALTER TABLE table_name DROP(column name(s)) CASCADE CONSTRAINTS; Marge Hohly

38 Viewing Constraint Use the DESCRIBE command to confirm its existence .
DESCRIBE can only verify is the NOT NULL constraint. NOT NULL constraint appears in the data dictionary as a CHECK constraint. Use a query of the USER_CONSTRAINTS table to view all constraints on your table. SELECT constraint_name, constraint_type FROM user_constraints WHERE TABLE_NAME ='table_name'; SELECT constraint_name, constraint_type FROM user_constraints WHERE TABLE_NAME ='COPY3_EMPLOYEES‘; Note in example only the table name is substituted. Note only the table name was changed. This last slide shows how to query the Data Dictionary to find information about constraints. There is a view, called ‘user_constraints,’ that contains columns that you can use to access the constraint information. This slide shows the abbreviations used when talking about constraint types, for example C is for Check Constraint, P is for Primary Key and U is for Unique Key. You can view constraints on specific tables by using the database browser and looking at tables in Application Express. Or, you can browse the Data Dictionary as an option. Please take some time now using both methods to examine the constraints in your schema so that you become familiar with what they are and how they are referenced. Marge Hohly

39 QUERY THE DATA DICTIONARY
SELECT constraint_name, constraint_type, table_name, status FROM user_constraints; Types: P = Primary Key R = Foreign Key (Referential) C = Check (Includes NOT NULL) U = Unique Marge Hohly

40 Viewing Constraint SELECT constraint_name, column_name FROM user_cons_columns WHERE table_name = 'EMPLOYEES'; Students need to know how to use the SELECT statement to view the data dictionary constraints. Make sure they write this code so that they will be familiar with it. Marge Hohly

41 Viewing Constraints Marge Hohly

42 Constraint Rules in Review:
The NOT NULL constraint can be specified only at the column level, not the table level PRIMARY, UNIQUE, FOREIGN KEY, and CHECK constraints can be specified at the column level OR the table level Where to add constraints as part of the CREATE TABLE statement: At the column level Following the data type At the table level Following the comma after the last column name and data type Marge Hohly

43 Miscellaneous FK Constraint Information:
Another name for FOREIGN KEY CONSTRAINTS is REFERENTIAL INTEGRITY CONSTRAINTS When specifying FOREIGN KEY CONSTRAINTS, the table that contains the PRIMARY KEY is called the PARENT TABLE. The table that contains the FOREIGN KEY CONSTRAINT is called the CHILD TABLE When a DELETE statement is issued for a row in the PARENT TABLE, the command will not execute if there are rows in the CHILD TABLE that use the row from the PARENT TABLE Add ON DELETE CASCADE to the end of a FOREIGN KEY constraint to force CHILD TABLE rows to be deleted when PARENT TABLE rows are deleted Add ON DELETE SET NULL to the end of the FOREIGN KEY constraint to force CHILD TABLE rows to be replaced with NULL values when PARENT TABLE rows are deleted Marge Hohly


Download ppt "Sections 10 – Constraints"

Similar presentations


Ads by Google