PRAKTIKUM DATABASE DESIGN & PROGRAMMING WITH SQL
Dosen Pengampu: Anief Fauzan Rozi, S.Kom., M.Eng., MCE.
Nama: Rizky Nurdiasyah
Nim: 221210014
Prodi: Sistem Informasi
FAKULTAS TEKNOLOGI INFORMASI
UNIVERSITAS MERCU BUANA YOGYAKARTA
TAHUN 2023
Database Programming with SQL
14.1 : Intro to Constraints; NOT NULL and UNIQUE Constraints
Practice Activities
Objectives
• Define the term "constraint" as it relates to data integrity
• State when it is possible to define a constraint at the column level, and when it is possible atthe table
level
• State why it is important to give meaningful names to constraints
• State which data integrity rules are enforced by NOT NULL and UNIQUE constraints
• Write a CREATE TABLE statement which includes NOT NULL and UNIQUE constraints at thetable
and column levels
• Explain how constraints are created at the time of table creation
Vocabulary
Identify the vocabulary word for each definition below.
UNIQUE CONSTRAINT Every value in a column or set of columns (a composite key)
must be unique
NOT NULL Constraint For every row entered into the table, there must be a value for
that column
PRIMAR KEY Constraint ensures that the column contains no null values and
uniquely identifies each row of the table
CECK CONSTRAINT Specifies a condition for a column that must be true for each row
of data
REFERENCES Identifies that table and column in the parent table
UNIQUE ConstraintAn integrity constraint that requires every value in a column or setof
columns be unique
FOREIGN KEY Designates a column (child table) that establishes a relationship
between a primary key in the same table and a different table
(parent table)
TABLE LEVEL CONSTRAINT References one or more columns and is defined separately fromthe
definitions of the columns in the table
CONSTRAINT Database rule.
COLUMN LEVEL Database rule that references a single column
CONSTRAINT
Try It / Solve It
Global Fast Foods has been very successful this past year and has opened several new stores. Theyneed to add a
table to their database to store information about each of their store’s locations. The owners want to make sure
that all entries have an identification number, date opened, address, and city and that no other entry in the table
can have the same email address. Based on this information, answer the following questions about the
global_locations table. Use the table for your answers.
Global Fast Foods global_locations Table
NAME TYPE LENGTH PRECISION SCALE NULLABLE DEFAULT
Id PK NO
name
date_opened NO
address NO
city NO
zip/postal
code
phone
email UK
manager_id
Emergency
contact
1. What is a “constraint” as it relates to data integrity?
Database can be as reliable as the data in it, and database rules are implemented as Constraint to maintain data
integrity. For example these constraints may prohibit deletion of a table or some row wheninsertion, updation or
deletion is executed. Type of constraints:
· PRIMARY KEY Constraint
· UNIQUE Constraint
· FOREIGN KEY Constraint
· CHECK Constraint with condition applied on the column/columns (they work at row level)
· NOT NULL Constraint (implemented at row level using special CHECK Constraint having condition ISNOT
NULL for single column)
2. What are the limitations of constraints that may be applied at the column level and at thetable
level?
• Constraints referring to more than one column are defined at Table Level
• NOT NULL constraint must be defined at column level as per ANSI/ISO SQL standard.
• If word CONSTRAINT is used in a CREATE TABLE statement, I must specify constraint name. Also, thatis why,
Table level constraint must be user-named.
3. Why is it important to give meaningful names to constraints?
• If a constraint is violated in a SQL statement execution, it is easy to identify the causewith
user-named constraints.
• It is easy to alter names/drop constraint.
• Handling production issues may be faster with user-named constraints
4. Based on the information provided by the owners, choose a datatype for each column. Indicatethe
length, precision, and scale for each NUMBER datatype.
5. Use “nullable” to indicate those columns that can have null values
6. Write the CREATE TABLE statement for the Global Fast Foods locations table to definethe
constraints at the column level.
CREATE TABLE f_global_locations
( id NUMBER(6,0) CONSTRAINT f_gln_id_pk PRIMARY KEY ,name VARCHAR2(50),
date_opened DATE CONSTRAINT f_gln_dt_opened_nn NOT NULL ENABLE,address VARCHAR2(50) CONSTRAINT
f_gln_add_nn NOT NULL ENABLE, city VARCHAR2(30) CONSTRAINT f_gln_city_nn NOT NULL ENABLE,
zip_postal_code VARCHAR2(12),
phone VARCHAR2(20),
email VARCHAR2(75) CONSTRAINT f_gln_email_uk UNIQUE,manager_id NUMBER(6,0),
emergency_contact VARCHAR2(20)
);
7. Execute the CREATE TABLE statement in Oracle Application Express.
8. Execute a DESCRIBE command to view the Table Summary information.
9. 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.
CREATE TABLE f_global_locations
( id NUMBER(6,0) CONSTRAINT f_gln_id_pk PRIMARY KEY ,
name VARCHAR2(50),
date_opened DATE CONSTRAINT f_gln_dt_opened_nn NOT NULL ENABLE,address
VARCHAR2(50) CONSTRAINT f_gln_add_nn NOT NULL ENABLE, city
VARCHAR2(30) CONSTRAINT f_gln_city_nn NOT NULL ENABLE, zip_postal_code
VARCHAR2(12),
phone VARCHAR2(20),email VARCHAR2(75) ,
manager_id NUMBER(6,0), emergency_contact VARCHAR2(20), CONSTRAINT f_gln_email_uk
UNIQUE(email)
Database Programming with SQL
14-2: PRIMARY KEY, FOREIGN KEY, and CHECK Constraints
Practice Activities Objectives
• Define and give an example of PRIMARY KEY, FOREIGN KEY, and CHECK constraints
• Explain the purpose of defining PRIMARY KEY, FOREIGN KEY, and CHECK constraints on a table
• Demonstrate the creation of constraints at the column level and table level in a CREATE TABLE
statement
• Evaluate a business problem requiring the addition of a PRIMARY KEY and FOREIGN KEY constraint
and write the code to execute the change
Vocabulary
Identify the vocabulary word for each definition below.
ON DELETE CASCADE Allows a foreign key row that is referenced to a primary key
row to be deleted
Check Constraint Explicitly defines a condition that must be met
PRIMARY KEY A column or set of columns that uniquely identifies each row
in a table
NOT NULL Constraint ensures that the column contains no null values
ON DELETE SET NULL Allows a child row to remain in a table with null values
when a parent record has been deleted
FOREIGN KEY Constraint Establishes a relationship between the foreign key column and a
primary key or unique key in the same table or a different table
Try It / Solve It
1. What is the purpose of a
a. PRIMARY KEY
Uniquely identify each row in table.
b. FOREIGN KEY
Referential integrity constraint links back parent table's primary/unique key to child table's column.
c. CHECK CONSTRAINT
Explicitly define condition to be met by each row's fields. This condition must be returned as true or unknown.
2. Using the column information for the animals table below, name constraints where applicable at the table
level, otherwise name them at the column level. Define the primary key (animal_id). The
license_tag_number must be unique. The admit_date and vaccination_date columns cannot contain null
values.
animal_id NUMBER(6) - PRIMARY KEY
name VARCHAR2(25)
license_tag_number NUMBER(10)- UNIQUE
admit_date DATE- NOT NULL adoption_id NUMBER(5), vaccination_date DATE- NOT NULL
3. Create the animals table. Write the syntax you will use to create the table.
4. Enter one row into the table. Execute a SELECT * statement to verify your input. Refer to the graphic
below for input.
ANIMAL_ NAME LICENSE_TAG_ ADMIT_DATE ADOPTION_ VACCINATION_
ID NUMBER ID DATE
101 Spot 35540 10-Oct-2004 205 12-Oct-2004
5. Write the syntax to create a foreign key (adoption_id) in the animals table that has a corresponding primary-
key reference in the adoptions table. Show both the column-level and table-level syntax. Note that because
you have not actually created an adoptions table, no adoption_id primary key exists, so the foreign key
cannot be added to the animals table.
If there is a value in animals.adoption_id, which is not present as primary key/unique key in parent table, it
will give error, so first fix it:
UPDATE animals
SET adoption_id = ( SELECT id FROM adoptions WHERE ROWNUM = 1);
or
UPDATE animals
SET adoption_id = NULL;
SELECT * FROM animals;
Adding foreign key using column level statement:
ALTER TABLE animals
MODIFY ( adoption_id NUMBER(5,0) CONSTRAINT anl_adopt_id_fk REFERENCES adoptions(id)
ENABLE );
Verify that constraint is generated:
SELECT *
FROM user_constraints
WHERE LOWER(table_name) = 'animals' AND constraint_type = 'R';
Now drop it:
ALTER TABLE animals
DROP CONSTRAINT anl_adopt_id_fk ;
Adding foreign key using table level statement:
ALTER TABLE animals ADD CONSTRAINT anl_adopt_id_fk FOREIGN KEY (adoption_id)
REFERENCES adoptions(id) ENABLE;
Verify that constraint is generated:
SELECT *
FROM user_constraint
WHERE LOWER(table_name) = 'animals' AND constraint_type = 'R';
6. What is the effect of setting the foreign key in the ANIMAL table as:
a. ON DELETE CASCADE
When a record is deleted from the "adoptions" table that is referenced by the foreign key in the
"animals" table, the corresponding records in the "animals" table will be automatically deleted as well.
This ensures the referential integrity and maintains consistency.
b. ON DELETE SET NULL
When a record is deleted from the "adoptions" table that is referenced by the foreign key in the
"animals" table, the value of the foreign key in the "animals" table will be set to NULL. This means that
the relationship between the "animals" table and the "adoptions" table is broken, and the "animals"
records will no longer be associated with any specific adoption.
7. What are the restrictions on defining a CHECK constraint?
• The check condition must be a Boolean expression.
• The check condition cannot refer to columns in other tables.
• The check condition cannot use subqueries.
• The check condition cannot refer to dynamic performance views or current package state.
• The check condition cannot include calls to user-defined functions that are not declared as deterministic.
• The check condition cannot exceed 4,000 bytes in length.
• The check condition cannot contain bind variables or literals with bind variables.
Database Programming with SQL
14-3: Managing Constraints
Practice Activities Objectives
• · To deactivate an integrity constraint-DISABLE CONSTRAINT
• · Disables dependent integrity constraints- CASCADE clause
• · To add, modify, or drop columns from a table- ALTER TABLE
• · To activate an integrity constraint currently disabled- ENABLE CONSTRAINT
• · Removes a constraint from a table- DROP CONSTRAINT
• · Allows user to delete a column from a table-DROP COLUMN
• · Defines the actions the database server takes when a user attempts to delete or
update a key to which existing foreign keys point- CASCADE CONSTRAINTS
Using Oracle Application Express, click the SQL Workshop tab in the menu bar. Click the
Ob-ject Browser and verify that you have a table named copy_d_clients and a table named
copy_d_events. If you don’t have these tables in your schema, create them before
completing the exercises below. Here is how the original tables are related. The d_clients
table has a primary key client_number. This has a primary-key constraint and it is
referenced in the foreign-key constraint on the d_events table.
CREATE TABLE
copy_d_clients AS ( SELECT *
FROM d_clients); DESCRIBE
copy_d_clients ; DESCRIBE
d_clients;
SELECT * FROM d_clients ;
SELECT * FROM
copy_d_clients ; SELECT *
FROM user_constraints
WHERE LOWER(table_name) IN ( 'd_clients', 'copy_d_clients');
CREATE TABLE
copy_d_events AS ( SELECT *
FROM d_events); DESCRIBE
copy_d_events ; DESCRIBE
d_events;
SELECT * FROM d_events ;
SELECT * FROM
copy_d_events ; SELECT *
FROM user_constraints
WHERE LOWER(table_name) IN ( 'd_events', 'copy_d_events');
1. What are four functions that an ALTER statement can perform on constraints?
• ADD (uses modify clause to add not null on a column though)
• DROP
• ENABLE/DISABLE
2. Since the tables are copies of the original tables, the integrity rules are not passed onto the new
tables; only the column datatype definitions remain. You will need to add a PRIMARY KEY constraint
to the copy_d_clients table. Name the primary key copy_d_clients_pk . What is the syntax you used to
create the PRIMARY KEY constraint to the copy_d_clients.table?
ALTER TABLE copy_d_clients
ADD CONSTRAINT copy_d_clt_client_number_pk PRIMARY KEY (client_number);
SELECT *
FROM user_constraints
WHERE LOWER(table_name) = 'copy_d_clients' and constraint_type = 'P';
3. Create a FOREIGN KEY constraint in the copy_d_events table. Name the foreign key
copy_d_events_fk. This key references the copy_d_clients table client_number column. What is the
syntax you used to create the FOREIGN KEY constraint in the copy_d_events table?
ALTER TABLE copy_d_events
ADD CONSTRAINT copy_d_eve_client_number_fk FOREIGN KEY (client_number)
REFERENCES copy_d_clients (client_number) ENABLE;
SELECT *
FROM user_constraints
WHERE LOWER(table_name) = 'copy_d_events' and constraint_type = 'R';
4. Use a SELECT statement to verify the constraint names for each of the tables. Note that the
tablenames must be capitalized.
SELECT constraint_name, constraint_type, table_name
FROM user_constraints
WHERE table_name = UPPER('copy_d_events') ;
SELECT chld.table_name "Subject", chldcols.column_name "Subject Column Name",
chld.constraint_name "constraint_name in Subject", chld.constraint_type "constraint_type
in Subject", prnt.table_name "Parent of FK", prntcols.column_name "Parent's Column
Name", prnt.constraint_name "Parent PK"
FROM user_constraints chld LEFT OUTER JOIN user_constraints prnt ON
chld.r_constraint_name = prnt.constraint_name
LEFT OUTER JOIN user_cons_columns chldcols ON chld.constraint_name =
chldcols.constraint_name
LEFT OUTER JOIN user_cons_columns prntcols ON prnt.constraint_name =
prntcols.constraint_name
WHERE chld.table_name = UPPER('copy_d_events');
SELECT constraint_name, constraint_type, table_name
FROM user_constraints
WHERE table_name = UPPER('copy_d_clients') ;
SELECT chld.table_name "Subject", chldcols.column_name "Subject Column Name",
chld.constraint_name "constraint_name in Subject", chld.constraint_type "constraint_type
in Subject", prnt.table_name "Parent of FK", prntcols.column_name "Parent's Column
Name", prnt.constraint_name "Parent PK"
FROM user_constraints chld LEFT OUTER JOIN user_constraints prnt ON
chld.r_constraint_name = prnt.constraint_name
LEFT OUTER JOIN user_cons_columns chldcols ON chld.constraint_name =
chldcols.constraint_name
LEFT OUTER JOIN user_cons_columns prntcols ON prnt.constraint_name =
prntcols.constraint_name
WHERE chld.table_name = UPPER('copy_d_clients');
a. The constraint name for the primary key in the copy_d_clients table is .
COPY_D_CLT_CLIENT_NUMBER_PK
b. The constraint name for the foreign key in the copy_d_events table is
COPY_D_EVE_CLIENT_NUMBER_FK
5. Drop the PRIMARY KEY constraint on the copy_d_clients table. Explain your
results. ALTER TABLE copy_d_clients
DROP CONSTRAINT COPY_D_CLT_CLIENT_NUMBER_PK ;
I get message:
ORA-02273: this unique/primary key is referenced by some foreign keys
ALTER TABLE copy_d_clients
DROP CONSTRAINT COPY_D_CLT_CLIENT_NUMBER_PK CASCADE ;
SELECT constraint_name, constraint_type, table_name
FROM user_constraints
WHERE table_name = UPPER('copy_d_events') AND constraint_type = 'R';
The CASCADE option of the DROP clause causes any dependent constraints also to be dropped.
(After this I recreated the constraints following point 2 and 3 above)
6. Add the following event to the copy_d_events table. Explain your results.
ID NAM EVENT_D DESCRIP CO VENUE PACKAGE_ THEME_C CLIENT_NU
E ATE TION ST _ID CODE ODE MBER
14 Cline 15-Jul- Church 450 105 87 77 7125
0 Bas 2004 and 0
Mitzv Private
ah Home
formal
INSERT INTO
copy_d_events(client_number,id,name,event_date,description,cost,venue_id,package_code,th
eme_c ode)
VALUES(7125,140,'Cline Bas Mitzvah',TO_DATE('15-Jul-2004','dd-Mon-yyyy'),'Church
and Private Home formal',4500,105,87,77);
ORA-02291: integrity constraint (HKUMAR.COPY_D_EVE_CLIENT_NUMBER_FK) violated -
parent key not found
SELECT * FROM copy_d_clients WHERE client_number
= 7125; no data found
That is why I got above error ORA-02291.
7. Create an ALTER TABLE query to disable the primary key in the copy_d_clients table. Then add
the values from #5 to the copy_d_events table. Explain your results.
ALTER TABLE copy_d_clients
DISABLE CONSTRAINT COPY_D_CLT_CLIENT_NUMBER_PK ;
I get message ORA-02297: cannot disable constraint
(HKUMAR.COPY_D_CLT_CLIENT_NUMBER_PK) - dependencies exist.
ALTER TABLE copy_d_clients
DISABLE CONSTRAINT COPY_D_CLT_CLIENT_NUMBER_PK CASCADE;
Table altered.
8. Repeat question 5: Insert the new values in the copy_d_events table. Explain your results.
INSERT INTO
copy_d_events(client_number,id,name,event_date,description,cost,venue_id,package_code,th
eme_code)
VALUES(7125,140,'Cline Bas Mitzvah',TO_DATE('15-Jul-2004','dd-Mon-yyyy'),'Church and
Private Home formal',4500,105,87,77);
1 row(s) inserted.
9. Enable the primary-key constraint in the copy_d_clients table. Explain your results.
ALTER TABLE copy_d_clients
ENABLE CONSTRAINT COPY_D_CLT_CLIENT_NUMBER_PK CASCADE;
ORA-00933: SQL command not properly ended
ALTER TABLE copy_d_clients
ENABLE CONSTRAINT COPY_D_CLT_CLIENT_NUMBER_PK ;
In case of enable I don’t have option like CASCADE.
10. If you wanted to enable the foreign-key column and reestablish the referential integrity between
these two tables, what must be done?
ALTER TABLE copy_d_events
ENABLE CONSTRAINT COPY_D_EVE_CLIENT_NUMBER_FK;
ORA-02298: cannot validate (HKUMAR.COPY_D_EVE_CLIENT_NUMBER_FK) -
parent keys not found
So first I need to fix the row with client_number to a valid value/null.
But since client_number is not nullable, I will either have to delete invalid row or update that
row.
DELETE FROM copy_d_events WHERE
client_number NOT IN ( SELECT client_number FROM copy_d_clients);
1 row(s) deleted.
ALTER TABLE copy_d_events
ENABLE CONSTRAINT COPY_D_EVE_CLIENT_NUMBER_FK;
Table altered.
11. Why might you want to disable and then re-enable a constraint?
Generally to make bulk operations fast, where my input data is diligently sanitized and I am sure,
it is safe to save some time in this clumsy process.
12. Query the data dictionary for some of the constraints that you have created. How does the data
dictionary identify each constraint type?
Queries are same as in point 2,3, 4 above.
I can check value of CONSTRAINT_TYPE in all_constraints/user_constraints view.
• C - Check constraint
Sub-case - if I see SEARCH_CONDITION something like "FIRST_NAME" IS NOT NULL , its a NOT
NULL constraint.
• P - Primary key
• R - Referential integrity (fk)
• U - Unique key