0% found this document useful (0 votes)
5 views

Database 2nd Lab Notes

The document provides detailed instructions on creating a database tablespace, user, and various tables using SQL commands, along with constraints and data types. It also discusses common problems encountered during database operations and methods to resolve them, such as handling foreign key violations and data type mismatches. Additionally, it covers modifying tables and managing data integrity through constraints like ON DELETE CASCADE.

Uploaded by

Ai Cha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Database 2nd Lab Notes

The document provides detailed instructions on creating a database tablespace, user, and various tables using SQL commands, along with constraints and data types. It also discusses common problems encountered during database operations and methods to resolve them, such as handling foreign key violations and data type mismatches. Additionally, it covers modifying tables and managing data integrity through constraints like ON DELETE CASCADE.

Uploaded by

Ai Cha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Database 2nd Lab Notes

LAB 2 WEEK 1
Part 1
Creating a tablespace :

-- Create a normal (permanent) tablespace


CREATE TABLESPACE School_TBS --Specifies the name of the database
tablespace.
DATAFILE 'C:\School_TBS.dat' SIZE 100M --Specifies the full name of
the system file and its size in megabytes.
AUTOEXTEND ON --The size is increased automatically in case of
saturation
ONLINE; -- Available immediately upon creation

-- Create a temporary tablespace


CREATE TEMPORARY TABLESPACE School_TempTBS
TEMPFILE 'C:\School_TempTBS.dat' SIZE 100M
AUTOEXTEND ON;

Creating the User :


Create a DBASchool user by assigning him the two tablespaces created
previously;

CREATE USER DBASchool --spicify name of the user


IDENTIFIED BY YourPassword --set the password
DEFAULT TABLESPACE School_TBS --assign the permenant tablespace
TEMPORARY TABLESPACE School_tempTBS; --assign the temporary
tablespace

Granting all privilidges to the user :

GRANT ALL privileges to DBASchool;

PART 2:
Part II: Data Definition Language
4. Create the basic relationships.
5. Add all constraints
6. List the problems you encountered
7. How did you correct them

Creating The basic Relationships :


1. STUDENT Table

CREATE TABLE STUDENT (


StudentID NUMBER,
FirstName VARCHAR2(50),
LastName VARCHAR2(50),
BirthDate DATE,
Address VARCHAR2(100),
Email VARCHAR2(100),
Year NUMBER,
CONSTRAINT pk_student PRIMARY KEY (StudentID)
);

2. COURSE Table

CREATE TABLE COURSE (


CourseID NUMBER,
CourseName VARCHAR2(100),
CourseCoef NUMBER,
CourseCredits NUMBER,
CONSTRAINT pk_course PRIMARY KEY (CourseID)
);

3. ENROLLMENT Table

CREATE TABLE ENROLLMENT (


StudentID NUMBER,
CourseID NUMBER,
EnrollmentDate DATE,
FinalMark REAL,
CONSTRAINT pk_enrollment PRIMARY KEY (StudentID, CourseID),
CONSTRAINT fk_enrollment_student FOREIGN KEY (StudentID)
REFERENCES STUDENT(StudentID),
CONSTRAINT fk_enrollment_course FOREIGN KEY (CourseID)
REFERENCES COURSE(CourseID)
);

4. TEACHER Table

CREATE TABLE TEACHER (


TeacherID NUMBER,
CIV VARCHAR2(10),
FirstName VARCHAR2(50),
LastName VARCHAR2(50),
Salary REAL,
Email VARCHAR2(100),
Grade VARCHAR2(20),
CONSTRAINT pk_teacher PRIMARY KEY (TeacherID),
CONSTRAINT chk_civ CHECK (CIV IN ('Mr', 'Miss', 'Mrs')),
CONSTRAINT chk_grade CHECK (Grade IN ('Assistant', 'Associate',
'Full Professor'))
);

5. COURSE_ASSIGNMENT Table

CREATE TABLE COURSE_ASSIGNMENT (


CourseID NUMBER,
TeacherID NUMBER,
StartDate DATE,
EndDate DATE,
CONSTRAINT pk_course_assignment PRIMARY KEY (CourseID,
TeacherID),
CONSTRAINT fk_course_assignment_course FOREIGN KEY (CourseID)
REFERENCES COURSE(CourseID),
CONSTRAINT fk_course_assignment_teacher FOREIGN KEY (TeacherID)
REFERENCES TEACHER(TeacherID)
);

6. EXAM Table

CREATE TABLE EXAM (


ExamID NUMBER,
CourseID NUMBER,
ExamDate DATE,
ExamType VARCHAR2(50),
CONSTRAINT pk_exam PRIMARY KEY (ExamID),
CONSTRAINT fk_exam_course FOREIGN KEY (CourseID) REFERENCES
COURSE(CourseID),
CONSTRAINT chk_exam_type CHECK (ExamType IN ('Midterm',
'Final', 'Quiz'))
);

7. EXAM_RESULT Table

CREATE TABLE EXAM_RESULT (


ResultID NUMBER,
StudentID NUMBER,
ExamID NUMBER,
Score REAL,
CONSTRAINT pk_exam_result PRIMARY KEY (ResultID),
CONSTRAINT fk_exam_result_student FOREIGN KEY (StudentID)
REFERENCES STUDENT(StudentID),
CONSTRAINT fk_exam_result_exam FOREIGN KEY (ExamID) REFERENCES
EXAM(ExamID)
);

Summary of Data Types and Constraints


Date Attributes: All attributes ending with "Date" are of type DATE .
ID and Credits Attributes: Attributes ending with "ID" and CourseCredits are of
type NUMBER .
String Attributes: All other attributes are defined as VARCHAR2 , suitable for string
values.
Real Attributes: Salary , FinalMark , and Score are defined as REAL .
Domain Constraints:
CIV can only be 'Mr', 'Miss', or 'Mrs'.
Grade can only be 'Assistant', 'Associate', or 'Full Professor'.
ExamType can only be 'Midterm', 'Final', or 'Quiz'.

The Problems You Encountered


Some common problems you might encounter are:

1. Foreign key violation: Trying to insert a record in the Enrollments table


where the student_id or course_id doesn’t exist in the Students or
Courses table.
2. Invalid data type: If the data type of values being inserted doesn’t match the
column type (e.g., trying to insert a string into a NUMBER field).
3. Length issues: If values exceed the defined length of the VARCHAR2 field.
How Did You Correct Them
1. Foreign key violation: Ensure that the foreign key references a valid row in the
parent table. For example:

INSERT INTO Enrollments (enrollment_id, student_id, course_id,


enrollment_date)
VALUES (1, 100, 200, SYSDATE); -- Ensure student_id 100 and
course_id 200 exist in Students and Courses

2. Invalid data type: Verify that the data you are inserting matches the column's data
type. For example, ensure credits is a NUMBER and not a VARCHAR2 .
3. Length issues: Ensure the data being inserted fits within the defined length of the
column. For example, if the course_name column is defined as VARCHAR2(100) ,
make sure you don’t insert a string longer than 100 characte

SOME ADDITIONAL NOTES :


Syntax to create a table :

CREATE TABLE table_name (


column1 datatype(size) [NOT NULL] ,
column2 datatype ,

...
CONSTRAINT pk_constraint_name PRIMARY KEY (column1)
CONSTRAINT fk_constraint_name FORIGEN KEY (nameOfCol)
REFERENCES TABLE_NAME(nameOfCol)
CONSTRAINT check_exam CHECK (ExamType IN ('Midterm' , 'Final' ,
'Quiz')
);

LAB 2 WEEK 2
Part 1 :
to add an attribute to a table ' ALTER TABLE tableName ADD colName datatype'
to add costraints after creating the table : 'ALTER TABLE tableName MODIFY
attribute NOT NULL'
to reduce or enlarge an attribute : 'ALTER TABLE tableName MODIFY attriobute
VARCHAR(50);'
to delete an attribute 'ALTER TABLE TableName DROP COLUMN attributeName; '
to display table information 'DESC tableName'
to rename a column 'ALTER TABLE TableName RENAME COLUMN Address to
StudentAddress;'
to add a check interval constraint : ALTER TABLE TableName ADD CONSTRAINT
check_dates CHECK (StartDate < EndDate);

Add the HireDate attribute of Date type to


the Teacher table:

ALTER TABLE Teacher


ADD HireDate DATE;

Add the NOT NULL constraint for the Grade


and Salary attributes of the Teacher table:

ALTER TABLE Teacher


MODIFY Grade NOT NULL;

ALTER TABLE TEACHERALYT


MODIFY Salary NOT NULL;

Modify the length of the FirstName attribute


of the Teacher table (either enlarge or reduce):
To enlarge:

ALTER TABLE Teacher


MODIFY FirstName VARCHAR2(100); -- For example, enlarging to
100 characters

To reduce:

ALTER TABLE Teacher


MODIFY FirstName VARCHAR2(50); -- For example, reducing to 50
characters
Delete the HireDate column in the Teacher
table and verify deletion:
Delete the column:

ALTER TABLE Teacher


DROP COLUMN HireDate;

Verify the deletion:

DESC Teacher; -- or SELECT * FROM Teacher WHERE ROWNUM = 1;

Rename the Address column in the Student


table to StudentAddress and verify:
Rename the column:

ALTER TABLE Student


RENAME COLUMN Address TO StudentAddress;

Check the renaming:

DESC Student;

Add the constraint that the course start date


must be less than the end date:

ALTER TABLE Course


ADD CONSTRAINT check_dates CHECK (StartDate < EndDate);

PART 2 (DML): manipulating the instances


to add instanvces to your table INSERT INTO TableName (col1 , col2 ...)
VALUES (val1 , val2 ....);
to modify an attribute's value in a specific position : (eg . name = sara )

UPDATE tableName
SET salary = salary + 600;
WHERE Name = 'sara';
Fill all the tables by the instances
represented above
we use the INSERT statemlent to insert instances into a table .

INSERT INTO Teacher (TeacherID, FirstName, LastName, Grade, Salary,


HireDate)
VALUES (1, 'Sajida', 'Laichi', 'A', 60000, TO_DATE('2021-09-01',
'YYYY-MM-DD'));

-- Repeat for other tables such as Student, Course, etc.

we used TO_DATE() function to convert a string to the appropiate date format that
must be unified through all other columns : TO_DATE('string', 'format')

Problems
refrential integrity: to insert a record that is linked to another table by id but that
one instance with that id doesn't exist yet
can not insert null value to an attribute that has the constraint 'not_null'
if date data type does not fit in the default form , we simply change only the instance
that caused the problem by chaning its format

Suppose the salary of Pr. Sajida Laichi


increased by 5000DA. What should be done?
To update Pr. Sajida Laichi’s salary, you can use the UPDATE statement:

UPDATE Teacher
SET Salary = Salary + 5000
WHERE FirstName = 'Sajida' AND LastName = 'Laichi';

For Courses in the month of January, add 5


days to the start date. Disable constraint to
allow editing. Reactivate the constraint.
1. Disable the constraint on the course start date and end date (the one that
ensures the start date is less than the end date):

ALTER TABLE Course


DISABLE CONSTRAINT check_dates;
if we try to update the info before we disable the constraint , we get an error check
constraint is voilated

2. Update the start dates for courses in January:

UPDATE Course
SET StartDate = StartDate + 5
WHERE EXTRACT(MONTH FROM StartDate) = 1;

EXTRACT function for date datatypes in sql allows extracting day/month feild from
a date datatype.

3. Reactivate the constraint:

ALTER TABLE Course


ENABLE CONSTRAINT check_dates;

we get an error ORA-02293: cannot validate (DBASCHOOL.CHECK_DATES) -


check constraint violated
why? we have some instances that do not satisfy the constarint in the table.
we need it in immigration de données or exporting huge amount of data .
Another Case: delete a primary key (disable the foreign key constraint in the other
table )
- How to resolve ?
( enrollment has a foreign key that references the student table )
Delete Dependent Rows First: Manually remove the entries in the ENROLLMENT
table that reference the student before deleting the student record from the STUDENT
table.
Use ON DELETE CASCADE: Define the foreign key in the ENROLLMENT table with
the ON DELETE CASCADE option, allowing for automatic deletion of related enrollment
records when a student is deleted. !!

Delete all ‘Object-Oriented Programming’


courses. What are the problems
encountered?
to delete all instances with a specific attribute : 'DELETE FROM Course WHERE
courseName = 'OOP'

To delete a course, you would use:

DELETE FROM Course


WHERE CourseName = 'Object Oriented Programming';

Potential problems:

Foreign key constraints: If other tables (e.g., enrollments) reference the course,
deleting it could cause foreign key constraint violations.
integrity constraint (DBASCHOOL.FK_EXAM_COURSE) violated - child
record found
other tables use the course_id as foreign key in other tables , so we get an error
to resolve , when I create the foreign key , nzidlo on delete cascade

Definition: ON DELETE CASCADE is a setting for a foreign key in SQL that automatically
deletes related rows in the child table when the corresponding row in the parent table is
deleted. This maintains referential integrity by preventing orphaned records in the child
table.

How to Use:

1. Define it on a foreign key constraint when creating or altering a table.


2. When a row in the parent table is deleted, rows in the child table that reference it
are automatically removed.

CREATE TABLE ENROLLMENT (


EnrollmentID NUMBER PRIMARY KEY,
StudentID NUMBER,
FOREIGN KEY (StudentID) REFERENCES STUDENT(StudentID)
ON DELETE CASCADE --here
);

You might also like