DBMS Lab Manual 6116
DBMS Lab Manual 6116
Lab Manual
For
3130703
INDEX
2 Implement Constraints 9
7 Views 32
9 cursors 38
10 Triggers 39
11 Concepts of Normalization
12 Conversion in 3 NF
AIM:
OBJECTIVES
THEORY
● DROP - It will delete the table structure provided the table should be empty.
PROCEDURE
CREATION OF TABLE:
SYNTAX:
ALTER TABLE
Syntax:
EXAMPLE:
Syntax:
EXAMPLE:
Syntax:
Syntax:
Syntax:
RENAMING TABLES
Syntax:
Rename <oldtable> to <new table>;
EXAMPLE:
Rename Employee to Employee 1;
TRUNCATE TABLE
Syntax:
Example:
Truncate table Employee;
DESTROYING TABLES
Syntax:
Example:
. Syntax:
Example:
desc employee;
RESULT:
Exercise:
1. Create the tables described below
PRODUCTNO Varchar2 6
DESCRIPTION Varchar2 15
UNITMEASURE Varchar2 10
QTYONHAND Number 8
REORDERLVL Number 8
CLIENTNO Varchar2 6
NAME Varchar2 20
ADDRESS1 Varchar2 30
ADDRESS2 Varchar2 30
CITY Varchar2 15
PINCODE Number 8
STATE Varchar2 15
SALESMANNO Varchar2 6
SALESMANNAME Varchar2 20
ADDRESS1 Varchar2 30
ADDRESS2 Varchar2 30
CITY Varchar2 15
PINCODE Number 8
STATE Varchar2 15
SNO Number 5
SNAME Varchar2 20
AGE Number 5
SDOB Date
Answers :
Exercise 1 :
(d) Student
(a) Add a column called ‘telephone’ of data type ‘number’ and size =’10’ to the
Client _Master table.
Ans.
OUTPUT:
Ans.
OUTPUT:
Ans.
After OUTPUT:
Ans.
OUTPUT:
Title : “Constraints ”
AIM:
THEORY
Constraints are the business Rules which are enforced on the data being stored
in a table are called Constraints
TYPES OF CONSTRAINTS:
1) Primary key
2) Foreign key/references
3) Check
4) Unique
5) Not null
6) Null
7) Default
PROCEDURE
Syntax:
EXAMPLE
Syntax:
EXAMPLE
Syntax:
EXAMPLE
Syntax:
EXAMPLE
Syntax
EXAMPLE
Syntax
EXAMPLE
EXAMPLE
Exercise:
ADDRESS1 Varchar2 30
ADDRESS2 Varchar2 30
CITY Varchar2 15
PINCODE Number 8
STATE Varchar2 15
ADDRESS2 Varchar2 30
CITY Varchar2 15
PINCODE Number 8
STATE Varchar2 15
Answers :
(a)
OUTPUT:
(b)
OUTPUT:
(c)
OUTPUT:
AIM:
OBJECTIVES
THEORY
DML commands are the most frequently used SQL commands and is used to query and
manipulate the existing database objects. Some of the commands are
1. INSERT
This is used to add one or more rows to a table. The values are separated by
commas and the data types char and date are enclosed in apostrophes. The
values must be entered in the same order as they are defined.
2. SELECT
It is used to retrieve information from the table.it is generally referred to as
querying the table. We can either display all columns in a table or onlyspecify
column from the table.
3. UPDATE
It is used to alter the column values in a table. A single column may beupdated
or more than one column could be updated.
4. DELETE
After inserting row in a table we can also delete them if required. The delete
command consists of a from clause followed by an optional whereclause.
PROCEDURE
INSERT COMMAND
Example:
SQL>INSERT INTO EMPLOYEE VALUES(101,'MANU','LECTURER',15000);
(b) Inserting more than one record using a single insert commands:
Syntax:
Example:
SELECT COMMAND
Syntax:
Select * from
tablename;
Example:
Syntax:
Example:
Syntax:
SELECt <column1>, <column2> FROM <tablename> WHERE <condition> ;
Example:
Syntax:
<tablename>Example:
UPDATE COMMAND
Syntax:
Example:
DELETE COMMAND
RESULT
Problems
Answers:
1.
INSERT INTO client_master
VALUES ('C00001','Ivan','Mumbai',400054,'Maharashtra',1500),
('C00002','Ashwini','Chennai',780001,'TamilNadu',0),
('C00003','Joshi','Mangalore',560001,'Karnataka',5000),
('C00004','Deepak','Chennai',780001,'TamilNadu',0),
('C00005','Sharma','Mumbai',400054,'Maharashtra',2000);
OUTPUT:
2.
OUTPUT:
3.
INSERT INTO salesman_master
VALUES ('S00001', 'Aman', 'A/4', 'Worli', 'Mumbai', 400002, 'Maharaashtra'),
('S00002', 'Omkar', '65', 'Nariman', 'Mumbai', 400001, 'Maharaashtra'),
('S00003', 'Raj', 'p-7', 'Bandra', 'Mumbai', 400032, 'Maharaashtra'),
('S00004', 'Ashish', 'A/5', 'Juhu', 'Mumbai', 400044, 'Maharaashtra');
OUTPUT:
OUTPUT:
OUTPUT:
c. Retrieve the list of names,city and the state of all the clients
Ans.
OUTPUT:
d. List the various products available from the Product _Master table
Ans.
OUTPUT:
OUTPUT:
OUTPUT:
OUTPUT:
Ans.
OUTPUT:
Ans.
OUTPUT:
OUTPUT:
Ans.
OUTPUT:
c. Delete from the Client_master where the column state holds thevalue
‘Tamilnadu’.
Ans.
OUTPUT:
AIM:
OBJECTIVES
THEORY:
Data Control Language (DCL) consists of various commands which are relatedto data
sharing and security of data in database.
They are
GRANT
REVOKE
Granting Privileges:
Objects that are created by a user are owned and controlled by that user. If userwishes
to access any of the objects belonging to another user, the owner of the object will have
to give permissions for such access. This is called Granting of Privileges.
Granting privileges using the GRANT statements:
The GRANT statements provide various types of access to database objectssuch as
tables, views.
Syntax:
GRANT {object privileges}
ON object name
TO username;
Object Privileges:
Each object privilege that is granted authorizes the grantee to perform someoperation
on the object. The user can grant all the privileges or grant only specific object
privileges.
The list of object privileges is as follows:
• ALTER: allows the grantee to change the table definitions with the ALTERtable
command.
• DELETE: allows the grantee to remove the records from the table with the
DELETE command.
• INDEX: allows the grantee to create an index on the table with the CREATE
INDEX command.
• INSERT: allows the grantee to add records to the table with the INSERT
command.
• SELECT: allows the grantee to query the table with SELECT command.
• UPDATE: allows the grantee to modify the records in the table with the
UPDATE command.
Revoking privileges given:
Privileges once given can be denied to a user using the REVOKE command. The
object owner can revoke privileges granted to another user. A user of an object who
is not owner, but has been granted the GRANT privilege, has the power to
REVOKE the privileges from the grantee.
Revoking permission using the REVOKE statement:
The REVOKE statement is used to deny the grant given on an object.
Syntax:
REVOKE {object privileges}ON
object name
FROM username;
The REVOKE command is used to revoke object privileges that the userpreviously
granted to the Revoke.
AIM
To implement computations done on data of the given table
OBJECTIVES
To understand computations done on data of the given table with built infunctions
THEORY
Group Functions/Aggregate functions
A group function returns a result based on group of rows.
1. avg
Example: select avg (total) from student;
2. max
Example: select max (percentagel) from student;
2.min
Example: select min (marksl) from student;
4. sum
Example: select sum(price) from product
Count Function
In order to count the number of rows, count function is used.
1. count(*) – It counts all, inclusive of duplicates and nulls.
Example: select count(*) from student;
2. count(col_name)– It avoids null value.
Example: select count(total) from order;
2. count(distinct col_name) – It avoids the repeated and null values.
Example: select count(distinct ordid) from order;
Special Clauses:
Group by clause
This allows us to use simultaneous column name and group functions.
Example: Select max (percentage), deptname from student group bydeptname;
Having clause
This is used to specify conditions on rows retrieved by using group byclause.
Example: Select max(percentage), deptname from student group bydeptname having
count(*)>=50;
In / not in – used to select a equi from a specific set of values
Any - used to compare with a specific set of values Between / not
between – used to find between the rangesLike / not like – used to do
the pattern matching
PROCEDURE
OUTPUT
RESULT
PROGRAMS
• list the names of all clients having ‘a’ as the second letter in theirnames.
Ans.
Ans.
Ans.
Ans.
Ans.
CLIECTNO = 'C00003';
• list products whose selling price is greater than 500 and less than orequal to 750
Ans.
• Listing of names,city and state of clients who are not in the state of
‘maharashtra’.
Ans.
Ans.
Ans.
Ans.
• count the number of products having the price greater than or equalto 500
Ans.
a. printing the description and total quantity sold for each product.
Ans.
c. find out the total of all the billed orders for the month of june.
Ans.
AIM:
OBJECTIVES
THEORY
a) NESTED QUERIES:
A sub query is a query within a query. In Oracle, we can create sub queries
within your SQL statements. These sub queries can reside in the WHERE
clause, the FROM clause, or the SELECT clause.
b) JOINS:
Natural join:
It returns the matching rows from the table that are being joined
.
Syntax:
>select <attribute> from TN where TN1.attribute=TN2.attribute.
Inner join:
It returns the matching rows from the table that are being joined.
Syntax:
>select <attribute> from TN1 innerjoin TN2 on TN1.attribute=TN2.attribute.
Left outer join:
It returns all the rows from the table1 even when they are unmatched.
Syntax:
5. select <attribute> from TN1 left outer join TN2 on
TN1.attribute=TN2.attribute.
2. select <attribute> from TN where TN1.attribute(+)=TN2.attribute.
Syntax:
4. select <attribute> from TN1 right outer join TN2 on
TN1.attribute=TN2.attribute.
2. select <attribute> from TN where TN1.attribute=(+)TN2.attribute.
Full join:
PROCEDURE
NESTED QUERIES -
PNO NUMBER(3)
ENO NUMBER(3)
PJOB CHAR (12)
1 DBMS 2
2 COMPILER 3
3 C1 1
1 1 Programmer
2 1 Analyst
1 2 Analyst
2 2 Programmer
NESTED QUERIES
(i) SQL> select ename from emp_det where dno not in(select dno from
emp_det where ename ='SaravanaKumar');
ENAME
RajKumar
Shirley
(ii)SQL> select ename, dno from emp_det where dno = (select dno from
emp_det where ename ='RajKumar');
ENAME DNO
RajKumar 2
(iii)SQL> select ename from emp_det where eno in(select eno from work_in
where pno = (select pno from pro_det where pname = 'DBMS')) order by
ename;
ENAME
Mahendran
SaravanaKumar
(iv)SQL> select ename, basic_sal from emp_det where dno = 2 and
basic_sal>(select max(basic_sal) from emp_det where dno = 10) order by
ename;
ENAME BASIC_SAL
RajKumar 10000
(v)SQL> select pno,pname from pro_det where exists(select pno from work_in
where work_in.pno =pro_det.pno);
PNO PNAME
1 DBMS
2 COMPILER
MAX(BASIC_SAL)
8000
(ix)SQL> select * from emp_det where basic_sal < (select avg(basic_sal) from
emp_det);
JOINS
SQL> create table emp(name varchar2(20),salary number(10));
Table created.
SQL> select * from emp;
NAME SALARY
ashu 10000
asma 1200
asif 2000
arif 1000
niyas 3000
SQL> create table emp1(name varchar2(20),empid number(10));
Table created.
.
SQL> select * from emp1;
NAME EMPID
fathi 12
sumi 32
priya 11
wahab 10
sweety 9
asma 1200
6 rows selected.
NATURAL JOIN
asma 1200
asma 1200
asif 2000
arif 1000
niyas 3000
ashu 10000
asma 1200
sweety 9
sumi 32
wahab 10
fathi 12
priya 11,
6 rows selected.
FULL JOIN
SQL>select emp1.name,emp.name,emp1.empid,salary from emp full join emp1
on
emp.name=emp1.name
NAME NAME EMPID SALARY
RESULT:
Thus the nested queries and join operations are executed and verifiedin DBMS.
Exercise :
1. Exercises on sub-queries
b) Find the name and complete address for the customer who has placed order
number ‘o19001’.
Query:
c) find the clients who have placed orders before the month of may ‘02
Query:
d) find the names of clients who have placed orders worth Rs.10000 or more.
Query:
Title : “VIEWS”
AIM:
OBJECTIVES
To implement views
THEORY
A view is the tailored presentation of data contained in one or more table and
can also be said as restricted view to the data‟s in the tables. A view is a “virtual
table” or a “stored query” which takes the output of a query and treats it as a
table. The table upon which a view is created is called as base table . A view is a
logical table based on a table or another view. A view contains no data of its
own but is like a window through which data from tables can be viewed or
changed. The tables on which a view is based are called base tables. The view is
stored as a SELECT statement in the data dictionary .
Advantages of a view:
a. Additional level of table security.
b. Hides data complexity.
c. Simplifies the usage by combining multiple tables into a single table
Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
Example
Create or replace view empview as select * from emp;
PROCEDURE
1) create a table aa
Bb 23 2001 12 23435
Cc 55 342 76 687478
dd 2 1233 123 53616578
ee 21 1111 111 12435798
3) create table qq
SQL> create table qq(name varchar2(20),book number(10),author
varchar(20),publisher varchar2(20),ISBN number(20));
4) describe table qq
bb 21 23 dfd 573568
cc 43 55 fg 65839
ee 44 21 dfd 1235798
oo 87 34 gfh 6358379
5) create a view on qq
View created.
21 bb qwa
cc 65839 fg
ee 1235798 dfd
oo 6358379 gfh
SQL> create view ss as select name,book from aa union select name,book from
qq;
View created.
SQL> select * from ss;
NAME BOOK
bb 21
bb 23
cc 43
cc 55
dd 2
ee 21
ee 44
oo 87
8 rows selected.
Result
Thus the view creation commands are executed successfully.
EXERCISE:
Table:Hosp_doc
Doc_code Varchar2(4)
Doc_name Varchar2(4)
Specialization Varchar2(4)
Department Varchar2(4)
Date_of_join Date
Exper Number(2)
2) create another view that contains doctor codes and doctor names of
‘orthologue’ department.
Query:
Query :
drop view vw_doctor;
AIM:
OBJECTIVES
FUNCTION:
Syntax:
Create or replace function<function_name>[argument]
Return datatype is
(local declaration)
begin
(executable statements)
[Exception]
(exception handlers)
End
PROCEDURE:
create [or replace] procedure procedurename
[parameter[in/out/in/in out] datatype [:=/default
expression]
[(parameter)]
is/as declaration
begin
pl/sql codes
[exception]
end
PROGRAM
OUTPUT
SQL> /
Enter value for a: 4
old 2: dbms_output.put_line('the factorial='||fact(&a)) new
2: dbms_output.put_line('the factorial='||fact(4)); the
factorial=24
PL/SQL procedure successfully completed.
RESULT:
Thus the functions and stored procedures are executed in SQL.
Problems;
1) procedure to find whether a given number is odd or even.
Ans :
n NUMBER := 1634;
r NUMBER;
BEGIN
-- Calculating modulo
r := MOD(n, 2);
IF r = 0 THEN
dbms_output.Put_line('Even');
ELSE
dbms_output.Put_line('Odd');
END IF;
END;
--End program
2) procedure to display 1-10 using while.
Ans :
DECLARE
DECLARE @counter int,
n int
SET @counter=1
WHILE(@counter<=n)
BEGIN PRINT ‘The values are :’+CONVERT(VARCHAR,@counter)
SET @counter=@counter+1
END
Title : “CURSORS”
AIM
To retrieve all students who have registered for Diploma and store their detailsinto
another table called diploma (id,name) using cursors.
OBJECTIVES
To implement cursor
PROCEDURE
1) TABLE CREATION
SQL>create table student(id number,name varchar2(25),programmevarchar2(25));
students;
Id name programme
1 rohan diploma
2 anu MA
3 robert diploma
4 tom btech
5 sunny diploma
SQL>declare
2 cursor stud is select * from students where programme =”diploma’;
3 id students.id%type;
4 name students.name%type
5 prog students.programme%type
6 begin
7 open stud;
8 loop
9 fetch stud into id,name,prog;
10 exit when stud%notfound;
11 insert into diploma values(id,name);
12 endloop;
13 end;
14 /
OUTPUT
RESULT
PROGRAMS
1.A HRD manager has decided to raise the salary of all employees in
department number 20 by 0.05.Whenever such raise is given to the
employees,the employee number ,the date when raise was given and raise
amunt are maintained in the emp_raise table.Write a PL/SQL block using
cursors to update the salary of each employee of dept no 20 and insert a record
in the emp_raise table as well.
Solution :
1. Table creation:
create table employee(
emp_name varchar(20),
emp_number int(5),
dep_name varchar(10),
dep_number int(5),
salary decimal(10,2)
);
2. Data insertion
3. Cursor creation :
BEGIN
DECLARE dep_number;
declare salary;
declare raise_date;
declare salary_raise
CURSOR FOR SELECT dep_number,salary,raise_date from employee;
OPEN salary_raise;
FETCH FROM salary_raise INTO salary,raise_date;
if dep_number==20 THEN
UPDATE TABLE employee
SET salary=salary+(salary*0.05);
SET raise_date=CURRENT_DATE;
END IF;
CLOSE salary_raise;
END
Output :
Title : “TRIGGER”
AIM
Create a Trigger for EMP table it will update another table SALARY while inserting
values
OBJECTIVES
To develop and execute a Trigger for Before and After update/Delete/Insert
operations on a table
THEORY.
PROCEDURE
step 1: start
step 2: initialize the trigger with specific table id.
step 3:specify the operations (update, delete, insert) for which the trigger has tobe
executed.
step 4: execute the trigger procedure for both before and after sequences step
5: carryout the operation on the table to check for trigger execution. step 6:
stop
PROGRAM
sql> create table emp(iname varchar2(10),iid number(5),salary number(10));table
created.
table created.
each row
declare
a varchar2(10);
begin
a:=:new.iname;
update sal set
totalsal=totalsal+:new.salary,totalemp=totalemp+1 whereiname=a;
end;
/
trigger created.
vec 1 1000
srm 0 0
Vec 1 1000
srm 1 3000
sql> insert into emp values('vec',100,5000);
1 row created.
vec 2 6000
srm 1 3000
sql> insert into emp values('vec',100,2000);
1 row created.
vec 3 8000
srm 1 3000
sql> insert into emp values('srm',200,8000);
1 row created.
Vec 3 8000
Srm 2 11000
RESULT:
The trigger procedure has been executed successfully for both before and after
sequences.
Problems
1. Write a trigger that stores the details of students changing their program from
CT to CHM.
1) Creating table
Query:
Create table student(name varchar(20),enroll varchar(20),branch varchar(20),program
varchar(20));
2) Inserted data:
3) Creation of trigger:
Query:
CREATE TRIGGER `stored_program` AFTER UPDATE ON `student`
FOR EACH ROW INSERT into student_stored
values(name,enroll,branch,program)
Output of Table :
1) Creation of table
Query:
Create table AUDIT_TRAIL(client_no varchar(6),name varchar(20),baldue
decimal(8,2),Operation varchar(8),userid varchar(20),olddate date);
2) Creation of trigger
Query:
Create trigger `store_data` before update on `client_master`
For each row
Begin
insert into AUDIT_TRAIL
Set action=’update’
Client_no=old.client_no
Name=old.name
Baldue=old.baldue
Olddate=currentdate()
End
AUDIT_TRAIL table:
Problem Statement:
An exercise to check whether the given database table is normalized or not. If
yes find out the status of normalization and reasoning.
Objective:
To study the concept of various levels of normalization and understand how to
convert into normalized forms.
We can easily verify that this table satisfies the definition of 1NF: viz., it has no
duplicated rows; each cell is single-valued (i.e., there are no repeating groups or
arrays); and all the entries in a given column are of the same kind. In this table
we can see that the key, SSN, functionally determines the other attributes;
i.e.,FirstName, LastName, and Major. .
AIM
An excercise to check whether the given database table is normalized or not. If
yes find out the status of normalization and reasoning.
Objective:
Design/Theory
Create a database table in SQL with a few no of rows and
columns.Analyze the table and determine to which normal form it beongs to
according to the rules and regulations of each normal forms.
Procedure:
Consider a book database table as given below.
By examining the table, we can infer that books dealing with history,
cognitive psychology, and folksong are assigned to the PCL General Stacks
collection; that books dealing with legal procedures are assigned to the Law
Library; that books dealing with Greek literature are assigned to the Classics
Library; that books dealing with library biography are assigned to the Library
and Information Science Collection (LISC);and that books dealing with music
literature are assigned to the Fine Arts Library.
Moreover, we can infer that the PCL General Stacks collection and the
LISC are both housed in the Perry-Castañeda Library (PCL) building; that the
Classics Library is housed in Waggener Hall; and that the Law Library and Fine
Arts Library are housed, respectively, in Townes Hall and the Fine Arts
Building.
Thus we can see that a transitive dependency exists in the above table :
any book that deals with history, cognitive psychology, or library biography
will be physically housed in the PCL building (unless it is temporarily checked
out to a borrower); any book dealing with legal procedures will be housed in
Townes Hall; and so on. In short, if we know what subject a book deals with,
we also know not only what library or collection it will be assigned to but also
what building it is physically housed in.
To solve this problem decompose the above table into three different tables as
follows
Table A
Table B
Table C
Subject Collection or Library
Table D
Collection or Library Building
1. What is a database?
2. What is DBMS?
3. Give an example for an RDBMS.
4. List the benefits of DBMS.
5. Disadvantage in File Processing System
6. What is a key? what are different keys in database?
7. What is a primary key?
8. What is a secondary key?
9. What is a candidate key?
10. What is an alternate key?
11. What is a super key?
12. What is a composite key?
13. What is a relation?
14. What is a table?
15. What is an attribute?
16. What is a domain?
17. What is a tuple?
18. What is a selection?
19. what is a join operation?
20. What are base operations in relational algebra?
21. What are different DBMS facilities? How many types of facilities are provided by a
DBMS?
22. What is Data Definition Language?
23. What is Data Dictionary?
24. What is a DML?
25. What is a query?
26. What is a query language?
27. What are the advantages of DBMS?
28. What is a SQL?
29. What are the features of SQL?
30. How SQL organizes the data?
31. What is data definition?
32. What is data retrieval?
33. What is data sharing?
34. What is a view?
35. What is normalization?
36. What is a first normal form?
37. What is a second normal form?
38. What is a third normal form?
39. What is BCNF?
40. What is fifth normal form?
41. What is Functional Dependency?
42. What is Lossless join property?
43. What are the commands to delete, modify and insert a record in the table?
44. What is time stamping?
45. What is data base schema?
46. What is a self join?