SlideShare a Scribd company logo
1 of 22
Department of Computer Science and EngineeringPage 1
Exercises:SQL constraints
Question1: Considerthe following schema to
Employee (eid: integer, ename: string, age: integer, salary: real, office_location string)
A) Create a table with following constraints:
- default office_location is ‘Chandigarh’
- records of only those employees will be stored in the table who have more than 10,000
salary and minimum 25 years of age.
- Employee id and employee name should Unique values and cannot be null.
NOTE: Employee id is not a primary Key.
B) Insert values into tables confirming to constraints in question 1.
-5 records with default office location ‘Chandigarh’, 3 males and 2 females, salary between 15000 to
27000, age 25 to 35.
-5 records with office location ‘Delhi’, 2 males and 3 females, salary 45000 to 55000, age 36 to 50.
Question 2: Defining constraint names, Modifying, adding and dropping
constraints
a) Defining constraint names for constraints.
b) Change the salary check condition to 20 from 25
c) Change the salary check condition to 10000 from 20000
d) Adding unique constraint at mobile number
e) Adding default constraint on newly added department name column
f) Dropping constraints
Question 3: Create a table Employee_new with following attributes
EMPLOYEE_ID number | EMP_NAME varchar(30) | EMAIL varchar(30) | PHONE_NUMBER
number | HIRE_DATE date | GENDER char(1) | JOB_TYPE varchar(20) | SALARY number (10,2)
Create a table Employee_new with following constraints:
a) Employee_id should be an identity column generated by default with starting value of 1001 and
incremented by 1.
b) Employee name attribute should not be null.
c) Email Address attribute should be unique and not null with check constraint that email value should have
@cumail.in string at the end.
d) Phone number --not null and unique.
Department of Computer Science and EngineeringPage 2
e) Hire date should be by default the system date.
f) Gender column should have only ‘M’ and ‘F’ values.
h) Job_type with check constraint for {‘Academics’,’Administration’, ‘Accounts’, ‘Marketing’} values.
i) Salary (with check constraint) should be between 20000 to 50000 for all employees.
Supplementary Problems:
1) For the table created in question 3 in exercises section:
a) Insert any 20 values corresponding to the attributes.
b) Assign constraint names to constraints wherever applicable.
c) Modify constraints.
d) Disable and enable different constraints.
e) Drop check constraints.
2) Create a table CLIENTS with following attributes:
Client id number, client_name varchar2(30), client_email varchar(40), order_number varchar(30), order_date
date, order_quantity number(10), shipping_date date, client_contact number(10)
With following constraints
a) Client_id should be an identity column generated by default with 100 as starting value and gets
incremented by 1.
b) Client_name should be not null
c) Client_email should be checked for @ and .characters.
d) Order number should begin with ‘O’ character followed by unique number.
e) Order_date should be system date.
f) Order_quantity should be greater than zero.
g) Shipping_date should be greater than order_date.
h) Client_contact attribute should be not null and unique.
Question 3: How to check the different constraints applied on a table using user_constraints table?
Answer 1:
CREATE TABLE Employee2 ( eid number NOTNULL,
ename VARCHAR(10) NOT NULL,
age number CHECK (age>=25),
salary number(10,2) CHECK ( salary>=10000),
OFFICE_LOCATION VARCHAR2(50) DEFAULT 'Chandigarh',
Department of Computer Science and EngineeringPage 3
UNIQUE(eid,ename));
INSERT INTO Employee2(eid,ename,age,salary) VALUES (76,'SMIITH',24,20000);
INSERT INTO Employee2(eid,ename,age,salary) VALUES (77,'SUMIIT',25,19000);
INSERT INTO Employee2(eid,ename,age,salary) VALUES (78,'NEHAA',26,9000);
select * from Employee2;
A) Use INSERT INTO command
-
Answer 2: Defining constraint names, Modifying, adding and droping constraints
a) Defining constraint names for constraints.
CREATE TABLE Employee
( eid number CONSTRAINT cons_e NOT NULL,
ename VARCHAR(10) CONSTRAINT cons_name NOT NULL,
age number CONSTRAINT age_check CHECK (age>=25),
salary number(10,2) CONSTRAINT salary_check CHECK ( salary>=10000 ),
OFFICE_LOCATION VARCHAR2(50) DEFAULT 'Chandigarh',
CONSTRAINT uni_com UNIQUE (eid,ename))
b) Change the age check condition to 20 from 25
Drop the existing age_check constraint first using following command
ALTER TABLE employee drop constraint age_check;
Then add check constraint to age column with new condition
alter table employee modify age check(age>=20);
c) Change the salary check condition to 10000 from 20000
ALTER TABLE employee modify CONSTRAINT salary_check (salary >5000)
Gives error
Drop the existing salary_check constraint using
ALTER TABLE employee drop constraint salary_check;
Then add new constraint with constraint_name using
ALTER TABLE employee ADD CONSTRAINT salary_check CHECK (salary >20000);
d) Adding unique constraint at mobile number
Add a column contact number in the existing table using
ALTER TABLE employee add (contact number);
Then add unique constraint to this new column
ALTER TABLE employee add UNIQUE (contact);
Department of Computer Science and EngineeringPage 4
e) Adding default constraint on newly added department name column
Add a column dept_name in the existing table using
ALTER TABLE employee add (dept_name varchar(20))
Then add default constraint to this new column
alter table employee add dept_name VARCHAR2(50) default 'CSE'
f) Dropping constraints
Drop default constraint on office_location
ALTER TABLE employee modify office_location default null;
We cannot drop the default constraint but it value can be changed to null
Dropping constraint salary check
ALTER TABLE employee_grade11 drop constraint salary_check;
Dropping unique constraint
ALTER TABLE employee_grade11 drop constraint uni_com
Question 3: Create a table Employee_new with following attributes
EMPLOYEE_ID number | EMP_NAME varchar(30) | EMAIL varchar(30) | PHONE_NUMBER number |
HIRE_DATE date | GENDER char(1) | JOB_TYPE varchar(20) | SALARY number (10,2)
Constraints:
a) Employee_id should be an identity column generated by default with starting value of 1001 and
incremented by 1.
b) Employee name attribute should not be null.
c) Email Address attribute should be unique and not null with check constraint that email value should have
@cumail.in string at the end.
d) Phone number --not null and unique.
e) Hire date should be by default the system date.
f) Gender column should have only ‘M’ and ‘F’ values.
h) Job_type with check constraint for {‘Academics’,’Administration’, ‘Accounts’, ‘Marketing’} values.
i) Salary (with check constraint) should be between 20000 to 50000 for all employees.
Answer 3:
Create table employee_new (employee_ID number GENERATED BY DEFAULT AS IDENTITY start with
100 increment by 1,
Emp_name varchar(30) NOTNULL,
Email varchar(40) NOT NULL UNIQUE check( email LIKE '%@cumail.in'), Phone_number number(10)
NOT NULL UNIQUE,
Department of Computer Science and EngineeringPage 5
HIRE_date date default sysdate,
gender char(1) check( gender IN (‘M’,’F’),
JOB_TYPE varchar(30) check( job_type in(‘Academics’, ‘Accounts’, ‘Administration’, ‘Marketing’)),
salary number(10,2) check (salary between 20000.00 and 45000.00));
Supplementary Problems:
3) For the table created in question 3 in exercises section:
f) Insert any 20 values corresponding to the attributes.
g) Assign constraint names to constraints wherever applicable.
h) Modify constraints.
i) Disable and enable different constraints.
j) Drop check constraints.
4) Create a table CLIENTS with following attributes:
Client id number, client_name varchar2(30), client_email varchar(40), order_number varchar(30), order_date
date, order_quantity number(10), shipping_date date, client_contact number(10)
With following constraints
i) Client_id should be an identity column generated by default with 100 as starting value and gets
incremented by 1.
j) Client_name should be not null
k) Client_email should be checked for @ and .characters.
l) Order number should begin with ‘O’ character followed by unique number.
m) Order_date should be system date.
n) Order_quantity should be greater than zero.
o) Shipping_date should be greater than order_date.
p) Client_contact attribute should be not null and unique.
a) Create the table with given constraints.
CREATE TABLE client12 (
client_id NUMBER GENERATED BY DEFAULT AS IDENTITY start with 100 increment by 1,
client_name VARCHAR2(50) constraint con_name NOT NULL,
client_email varchar(40) constraint con_email NOT NULL UNIQUE check( client_email LIKE '%@%.%'),
order_number varchar(30) constraint con_order NOT NULL UNIQUE check (order_number LIKE 'O%'),
order_date date default sysdate,
order_quantity number(10) constraint con_quan check (order_quantity>0),
Department of Computer Science and EngineeringPage 6
shipping_date date,
constraint con_shipping check(shipping_date > order_date),
client_contact number(10) constraint con_contact not null unique );
b) Insert records corresponding to attribute values.
c) Add a composite unique key constraint on email and phone number.
Alter table client12 add constraint com_uni UNIQUE( client_email, client_contact);
Question 3: How to check the different constraints applied on a table.
To check all constraints applied on a particular table then you need to query the USER_CONSTRAINTS view like
this:
SELECT * FROM user_constraints WHERE table_name = '<your table name>' AND constraint_name = '<your
constraint name>';
Select * from user_constraints where table_ name = ‘EMPLOYEE_GRADE1’
NOTE: The table name has to be specified in CAPITALS.
NOTE: In Table 1 given below only few of the columns have been shown. The next Table 2 gives the
description of all columns in the user_constraints table.
Table 1:
Department of Computer Science and EngineeringPage 7
OWNER CONSTRAIN
T_NAME
CONSTR
AINT
_TYPE
TABLE_
NAME
SEAR
CH_C
ONDI
TION
SEARCH_CO
NDITION_VC
R_OWNER
SQL_VNWXN
PUTDLEHTCC
XPROWHQXT
T
SYS_C00285
04536
C EMPLOY
EE_GRA
DE1
EID""
IS
NOT
NULL
EID"" IS NOT
NULL
-
SQL_VNWXN
PUTDLEHTCC
XPROWHQXT
T
SYS_C00285
04537
C EMPLOY
EE_GRA
DE1
ENAM
E"" IS
NOT
NULL
ENAME"" IS
NOT NULL
-
SQL_VNWXN
PUTDLEHTCC
XPROWHQXT
T
SYS_C00285
04538
C EMPLOY
EE_GRA
DE1
age&g
t;=25
age&gt;=25 -
SQL_VNWXN
PUTDLEHTCC
XPROWHQXT
T
SYS_C00285
04539
C EMPLOY
EE_GRA
DE1
salary
&gt;=
10000
salary&gt;=1
0000
-
SQL_VNWXN
PUTDLEHTCC
XPROWHQXT
T
SYS_C00285
04540
U EMPLOY
EE_GRA
DE1
- - -
Table 2:
Department of Computer Science and EngineeringPage 8
Column Datatype NULL Description
OWNER VARCHAR2(128)
Owner of the constraint
definition
CONSTRAINT_NAME VARCHAR2(128)
Name of the constraint
definition
CONSTRAINT_TYPE VARCHAR2(1)
Type of the constraint
definition:
C - Check constraint on
a table
P - Primary key
U - Unique key
R - Referential integrity
V - With check option,
on a view
O - With read only, on a
view
H - Hash expression
F - Constraint that
involves a REF column
Department of Computer Science and EngineeringPage 9
S - Supplemental
logging
TABLE_NAME VARCHAR2(128)
Name associated with
the table (or view) with
the constraintdefinition
SEARCH_CONDITION LONG
Text of search condition
for a check constraint.
This column returns the
correct value only when
the row originates from
the current container.
SEARCH_CONDITION_V
C
VARCHAR2(4000
)
Text of search condition
for a check constraint.
This column may
truncate the search
condition.
R_OWNER VARCHAR2(128)
Owner of the table
referred to in a
referential constraint
R_CONSTRAINT_NAME VARCHAR2(128)
Name of the unique
constraint definition for
the referenced table
DELETE_RULE VARCHAR2(9)
Delete rule for a
referential constraint:
CASCADE
SET NULL
NO ACTION
Department of Computer Science and EngineeringPage 10
STATUS VARCHAR2(8)
Enforcement status of
the constraint:
ENABLED
DISABLED
DEFERRABLE VARCHAR2(14)
Indicates whether the
constraint is deferrable
(DEFERRABLE) or not
(NOT DEFERRABLE)
DEFERRED VARCHAR2(9)
Indicates whether the
constraint was initially
deferred (DEFERRED)
or not (IMMEDIATE)
VALIDATED VARCHAR2(13)
When STATUS =
ENABLED, possible
values are:
VALIDATED - All data
obeys the constraint
(thatis,the existingdata
in the table was
validated when the
constraint was enabled,
as well as any
subsequent data
entered into the table)
Department of Computer Science and EngineeringPage 11
NOT VALIDATED - All
data may not obey the
constraint (that is, the
existingdatainthe table
was not validated when
the constraint was
enabled,butsubsequent
data entered into the
table was validated)
When STATUS =
DISABLED, possible
values are:
VALIDATED - All data
obeys the constraint,
but the unique index on
the constraint has been
dropped. This setting is
useful in data
warehousing
environments, but has
some restrictions. Refer
to Oracle Database Data
Warehousing Guide for
more information on
this setting.
NOT VALIDATED - All
data may not obey the
constraint
Department of Computer Science and EngineeringPage 12
GENERATED VARCHAR2(14)
Indicates whether the
name of the constraint
is user-generated
(USER NAME) or
system-generated
(GENERATED NAME)
BAD VARCHAR2(3)
Indicates whether this
constraint specifies a
centuryinan ambiguous
manner (BAD) or not
(NULL). To avoid errors
resulting from this
ambiguity, rewrite the
constraint using the
TO_DATE function with
a four-digit year.
See Also: the TO_DATE
function in Oracle
DatabaseSQL Language
Reference and Oracle
Database Development
Guide
RELY VARCHAR2(4)
When VALIDATED =
NOT VALIDATED, this
column indicates
whether the constraint
is to be taken into
account for query
rewrite (RELY) or not
(NULL).
When VALIDATED =
VALIDATED, this
column is not
meaningful.
Department of Computer Science and EngineeringPage 13
LAST_CHANGE DATE
When the constraint
was last enabled or
disabled
INDEX_OWNER VARCHAR2(128)
Name of the user
owning the index
INDEX_NAME VARCHAR2(128)
Name of the index (only
shown for unique and
primary-keyconstraints)
INVALID VARCHAR2(7)
Indicates whether the
constraint is invalid
(INVALID) or not (NULL)
VIEW_RELATED VARCHAR2(14)
Indicates whether the
constraint depends on a
view (DEPEND ON
VIEW) or not (NULL)
ORIGIN_CON_ID VARCHAR2(256)
The ID of the container
where the data
originates. Possible
values include:
0: This value is used for
rows in non-CDBs. This
value is not used for
CDBs.
n: This value is used for
rows containing data
that originate in the
containerwithcontainer
ID n (n = 1 if the row
originates in root)
Department of Computer Science and EngineeringPage 14
EXERCISE QUESTIONS:Primary Key and ForeignKey
The following relational schema is given:
Emp(eid: integer, ename:string, age:integer, salary:real)
Works(eid:integer, did: integer, project_name:string)
Dept(did: integer, dname: string, budget: real, managerid: integer)
Ques 1: For basedon the given relationalschema.
a) Create emp, dept and works table with the possible primary and foreign key constraints.
CREATE TABLE Emp( eid INTEGER,
ename varCHAR(30),
age INTEGER ,
salary REAL,
constraint cons_emp_pk
PRIMARY KEY (eid))
CREATE TABLE Dept(
did INTEGER,
dname varchar2(30),
buget REAL,
managerid INTEGER ,
constraint cons_dept_pk
PRIMARY KEY (did),
constraint cons_dept_fk
Department of Computer Science and EngineeringPage 15
FOREIGN KEY (managerid) REFERENCES Emp (eid) on delete cascade)
CREATE TABLE Works (
eid INTEGER,
did INTEGER,
project_name varchar(20),
constraint cons_works_fk
FOREIGN KEY (did) REFERENCES Dept (did) on delete set null
constraint cons_works_fk1
FOREIGN KEY(eid) REFERENCES emp(eid) on delete cascade
insert into emp values(101,'John Doe',32,15000);
insert into emp values(102,'Toy',32,15000);
insert into emp values(103,'Ralph',35,35000);
insert into emp values(104,'Joe',37,50000);
insert into emp values(105,'William',40,75000);
select * from emp;
insert into Dept values(11,'CSE',50000,101);
insert into dept values (12,'ME',100000,102);
insert into dept values (13,'ECE',75000,103);
select * from dept
insert into works values(101,11,'Research');
insert into works values (102,11,'Academics');
insert into works values (103,12,'Administration');
Department of Computer Science and EngineeringPage 16
insert into works values (104,13,'Administration');
insert into works values (105,12,'Research');
select * from works order by eid
b) Delete a record from works table with eid = 105 and check whether referential integrity constraint
violates or not.
delete from works where eid = 105 -- eid entry corresponding to 105 gets deletedfrom works table and no
effect on parent table emp as works is the child table
c) Delete a record from emp table with eid = 104 and check whether referential integrity constraint
violates or not.
delete from emp where eid = 104 – eid entry corresponding to 104 gets deleted from both parent and child
table as a result of ‘on delete cascade’
d) Delete a record from dept table with did = 12 and check whether referential integrity constraint
violates or not.
delete from dept where did = 12 – this will remove the corresponding value from dept table and set value to ‘–‘
i.e. null for did column in works table as a result of ‘on delete set null’
EI
D
DI
D
PROJECT_NAM
E
10
3
- Administration
10
1
11 Research
10
2
11 Academics
Department of Computer Science and EngineeringPage 17
e) Changing on delete set null to on delete NO ACTION
- NO ACTION cannot be used in the script to define a NO ACTION constraint in Oracle.
- By default if on delete clause is not mentioned in foreign key constraint then it represents no action.
Firstly drop the existing constraint using
-alter table works drop constraint cons_works_fk
Secondly, add the constraint without on delete clause which means NO ACTION Referential action
- alter table works add constraint cons_works_fk FOREIGN KEY(did) REFERENCES
dept(did)
Now, execute the following query
o delete from dept where did = 11
The following error is generated
ORA-02292: integrity constraint
(SQL_GVLIADHQLTEEFZAHBPGHKPSVD.CONS_WORKS_FK) violated - child
record found ORA-06512: at "SYS.DBMS_SQL", line 1721
NOTE: ON DELETE SET DEFAULT, ON UPDATE CASCADE, ON UPDATE SET NULL, ON UPDATE
SET DEFAULT are not supported by ORACLE
Question 2: How to define self referential integrity constraint.
Solution: Self referential integrity constraint - In this type of referential integrity, foreign key references the
primary key of same table.
Department of Computer Science and EngineeringPage 18
For example we have employee table with attributes emp_id, emp_name, job_title and manager_id. As
manager has to be an employee with some emp_id so Manager_id is self referring the emp_id key in the same
table.
create table employee(
emp_id varchar(20) check(emp_id LIKE'E%'),
emp_name varchar(20) not null,
job_title varchar(20) not null,
manager_id varchar(20) check(manager_id LIKE 'E%'),
Constraint cons_pk PRIMARY KEY (emp_id),
Constraint cons_fk Foreign key(manager_id) references employee(emp_id))
insert into employee values('E101', 'Akash', 'Manager', 'E101')
insert into employee values('E102', 'Ridhima', 'Executive', 'E101')
insert into employee values('E103', 'Vansh', 'Manager', 'E103')
insert into employee values('E104', 'Rahul', 'Executive', 'E101')
insert into employee values('E105', 'Poorva', 'Senior_executive', 'E103')
insert into employee values('E106', 'Rohandeep', 'Senior_Executive', 'E103')
select * from employee order by emp_id
EMP_I
D
EMP_NA
ME
JOB_TITLE
MANAGER_I
D
E101 Akash Manager E101
E102 Ridhima Executive E101
E103 Vansh Manager E103
E104 Rahul Executive E101
E105 Poorva
Senior_executi
ve
E103
E106 Rohandeep
Senior_Executi
ve
E103
Now, execute following queries
Department of Computer Science and EngineeringPage 19
1. insert into employee values('E107', 'Riva', 'Manager', 'E108') --- it gives integrity constraint violation
error as manager_id 108 is not a valid emp_id.
2. delete from employee where emp_id = 'E104' – deletes row successfully
3. delete from employee where emp_id = 'E101' --- it gives referential integrity constraint error
4. To delete an employee who is also the manager, change its manages id to null and then delete the
corresponding entry
update employee set manager_id = null where manager_id = 'E101'
select * from employee
EMP_I
D
EMP_NA
ME
JOB_TITLE
MANAGER_I
D
E101 Akash Manager -
E102 Ridhima Executive -
E103 Vansh Manager E103
E104 Rahul Executive -
E105 Poorva
Senior_executi
ve
E103
E106 Rohandeep
Senior_Executi
ve
E103
Delete from employee where emp_id = ‘E101’ –deleted successfully
5. Add self referential integrity constraint with ON DELETE CASCADE
Drop table employee
Create table with on delete cascade referential action
create table employee(
emp_id varchar(20) check(emp_id LIKE'E%'),
emp_name varchar(20) not null,
job_title varchar(20) not null,
Department of Computer Science and EngineeringPage 20
manager_id varchar(20) check(manager_id LIKE 'E%'),
Constraint cons_pk PRIMARY KEY (emp_id),
Constraint cons_fk Foreign key(manager_id) references employee(emp_id) on delete cascade)
insert into employee values('E101', 'Akash', 'Manager', 'E101')
insert into employee values('E102', 'Ridhima', 'Executive', 'E101')
insert into employee values('E103', 'Vansh', 'Manager', 'E103')
insert into employee values('E104', 'Rahul', 'Executive', 'E101')
insert into employee values('E105', 'Poorva', 'Senior_executive', 'E103')
insert into employee values('E106', 'Rohandeep', 'Senior_Executive', 'E103')
delete from employee where emp_id = 'E101' – executes successfully
EMP_I
D
EMP_NA
ME
JOB_TITLE
MANAGER_I
D
E103 Vansh Manager E103
E105 Poorva
Senior_executi
ve
E103
E106 Rohandeep
Senior_Executi
ve
E103
Ques 3: The following table has two attributes A and C where A is the primary key and C is the foreign key
referencing A with on-delete cascade.
A C
-----
2 4
3 4
4 3
5 2
7 2
Department of Computer Science and EngineeringPage 21
9 5
6 4
The set of all tuples that must be additionally deleted to preserve referential integrity when the tuple (2,4) is
deleted is:
Ans: (5,2), (7,2) and (9,5) as on deletion of tuple 2,4 leads to deletion of 5,2 and 7,2 and (5,2) deletion leads to
deletion of 9,5.
CREATE TABLE test_fk
(
A number PRIMARY KEY,
C number,
FOREIGN KEY(C) REFERENCES test_fk(A) on delete cascade)
insert into test_fk values (2,2)
insert into test_fk values (3,3)
insert into test_fk values (4,3)
insert into test_fk values (5,2)
insert into test_fk values (7,2)
insert into test_fk values (9,5)
insert into test_fk values (6,4)
update test_fk set c=4 where a = 2;
update test_fk set c=4 where a = 3;
select * from test_fk order by a
delete from test_fk where a = 2 and c = 4 – rows deleted are (2,4), (5,2),(7,2) and (9,5) will be deleted
A C
3 4
4 3
6 4
Department of Computer Science and EngineeringPage 22
Ques 4: In table T1, P is the primary key, Q is the foreign key referencing R in table T2 with on-delete cascade
and on-update cascade. In table T2, R is the primary key and S is the foreign key referencing P in the table T1
with on-delete set NULL and on-update cascade. In order to delete record (3,8) from table T1, (8,3) T2, (5) T1,
(2) T1 numbers of additional record that need to be deleted from table T1 is:
Ans:Given,
● Q -> R(Primary Key)
● S -> P (Primary Key)
Entry to be deleted – P (3) and Q(8)
● Q can be deleted directly
● Now, S – > P but the relationship given is on delete set NULL, Therefore when we delete 3 from T1
,the entry in T2 having 3 will be NULL.
Therfore, Answer is 0 entries.
Kindly check entries corresponding to (8,3) T2, (5) T1, (2) T1

More Related Content

Similar to Day 7 Worksheet.docx

284566820 1 z0-061(1)
284566820 1 z0-061(1)284566820 1 z0-061(1)
284566820 1 z0-061(1)panagara
 
Database management system file
Database management system fileDatabase management system file
Database management system fileAnkit Dixit
 
Rdbms class test ii sep 2019
Rdbms class test  ii sep 2019Rdbms class test  ii sep 2019
Rdbms class test ii sep 2019ARVIND SARDAR
 
Sql task answers
Sql task answersSql task answers
Sql task answersNawaz Sk
 
SQL practice questions set
SQL practice questions setSQL practice questions set
SQL practice questions setMohd Tousif
 
Manipulating Data Oracle Data base
Manipulating Data Oracle Data baseManipulating Data Oracle Data base
Manipulating Data Oracle Data baseSalman Memon
 
Plsql task
Plsql taskPlsql task
Plsql taskNawaz Sk
 
Informatics practises 12th CBSE INDIA 2012-2013 MAIN EXAM paper
Informatics practises 12th CBSE INDIA 2012-2013 MAIN EXAM paperInformatics practises 12th CBSE INDIA 2012-2013 MAIN EXAM paper
Informatics practises 12th CBSE INDIA 2012-2013 MAIN EXAM paperHarish Gyanani
 
SQL practice questions - set 3
SQL practice questions - set 3SQL practice questions - set 3
SQL practice questions - set 3Mohd Tousif
 
Microsoft MCSA 70-457 it exams dumps
Microsoft MCSA 70-457 it exams dumpsMicrosoft MCSA 70-457 it exams dumps
Microsoft MCSA 70-457 it exams dumpslilylucy
 

Similar to Day 7 Worksheet.docx (20)

Sql lab experiments
Sql lab experimentsSql lab experiments
Sql lab experiments
 
284566820 1 z0-061(1)
284566820 1 z0-061(1)284566820 1 z0-061(1)
284566820 1 z0-061(1)
 
Database management system file
Database management system fileDatabase management system file
Database management system file
 
Rdbms class test ii sep 2019
Rdbms class test  ii sep 2019Rdbms class test  ii sep 2019
Rdbms class test ii sep 2019
 
rdbms practical record
rdbms practical recordrdbms practical record
rdbms practical record
 
Ip xi iii_ut_14-15
Ip xi iii_ut_14-15Ip xi iii_ut_14-15
Ip xi iii_ut_14-15
 
GPREC DBMS Notes 1
GPREC DBMS Notes 1GPREC DBMS Notes 1
GPREC DBMS Notes 1
 
Sql task answers
Sql task answersSql task answers
Sql task answers
 
Les08
Les08Les08
Les08
 
Cs practical file
Cs practical fileCs practical file
Cs practical file
 
SQL practice questions set
SQL practice questions setSQL practice questions set
SQL practice questions set
 
Manipulating Data Oracle Data base
Manipulating Data Oracle Data baseManipulating Data Oracle Data base
Manipulating Data Oracle Data base
 
Plsql task
Plsql taskPlsql task
Plsql task
 
Informatics practises 12th CBSE INDIA 2012-2013 MAIN EXAM paper
Informatics practises 12th CBSE INDIA 2012-2013 MAIN EXAM paperInformatics practises 12th CBSE INDIA 2012-2013 MAIN EXAM paper
Informatics practises 12th CBSE INDIA 2012-2013 MAIN EXAM paper
 
SQL practice questions - set 3
SQL practice questions - set 3SQL practice questions - set 3
SQL practice questions - set 3
 
Access practicals 2015
Access practicals 2015Access practicals 2015
Access practicals 2015
 
Microsoft MCSA 70-457 it exams dumps
Microsoft MCSA 70-457 it exams dumpsMicrosoft MCSA 70-457 it exams dumps
Microsoft MCSA 70-457 it exams dumps
 
Medium Questions
Medium QuestionsMedium Questions
Medium Questions
 
1 z1 051
1 z1 0511 z1 051
1 z1 051
 
zekeLabs sql-slides
zekeLabs sql-slideszekeLabs sql-slides
zekeLabs sql-slides
 

Recently uploaded

EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 

Recently uploaded (20)

EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 

Day 7 Worksheet.docx

  • 1. Department of Computer Science and EngineeringPage 1 Exercises:SQL constraints Question1: Considerthe following schema to Employee (eid: integer, ename: string, age: integer, salary: real, office_location string) A) Create a table with following constraints: - default office_location is ‘Chandigarh’ - records of only those employees will be stored in the table who have more than 10,000 salary and minimum 25 years of age. - Employee id and employee name should Unique values and cannot be null. NOTE: Employee id is not a primary Key. B) Insert values into tables confirming to constraints in question 1. -5 records with default office location ‘Chandigarh’, 3 males and 2 females, salary between 15000 to 27000, age 25 to 35. -5 records with office location ‘Delhi’, 2 males and 3 females, salary 45000 to 55000, age 36 to 50. Question 2: Defining constraint names, Modifying, adding and dropping constraints a) Defining constraint names for constraints. b) Change the salary check condition to 20 from 25 c) Change the salary check condition to 10000 from 20000 d) Adding unique constraint at mobile number e) Adding default constraint on newly added department name column f) Dropping constraints Question 3: Create a table Employee_new with following attributes EMPLOYEE_ID number | EMP_NAME varchar(30) | EMAIL varchar(30) | PHONE_NUMBER number | HIRE_DATE date | GENDER char(1) | JOB_TYPE varchar(20) | SALARY number (10,2) Create a table Employee_new with following constraints: a) Employee_id should be an identity column generated by default with starting value of 1001 and incremented by 1. b) Employee name attribute should not be null. c) Email Address attribute should be unique and not null with check constraint that email value should have @cumail.in string at the end. d) Phone number --not null and unique.
  • 2. Department of Computer Science and EngineeringPage 2 e) Hire date should be by default the system date. f) Gender column should have only ‘M’ and ‘F’ values. h) Job_type with check constraint for {‘Academics’,’Administration’, ‘Accounts’, ‘Marketing’} values. i) Salary (with check constraint) should be between 20000 to 50000 for all employees. Supplementary Problems: 1) For the table created in question 3 in exercises section: a) Insert any 20 values corresponding to the attributes. b) Assign constraint names to constraints wherever applicable. c) Modify constraints. d) Disable and enable different constraints. e) Drop check constraints. 2) Create a table CLIENTS with following attributes: Client id number, client_name varchar2(30), client_email varchar(40), order_number varchar(30), order_date date, order_quantity number(10), shipping_date date, client_contact number(10) With following constraints a) Client_id should be an identity column generated by default with 100 as starting value and gets incremented by 1. b) Client_name should be not null c) Client_email should be checked for @ and .characters. d) Order number should begin with ‘O’ character followed by unique number. e) Order_date should be system date. f) Order_quantity should be greater than zero. g) Shipping_date should be greater than order_date. h) Client_contact attribute should be not null and unique. Question 3: How to check the different constraints applied on a table using user_constraints table? Answer 1: CREATE TABLE Employee2 ( eid number NOTNULL, ename VARCHAR(10) NOT NULL, age number CHECK (age>=25), salary number(10,2) CHECK ( salary>=10000), OFFICE_LOCATION VARCHAR2(50) DEFAULT 'Chandigarh',
  • 3. Department of Computer Science and EngineeringPage 3 UNIQUE(eid,ename)); INSERT INTO Employee2(eid,ename,age,salary) VALUES (76,'SMIITH',24,20000); INSERT INTO Employee2(eid,ename,age,salary) VALUES (77,'SUMIIT',25,19000); INSERT INTO Employee2(eid,ename,age,salary) VALUES (78,'NEHAA',26,9000); select * from Employee2; A) Use INSERT INTO command - Answer 2: Defining constraint names, Modifying, adding and droping constraints a) Defining constraint names for constraints. CREATE TABLE Employee ( eid number CONSTRAINT cons_e NOT NULL, ename VARCHAR(10) CONSTRAINT cons_name NOT NULL, age number CONSTRAINT age_check CHECK (age>=25), salary number(10,2) CONSTRAINT salary_check CHECK ( salary>=10000 ), OFFICE_LOCATION VARCHAR2(50) DEFAULT 'Chandigarh', CONSTRAINT uni_com UNIQUE (eid,ename)) b) Change the age check condition to 20 from 25 Drop the existing age_check constraint first using following command ALTER TABLE employee drop constraint age_check; Then add check constraint to age column with new condition alter table employee modify age check(age>=20); c) Change the salary check condition to 10000 from 20000 ALTER TABLE employee modify CONSTRAINT salary_check (salary >5000) Gives error Drop the existing salary_check constraint using ALTER TABLE employee drop constraint salary_check; Then add new constraint with constraint_name using ALTER TABLE employee ADD CONSTRAINT salary_check CHECK (salary >20000); d) Adding unique constraint at mobile number Add a column contact number in the existing table using ALTER TABLE employee add (contact number); Then add unique constraint to this new column ALTER TABLE employee add UNIQUE (contact);
  • 4. Department of Computer Science and EngineeringPage 4 e) Adding default constraint on newly added department name column Add a column dept_name in the existing table using ALTER TABLE employee add (dept_name varchar(20)) Then add default constraint to this new column alter table employee add dept_name VARCHAR2(50) default 'CSE' f) Dropping constraints Drop default constraint on office_location ALTER TABLE employee modify office_location default null; We cannot drop the default constraint but it value can be changed to null Dropping constraint salary check ALTER TABLE employee_grade11 drop constraint salary_check; Dropping unique constraint ALTER TABLE employee_grade11 drop constraint uni_com Question 3: Create a table Employee_new with following attributes EMPLOYEE_ID number | EMP_NAME varchar(30) | EMAIL varchar(30) | PHONE_NUMBER number | HIRE_DATE date | GENDER char(1) | JOB_TYPE varchar(20) | SALARY number (10,2) Constraints: a) Employee_id should be an identity column generated by default with starting value of 1001 and incremented by 1. b) Employee name attribute should not be null. c) Email Address attribute should be unique and not null with check constraint that email value should have @cumail.in string at the end. d) Phone number --not null and unique. e) Hire date should be by default the system date. f) Gender column should have only ‘M’ and ‘F’ values. h) Job_type with check constraint for {‘Academics’,’Administration’, ‘Accounts’, ‘Marketing’} values. i) Salary (with check constraint) should be between 20000 to 50000 for all employees. Answer 3: Create table employee_new (employee_ID number GENERATED BY DEFAULT AS IDENTITY start with 100 increment by 1, Emp_name varchar(30) NOTNULL, Email varchar(40) NOT NULL UNIQUE check( email LIKE '%@cumail.in'), Phone_number number(10) NOT NULL UNIQUE,
  • 5. Department of Computer Science and EngineeringPage 5 HIRE_date date default sysdate, gender char(1) check( gender IN (‘M’,’F’), JOB_TYPE varchar(30) check( job_type in(‘Academics’, ‘Accounts’, ‘Administration’, ‘Marketing’)), salary number(10,2) check (salary between 20000.00 and 45000.00)); Supplementary Problems: 3) For the table created in question 3 in exercises section: f) Insert any 20 values corresponding to the attributes. g) Assign constraint names to constraints wherever applicable. h) Modify constraints. i) Disable and enable different constraints. j) Drop check constraints. 4) Create a table CLIENTS with following attributes: Client id number, client_name varchar2(30), client_email varchar(40), order_number varchar(30), order_date date, order_quantity number(10), shipping_date date, client_contact number(10) With following constraints i) Client_id should be an identity column generated by default with 100 as starting value and gets incremented by 1. j) Client_name should be not null k) Client_email should be checked for @ and .characters. l) Order number should begin with ‘O’ character followed by unique number. m) Order_date should be system date. n) Order_quantity should be greater than zero. o) Shipping_date should be greater than order_date. p) Client_contact attribute should be not null and unique. a) Create the table with given constraints. CREATE TABLE client12 ( client_id NUMBER GENERATED BY DEFAULT AS IDENTITY start with 100 increment by 1, client_name VARCHAR2(50) constraint con_name NOT NULL, client_email varchar(40) constraint con_email NOT NULL UNIQUE check( client_email LIKE '%@%.%'), order_number varchar(30) constraint con_order NOT NULL UNIQUE check (order_number LIKE 'O%'), order_date date default sysdate, order_quantity number(10) constraint con_quan check (order_quantity>0),
  • 6. Department of Computer Science and EngineeringPage 6 shipping_date date, constraint con_shipping check(shipping_date > order_date), client_contact number(10) constraint con_contact not null unique ); b) Insert records corresponding to attribute values. c) Add a composite unique key constraint on email and phone number. Alter table client12 add constraint com_uni UNIQUE( client_email, client_contact); Question 3: How to check the different constraints applied on a table. To check all constraints applied on a particular table then you need to query the USER_CONSTRAINTS view like this: SELECT * FROM user_constraints WHERE table_name = '<your table name>' AND constraint_name = '<your constraint name>'; Select * from user_constraints where table_ name = ‘EMPLOYEE_GRADE1’ NOTE: The table name has to be specified in CAPITALS. NOTE: In Table 1 given below only few of the columns have been shown. The next Table 2 gives the description of all columns in the user_constraints table. Table 1:
  • 7. Department of Computer Science and EngineeringPage 7 OWNER CONSTRAIN T_NAME CONSTR AINT _TYPE TABLE_ NAME SEAR CH_C ONDI TION SEARCH_CO NDITION_VC R_OWNER SQL_VNWXN PUTDLEHTCC XPROWHQXT T SYS_C00285 04536 C EMPLOY EE_GRA DE1 EID"" IS NOT NULL EID"" IS NOT NULL - SQL_VNWXN PUTDLEHTCC XPROWHQXT T SYS_C00285 04537 C EMPLOY EE_GRA DE1 ENAM E"" IS NOT NULL ENAME"" IS NOT NULL - SQL_VNWXN PUTDLEHTCC XPROWHQXT T SYS_C00285 04538 C EMPLOY EE_GRA DE1 age&g t;=25 age&gt;=25 - SQL_VNWXN PUTDLEHTCC XPROWHQXT T SYS_C00285 04539 C EMPLOY EE_GRA DE1 salary &gt;= 10000 salary&gt;=1 0000 - SQL_VNWXN PUTDLEHTCC XPROWHQXT T SYS_C00285 04540 U EMPLOY EE_GRA DE1 - - - Table 2:
  • 8. Department of Computer Science and EngineeringPage 8 Column Datatype NULL Description OWNER VARCHAR2(128) Owner of the constraint definition CONSTRAINT_NAME VARCHAR2(128) Name of the constraint definition CONSTRAINT_TYPE VARCHAR2(1) Type of the constraint definition: C - Check constraint on a table P - Primary key U - Unique key R - Referential integrity V - With check option, on a view O - With read only, on a view H - Hash expression F - Constraint that involves a REF column
  • 9. Department of Computer Science and EngineeringPage 9 S - Supplemental logging TABLE_NAME VARCHAR2(128) Name associated with the table (or view) with the constraintdefinition SEARCH_CONDITION LONG Text of search condition for a check constraint. This column returns the correct value only when the row originates from the current container. SEARCH_CONDITION_V C VARCHAR2(4000 ) Text of search condition for a check constraint. This column may truncate the search condition. R_OWNER VARCHAR2(128) Owner of the table referred to in a referential constraint R_CONSTRAINT_NAME VARCHAR2(128) Name of the unique constraint definition for the referenced table DELETE_RULE VARCHAR2(9) Delete rule for a referential constraint: CASCADE SET NULL NO ACTION
  • 10. Department of Computer Science and EngineeringPage 10 STATUS VARCHAR2(8) Enforcement status of the constraint: ENABLED DISABLED DEFERRABLE VARCHAR2(14) Indicates whether the constraint is deferrable (DEFERRABLE) or not (NOT DEFERRABLE) DEFERRED VARCHAR2(9) Indicates whether the constraint was initially deferred (DEFERRED) or not (IMMEDIATE) VALIDATED VARCHAR2(13) When STATUS = ENABLED, possible values are: VALIDATED - All data obeys the constraint (thatis,the existingdata in the table was validated when the constraint was enabled, as well as any subsequent data entered into the table)
  • 11. Department of Computer Science and EngineeringPage 11 NOT VALIDATED - All data may not obey the constraint (that is, the existingdatainthe table was not validated when the constraint was enabled,butsubsequent data entered into the table was validated) When STATUS = DISABLED, possible values are: VALIDATED - All data obeys the constraint, but the unique index on the constraint has been dropped. This setting is useful in data warehousing environments, but has some restrictions. Refer to Oracle Database Data Warehousing Guide for more information on this setting. NOT VALIDATED - All data may not obey the constraint
  • 12. Department of Computer Science and EngineeringPage 12 GENERATED VARCHAR2(14) Indicates whether the name of the constraint is user-generated (USER NAME) or system-generated (GENERATED NAME) BAD VARCHAR2(3) Indicates whether this constraint specifies a centuryinan ambiguous manner (BAD) or not (NULL). To avoid errors resulting from this ambiguity, rewrite the constraint using the TO_DATE function with a four-digit year. See Also: the TO_DATE function in Oracle DatabaseSQL Language Reference and Oracle Database Development Guide RELY VARCHAR2(4) When VALIDATED = NOT VALIDATED, this column indicates whether the constraint is to be taken into account for query rewrite (RELY) or not (NULL). When VALIDATED = VALIDATED, this column is not meaningful.
  • 13. Department of Computer Science and EngineeringPage 13 LAST_CHANGE DATE When the constraint was last enabled or disabled INDEX_OWNER VARCHAR2(128) Name of the user owning the index INDEX_NAME VARCHAR2(128) Name of the index (only shown for unique and primary-keyconstraints) INVALID VARCHAR2(7) Indicates whether the constraint is invalid (INVALID) or not (NULL) VIEW_RELATED VARCHAR2(14) Indicates whether the constraint depends on a view (DEPEND ON VIEW) or not (NULL) ORIGIN_CON_ID VARCHAR2(256) The ID of the container where the data originates. Possible values include: 0: This value is used for rows in non-CDBs. This value is not used for CDBs. n: This value is used for rows containing data that originate in the containerwithcontainer ID n (n = 1 if the row originates in root)
  • 14. Department of Computer Science and EngineeringPage 14 EXERCISE QUESTIONS:Primary Key and ForeignKey The following relational schema is given: Emp(eid: integer, ename:string, age:integer, salary:real) Works(eid:integer, did: integer, project_name:string) Dept(did: integer, dname: string, budget: real, managerid: integer) Ques 1: For basedon the given relationalschema. a) Create emp, dept and works table with the possible primary and foreign key constraints. CREATE TABLE Emp( eid INTEGER, ename varCHAR(30), age INTEGER , salary REAL, constraint cons_emp_pk PRIMARY KEY (eid)) CREATE TABLE Dept( did INTEGER, dname varchar2(30), buget REAL, managerid INTEGER , constraint cons_dept_pk PRIMARY KEY (did), constraint cons_dept_fk
  • 15. Department of Computer Science and EngineeringPage 15 FOREIGN KEY (managerid) REFERENCES Emp (eid) on delete cascade) CREATE TABLE Works ( eid INTEGER, did INTEGER, project_name varchar(20), constraint cons_works_fk FOREIGN KEY (did) REFERENCES Dept (did) on delete set null constraint cons_works_fk1 FOREIGN KEY(eid) REFERENCES emp(eid) on delete cascade insert into emp values(101,'John Doe',32,15000); insert into emp values(102,'Toy',32,15000); insert into emp values(103,'Ralph',35,35000); insert into emp values(104,'Joe',37,50000); insert into emp values(105,'William',40,75000); select * from emp; insert into Dept values(11,'CSE',50000,101); insert into dept values (12,'ME',100000,102); insert into dept values (13,'ECE',75000,103); select * from dept insert into works values(101,11,'Research'); insert into works values (102,11,'Academics'); insert into works values (103,12,'Administration');
  • 16. Department of Computer Science and EngineeringPage 16 insert into works values (104,13,'Administration'); insert into works values (105,12,'Research'); select * from works order by eid b) Delete a record from works table with eid = 105 and check whether referential integrity constraint violates or not. delete from works where eid = 105 -- eid entry corresponding to 105 gets deletedfrom works table and no effect on parent table emp as works is the child table c) Delete a record from emp table with eid = 104 and check whether referential integrity constraint violates or not. delete from emp where eid = 104 – eid entry corresponding to 104 gets deleted from both parent and child table as a result of ‘on delete cascade’ d) Delete a record from dept table with did = 12 and check whether referential integrity constraint violates or not. delete from dept where did = 12 – this will remove the corresponding value from dept table and set value to ‘–‘ i.e. null for did column in works table as a result of ‘on delete set null’ EI D DI D PROJECT_NAM E 10 3 - Administration 10 1 11 Research 10 2 11 Academics
  • 17. Department of Computer Science and EngineeringPage 17 e) Changing on delete set null to on delete NO ACTION - NO ACTION cannot be used in the script to define a NO ACTION constraint in Oracle. - By default if on delete clause is not mentioned in foreign key constraint then it represents no action. Firstly drop the existing constraint using -alter table works drop constraint cons_works_fk Secondly, add the constraint without on delete clause which means NO ACTION Referential action - alter table works add constraint cons_works_fk FOREIGN KEY(did) REFERENCES dept(did) Now, execute the following query o delete from dept where did = 11 The following error is generated ORA-02292: integrity constraint (SQL_GVLIADHQLTEEFZAHBPGHKPSVD.CONS_WORKS_FK) violated - child record found ORA-06512: at "SYS.DBMS_SQL", line 1721 NOTE: ON DELETE SET DEFAULT, ON UPDATE CASCADE, ON UPDATE SET NULL, ON UPDATE SET DEFAULT are not supported by ORACLE Question 2: How to define self referential integrity constraint. Solution: Self referential integrity constraint - In this type of referential integrity, foreign key references the primary key of same table.
  • 18. Department of Computer Science and EngineeringPage 18 For example we have employee table with attributes emp_id, emp_name, job_title and manager_id. As manager has to be an employee with some emp_id so Manager_id is self referring the emp_id key in the same table. create table employee( emp_id varchar(20) check(emp_id LIKE'E%'), emp_name varchar(20) not null, job_title varchar(20) not null, manager_id varchar(20) check(manager_id LIKE 'E%'), Constraint cons_pk PRIMARY KEY (emp_id), Constraint cons_fk Foreign key(manager_id) references employee(emp_id)) insert into employee values('E101', 'Akash', 'Manager', 'E101') insert into employee values('E102', 'Ridhima', 'Executive', 'E101') insert into employee values('E103', 'Vansh', 'Manager', 'E103') insert into employee values('E104', 'Rahul', 'Executive', 'E101') insert into employee values('E105', 'Poorva', 'Senior_executive', 'E103') insert into employee values('E106', 'Rohandeep', 'Senior_Executive', 'E103') select * from employee order by emp_id EMP_I D EMP_NA ME JOB_TITLE MANAGER_I D E101 Akash Manager E101 E102 Ridhima Executive E101 E103 Vansh Manager E103 E104 Rahul Executive E101 E105 Poorva Senior_executi ve E103 E106 Rohandeep Senior_Executi ve E103 Now, execute following queries
  • 19. Department of Computer Science and EngineeringPage 19 1. insert into employee values('E107', 'Riva', 'Manager', 'E108') --- it gives integrity constraint violation error as manager_id 108 is not a valid emp_id. 2. delete from employee where emp_id = 'E104' – deletes row successfully 3. delete from employee where emp_id = 'E101' --- it gives referential integrity constraint error 4. To delete an employee who is also the manager, change its manages id to null and then delete the corresponding entry update employee set manager_id = null where manager_id = 'E101' select * from employee EMP_I D EMP_NA ME JOB_TITLE MANAGER_I D E101 Akash Manager - E102 Ridhima Executive - E103 Vansh Manager E103 E104 Rahul Executive - E105 Poorva Senior_executi ve E103 E106 Rohandeep Senior_Executi ve E103 Delete from employee where emp_id = ‘E101’ –deleted successfully 5. Add self referential integrity constraint with ON DELETE CASCADE Drop table employee Create table with on delete cascade referential action create table employee( emp_id varchar(20) check(emp_id LIKE'E%'), emp_name varchar(20) not null, job_title varchar(20) not null,
  • 20. Department of Computer Science and EngineeringPage 20 manager_id varchar(20) check(manager_id LIKE 'E%'), Constraint cons_pk PRIMARY KEY (emp_id), Constraint cons_fk Foreign key(manager_id) references employee(emp_id) on delete cascade) insert into employee values('E101', 'Akash', 'Manager', 'E101') insert into employee values('E102', 'Ridhima', 'Executive', 'E101') insert into employee values('E103', 'Vansh', 'Manager', 'E103') insert into employee values('E104', 'Rahul', 'Executive', 'E101') insert into employee values('E105', 'Poorva', 'Senior_executive', 'E103') insert into employee values('E106', 'Rohandeep', 'Senior_Executive', 'E103') delete from employee where emp_id = 'E101' – executes successfully EMP_I D EMP_NA ME JOB_TITLE MANAGER_I D E103 Vansh Manager E103 E105 Poorva Senior_executi ve E103 E106 Rohandeep Senior_Executi ve E103 Ques 3: The following table has two attributes A and C where A is the primary key and C is the foreign key referencing A with on-delete cascade. A C ----- 2 4 3 4 4 3 5 2 7 2
  • 21. Department of Computer Science and EngineeringPage 21 9 5 6 4 The set of all tuples that must be additionally deleted to preserve referential integrity when the tuple (2,4) is deleted is: Ans: (5,2), (7,2) and (9,5) as on deletion of tuple 2,4 leads to deletion of 5,2 and 7,2 and (5,2) deletion leads to deletion of 9,5. CREATE TABLE test_fk ( A number PRIMARY KEY, C number, FOREIGN KEY(C) REFERENCES test_fk(A) on delete cascade) insert into test_fk values (2,2) insert into test_fk values (3,3) insert into test_fk values (4,3) insert into test_fk values (5,2) insert into test_fk values (7,2) insert into test_fk values (9,5) insert into test_fk values (6,4) update test_fk set c=4 where a = 2; update test_fk set c=4 where a = 3; select * from test_fk order by a delete from test_fk where a = 2 and c = 4 – rows deleted are (2,4), (5,2),(7,2) and (9,5) will be deleted A C 3 4 4 3 6 4
  • 22. Department of Computer Science and EngineeringPage 22 Ques 4: In table T1, P is the primary key, Q is the foreign key referencing R in table T2 with on-delete cascade and on-update cascade. In table T2, R is the primary key and S is the foreign key referencing P in the table T1 with on-delete set NULL and on-update cascade. In order to delete record (3,8) from table T1, (8,3) T2, (5) T1, (2) T1 numbers of additional record that need to be deleted from table T1 is: Ans:Given, ● Q -> R(Primary Key) ● S -> P (Primary Key) Entry to be deleted – P (3) and Q(8) ● Q can be deleted directly ● Now, S – > P but the relationship given is on delete set NULL, Therefore when we delete 3 from T1 ,the entry in T2 having 3 will be NULL. Therfore, Answer is 0 entries. Kindly check entries corresponding to (8,3) T2, (5) T1, (2) T1