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

DBMS

DBMS FILE

Uploaded by

as4848284
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

DBMS

DBMS FILE

Uploaded by

as4848284
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

Theory and Concept

Objective:- To implement various DML Operations on table.

DML ( Data Manipulation Language) Data manipulation is

● The retrieval of information stored in the database.


● The insertion of new information into the database.
● The deletion of information from the database.
● The modification of information stored by the appropriate data model. There are basically two
types.

(i) Procedural DML:- require a user to specify what data are needed and how to get those
data.
(ii) Non Procedural DML : require a user to specify what data are needed without
specifying how to get those data.

Updating the content of a table:


In creation situation we may wish to change a value in table without changing all values in the tuple .
For this purpose the update statement can be used.

Update table name

Set columnname = experision, columnname =expression……


Where columnname = expression;

Deletion Operation:-
A delete reQuestionst is expressed in much the same way as Questionry. We can delete whole tuple (
rows) we can delete values on only particulars attributes.

Deletion of all rows

Syntax:
Delete from tablename :

Deletion of specified number of rows


Syntax:

Delete from table name


Where search condition ;

Computation in expression lists used to select data

+ Addition - Subtraction
* multiplication ** exponentiation
/ Division () Enclosed operation
Renaming columns used with Expression Lists: - The default output column names can be renamed
by the user if required

Syntax:

Select column name


result_columnname, Columnname
result_columnname,
From table name;

Logical Operators:
The logical operators that can be used in SQL sentenced

are AND all of must be included

OR any of may be included


NOT none of could be included

Range Searching: Between operation is used for range searching.

Pattern Searching:

The most commonly used operation on string is pattern matching using the operation ‘like’ we
describe patterns by using two special characters.

● Percent (%) ; the % character matches any substring we consider the following examples.
● ‘Perry %’ matches any string beginning with perry
● ‘% idge % matches any string containing’ idge as substring.
● ‘ - - - ‘ matches any string exactly three characters.
● ‘ - - - % matches any string of at least of three characters.

Oracle functions:

Functions are used to manipulate data items and return result. function follow the format of function
_name (argument1, argument2 ..) .An arrangement is user defined variable or constant. The structure
of function is such that it accepts zero or more arguments.
Examples:
Avg return average value of n

Syntax:

Avg ([distinct/all]n)
Min return minimum value of expr.

Syntax:

MIN((distict/all )expr)
Count Returns the no of rows where expr is not null
Syntax:
Count ([distinct/all)expr]
Count (*) Returns the no rows in the table, including duplicates and those with nulls.
Max Return max value of expr

Syntax:

Max ([distinct/all]expr)
Sum Returns sum of values of n

Syntax:
Sum ([distinct/all]n)

Sorting of data in table


Syntax:
Select columnname, columnname
From table
Order by columnname;
Experiment No. # 3

Question.1 Using the table client master and product master answer the following
Queries.

i. Change the selling price of ‘1.44 floppy drive to Rs.1150.00


ii. Delete the record with client 0001 from the client master table.
iii. Change the city of client_no’0005’ to Bombay.
iv. Change the bal_due of client_no ‘0001, to 1000.
v. Find the products whose selling price is more than 1500 and also find the
new selling price as original selling price *15.
vi. Find out the clients who stay in a city whose second letter is a.
vii. Find out the name of all clients having ‘a’ as the second letter in their names.
viii. List the products in sorted order of their description.
ix. Count the total number of orders
x. Calculate the average price of all the products.
xi. Calculate the minimum price of products.
xii. Determine the maximum and minimum prices . Rename the tittle as
‘max_price’ and min_price respectively.
xiii. Count the number of products having price greater than or equal to 1500.
Theory and Concept

Objective:- To Alter the structure of the table

Modifying the Structure of Tables-

Alter table command is used to changing the structure of a table. Using the alter table clause you
cannot perform the following tasks:

(i) change the name of table


(ii) change the name of column
(iii) drop a column
(iv) decrease the size of a table if table data exists.

The following tasks you can perform through alter table command.

(i) Adding new columns:

Syntax
ALTER TABLE tablename
ADD (newcolumnname newdatatype (size));

(ii) Modifying existing table

Syntax:
ALTER TABLE tablename
MODIFY (newcolumnname newdatatype (size));

NOTE: Oracle not allow constraints defined using the alter table, if the data in the table, violates such
constraints.

Removing/Deleting Tables- Following command is used for removing or deleting a table.

Syntax:
DROP TABLE tabename:

Defining Integrity constraints in the ALTER TABLE command-

You can also define integrity constraints using the constraint clause in the ALTER TABLE
command. The following examples show the definitions of several integrity constraints.

(1) Add PRIMARY KEY-

Syntax:
ALTER TABLE tablename
ADD PRIMARY KEY(columnname);
Department of Computer Science & Engineering

(2) Add FOREIGN KEY-

Syntax:
ALTER TABLE tablename
ADD CONSTRAINT constraintname
FOREIGN KEY(columnname) REFERENCES tablename;

Droping integrity constraints in the ALTER TABLE command:

You can drop an integrity constraint if the rule that if enforces is no longer true or if the constraint is
no longer needed. Drop the constraint using the ALTER TABLE command with the DROP clause.
The following examples illustrate the droping of integrity constraints.

(1) DROP the PRIMARY KEY-

Syntax:
ALTER TABLE tablename
DROP PRIMARY KEY

(2) DROP FOREIGN KEY-

Syntax:
ALTER TABLE tablename
DROP CONSTRAINT constraintname;
Department of Computer Science & Engineering

Experiment No.5
Question 1. Create the following tables:

Challan_Header
Column name data type size Attributes
Challan_no varchar2 6 Primary key
s_order_no varchar2 6 Foreign key references s_order_no of
sales_order table
challan_date date not null
billed_yn char 1 values (‘Y’,’N’). Default ‘N’

Table Name : Challan_Details


Column name data type size Attributes
Challan_no varchar2 6 Primary key/Foreign key references
Product_no of product_master
Qty_disp number 4,2 not null

Q2. Insert the following values into the challan header and challan_details tables:

(i) Challan No S_order No Challan Date Billed

CH9001 019001 12-DEC-95 Y


CH865 046865 12-NOV-95 Y
CH3965 010008 12-OCT-95 Y

Data for challan_details table

Challan No Product No Qty Disp


CH9001 P00001 4
CH9001 P07965 1
CH9001 P07885 1
CH6865 P07868 3
CH6865 P03453 4
CH6865 P00001 10
CH3965 P00001 5
CH3965 P07975 2

Objective – Answer the following Queries

Q1. Make the primary key to client_no in client_master.


Q2. Add a new column phone_no in the client_master table.
Q3. Add the not null constraint in the product_master table with the columns
description, profit percent , sell price and cost price.
Q4. Change the size of client_no field in the client_master table.
Q5. Select product_no, description where profit percent is between 20 and 30 both inclusive.
Experiment No.3

Ques on.1 Using the table client master and product master answer the following
Queries.

I. Change the selling price of ‘1.44 floppy drive to Rs.1150.00.

II. Delete the record with client 0001 from the client master table.

III. Change the city of client_no’0005’ to Bombay.


IV. Change the bal_due of client_no ‘0001, to 1000.

V. Find the products whose selling price is more than 1500 and also find the
new selling price as original selling price *15.

VI. Find out the clients who stay in a city whose second le er is a.
VII. Find out the name of all clients having ‘a’ as the second le er in their names.

VIII. List the products in sorted order of their descrip on.

IX. Count the total number of orders.


X. Calculate the average price of all the products.

XI. Calculate the minimum price of products.

XII. Determine the maximum and minimum prices . Rename the le


as ‘max_price’ and min_price respec vely.

XIII. Count the number of products having price greater than or equal to 1500.
Theory and Concept

Objective:-To Implement the restrictions/constraints on the table.

Data constraints: Besides the cell name, cell lengthand cell data type there are other parameters i.e.
other data constrains that canbe passed to the DBAat check creationtime. The constraints caneither be
placed at column level or at the table level.

i. Column Level Constraints: If the constraints are defined along with the column definition, it
is called a column level constraint.
ii. Table Level Constraints: If the data constraint attached to a specify cell in a table reference
the contents of another cell in the table then the user will have to use table levelconstraints.

NullValue Concepts:-while creating tables ifa rowlocksa datavalue for particular column that
value is said to be null . Column of any data types may contain null values unless the column
was defined as not null when the table was created

Syntax:

Create table tablename


(column name datatype(size)not null……)

Primary Key: primary key is one or more columns is a table used to uniquickly identity each
row in the table. Primary key values must not be null and must be uni Question across the
column. A multicolumn primary key is called composite primary key.

Syntax:primarykeyasacolumn constraint

Createtabletablename
(columnnamedatatype(size)primarykey,….)

Primarykeyasatable constraint

Createtabletablename
(columnnamedatatype(size),columnnamedatatype(size)…
Primary key (columnname,columnname));

UniQuestion key concept:-A uniQuestion is similar to a primarykey except that the purpose
of a uniQuestion key is to ensure that information in the column for each record isuniQuestion
as with telephone or devices license numbers. A table may have many uniQuestion keys.

Syntax: UniQuestionasacolumnconstraint.

Createtabletablename
(columnnamedatatype(size)uniQuestion);
 RajKumarGoelInstituteofTechnology,Ghaziabad
Department ofComputerScience&Engineering

UniQuestionastable constraint:
Createtabletablename
(columnname datatype (size),columnname datatype (size)…uniQuestion
(columnname,columnname));

Default valueconcept: At the lineofcellcreationadefault valuecanbeassignedto it. When the


user is loading a recordwith values and leaves this cellempty, the DBAwilautomatically load
this cell withthe default value specified. The datatype ofthe default value should match the
data type of the column

Syntax:

Createtabletablename
(columnnamedatatype(size)default value,….);

Foreign Key Concept :Foreign key represents relationship between tables. A foreign key is
column whose values are derived from the primary key of the same of some other table . the
existence of foreign key implies that the table with foreign key is related to the primary key
table from which the foreign key is derived .A foreign key must have corresponding primary
key value in the primary key table to have meaning.
Foreignkeyas a columnconstraint

Syntax:

Createtabletablename
(columnnamedatatype(size)referencesanothertablename);

Foreignkeyasatableconstraint:

Syntax:
Create table
name(columnnamedatatype(siz
e)…. primary key
(columnname);
foreignkey(columnname)referencestablename);

Check Integrity Constraints: Use the check constraints when you need to enforce intergrity
rules that can be evaluated based on a logical expression following are a few examples of
appropriate check constraints.
 A check constraints name column of the coient_master so that the name is entered in
upper case.
 A check constraint on the client_no column of the client _master so that no client_no
value starts with ‘c’

Syntax:

Createtabletablename
(columnnamedatatype(size)CONSTRAINTconstraintname)
Check (expression));
 RajKumarGoelInstituteofTechnology,Ghaziabad
Department ofComputerScience&Engineering

Experiment 4
Question.2Createthefollowing tables:

i. Sales_master

Columnname Datatype Size Attributes


Salesman_no varchar2 6 Primarykey/firstletter
muststartwith‘s’
Sal_name varchar2 20 Notnull
Address varchar2 Notnull
City varchar2 20
State varchar2 20
Pincode Number 6
Sal_amt Number 8,2 Notnull, cannotbe0
Tgt_to_get Number 6,2 Notnull, cannotbe0
Ytd_sales Number 6,2 Notnull, cannotbe0
Remarks Varchar2 30

ii. Sales_order

Columnname Datatype Size Attributes


S_order_no varchar2 6 Primary/firstlettermustbe0
S_order_date Date 6 Primarykeyreferenceclientnoof
client_master table
Client_no Varchar2 25
Dely_add Varchar2 6
Salesman_no Varchar2 6 Foreign key references
salesman_noofsalesman_masterta
ble
Dely_type Char 1 Deliverypart(p)/full(f),defaultf
Billed_yn Char 1
RajKumarGoelInstituteofTechnology,Ghaziabad
____________________________________________________
Department of Computer Science &Engineering

Order_status Varchar1 ComputerScience Engineering process’;’fulfilled’;backorder’;’can celed


department

I. Sales_order_details

Column Datatype Size Attributes

S_order_no Varchar2 6 Primarykey/foreignkey


referencess_order_no
of sales_order
Product_no Varchar2 6 Primarykey/foreignkey
references product_no
ofproduct_master
Qty_order Number 8
Qty_disp Number 8
Product_rate Number 10,2
 RajKumarGoelInstituteofTechnology,Ghaziabad
Department ofComputerScience&Engineering

Insertthe followingdataintotheirrespectivetablesusing insertstatement:

Dataforsales_manmastertable

Salesman_no Salesman Address City Pin code State Salamt Tgt_ Ytd Remark
name to_ge Sales
t
500001 Kiran A/14worli Bomba 400002 Mah 3000 100 50 Good
y
500002 Manish 65,nariman Bomba 400001 Mah 3000 200 100 Good
y
500003 Ravi P-7Bandra Bomba 400032 Mah 3000 200 100 Good
y
500004 Ashish A/5 Juhu Bomba 400044 Mah 3500 200 150 Good
y

(i) Dataforsalesordertable:

S_orderno S_orderdate Clientno Dely Bill yn Salesmanno Delay Orderstatus


type date
019001 12-jan-96 0001 F N 50001 20-jan-96 Ip
019002 25-jan-96 0002 P N 50002 27-jan-96 C
016865 18-feb-96 0003 F Y 500003 20-feb-96 F
019003 03-apr-96 0001 F Y 500001 07-apr-96 F
046866 20-may-96 0004 P N 500002 22-may- C
96
010008 24-may-96 0005 F N 500004 26-may- Ip
96
 RajKumarGoelInstituteofTechnology,Ghaziabad
Department ofComputerScience&Engineering

(iii) Dataforsales_order_detailstable:

S_orderno Productno Qtyordered Qtydisp Product_rate


019001 P00001 4 4 525
019001 P07965 2 1 8400
019001 P07885 2 1 5250
019002 P00001 10 0 525
046865 P07868 3 3 3150
046865 P07885 10 10 5250
019003 P00001 4 4 1050
019003 P03453 2 2 1050
046866 P06734 1 1 12000
046866 P07965 1 0 8400
010008 P07975 1 0 1050
010008 P00001 10 5 525
Experiment No.5

Ques on 1. Create the following tables:


1. Challan Header
Column name datatype Size A ributes
Challan_no Varchar2 6 Primary key
S_order_no Varchar2 6 Foreign key references
s_order_no of
sales_order table
Challan_date Date Not null
Billed_yn Char 1 Values(‘Y’,’N’).Default’N’

2. Challan_Details
Column name Datatype Size A ributes
Challan_no Varchar2 6 Primary key/foreign
key references
Product_no of
product_master
Qty_disp Number 4,2 Not null
Q2. Insert the following values into the challan header and challan_details tables:
Q1. Make the primary key to client_no in client_master.

Q2. Add a new column phone_no in the client_master table.

Q3. Add the not null constraint in the product_master table with the columns
descrip on, profit percent , sell price and cost price.

Q4. Change the size of client_no field in the client_master table.

Q5. Select product_no, descrip on where profit percent is between 20 and 30 both inclusive.
Department ofComputerScience&Engineering

Theory&Concept
Objective:-ToimplementtheconceptofJoins
Joint Multiple Table (Equi Join):Some times we require to treat more than one table as though
manipulate data fromallthe tables as thoughthetables were not separateobject butone single entity. To
achieve this we have to join tables.Tables are joinedon column thathave dame data typeand data with
in tables.

ThetablesthathavetobejoinedarespecifiedintheFROMclauseandthejoining attributes in
the WHERE clause.

AlgorithmforJOINinSQL:
1. Cartesianproductoftables(specifiedinthe FROMclause)
2. Selectionofrowsthatmatch(predicateintheWHEREclause)
3. Projectcolumnspecified intheSELECTclause.

1. Cartesianproduct:-
Considertwotablestudentandcourse
Select B.*,P.*
FROMstudentB,courseP;

2. INNERJOIN:
Cartesianproductfollowedbyselection
Select B.*,P.*
FROM student B, Course P
WHEREB.course#P.course#;

3. LEFTOUTERJOIN:
LEFTOUTERJOIN=Cartesianproduct+selectionbut includerowsfromthe lefttable which are
unmatched pat nulls in the values of attributes belonging to th e second table
Exam:
SelectB.*,P*
FROMstudentBleft joincoursep
ON B.course # P.course #;

4. RIGHTOUTER JOIN:
RIGHTOUTERJOIN=Cartesianproduct+selectionbut includerowsfromrighttable which are
unmatched

Exam:
SelectB.*,P.*FromstudentBRIGHTJOINcourseP
B.course# = P course # ;

5. FULLOUTER JOIN
Exam
Select B.*,P.*
Fromstudent BFULLJOINcourseP On
B.course # = P course # ;
 RajKumarGoelInstituteofTechnology,Ghaziabad
Department ofComputerScience&Engineering

EXPERIMENTNO.6

A.ConsiderthefollowingschemaforaLibraryDatabase: BOOK

(Book_id, Title, Publisher_Name, Pub_Year) BOOK_AUTHORS

(Book_id, Author_Name)

PUBLISHER (Name, Address, Phone)

BOOK_COPIES(Book_id,Branch_id,No-of_Copies)

BOOK_LENDING(Book_id,Branch_id,Card_No,Date_Out,Due_Date)

LIBRARY_BRANCH (Branch_id, Branch_Name, Address)

WriteSQLqueriesto:

1. Retrieve details of all books in the library– id, title, name of publisher, authors, number of copies
in each branch, etc.
 RajKumarGoelInstituteofTechnology,Ghaziabad
Department ofComputerScience&Engineering

2. Get the particulars of borrowers who have borrowed more than 3 books, but from Jan 2017 to
Jun 2017.

3. Delete a book in BOOK table. Update the contents of other tables to reflect this data
manipulation operation.
 RajKumarGoelInstituteofTechnology,Ghaziabad
Department ofComputerScience&Engineering

4. 4.Partition the BOOK table based on year of publication.Demonstrate its working with a simple
query.

5. Create a view of all book sand its number of copies that are currently available in the Library.
 RajKumarGoelInstituteofTechnology,Ghaziabad
Department ofComputerScience&Engineering
 RajKumarGoelInstituteofTechnology,Ghaziabad
Department ofComputerScience&Engineering

TableCreation

CREATETABLEPUBLISHER (
NAMEVARCHAR2(20)PRIMARYKEY,
PHONE INTEGER,
ADDRESSVARCHAR2 (20)
);

CREATETABLEBOOK
(
BOOK_IDINTEGERPRIMARYKEY,
TITLE VARCHAR2 (20),
PUB_YEARVARCHAR2(20),
PUBLISHER_NAMEREFERENCESPUBLISHER(NAME)ONDELETECASCADE
);

CREATETABLEBOOK_AUTHORS (
AUTHOR_NAMEVARCHAR2(20),
BOOK_IDREFERENCESBOOK(BOOK_ID)ONDELETECASCADE, PRIMARY
KEY (BOOK_ID, AUTHOR_NAME)
);

CREATETABLELIBRARY_BRANCH (
BRANCH_IDINTEGERPRIMARYKEY,
BRANCH_NAME VARCHAR2 (50),
ADDRESSVARCHAR2 (50)
);

CREATETABLEBOOK_COPIES (
NO_OF_COPIESINTEGER,
BOOK_IDREFERENCESBOOK(BOOK_ID)ONDELETECASCADE,
BRANCH_IDREFERENCESLIBRARY_BRANCH(BRANCH_ID)ONDELETECASCADE, PRIMARY
KEY (BOOK_ID, BRANCH_ID)
);

CREATETABLECARD (
CARD_NOINTEGERPRIMARY KEY
);

CREATETABLEBOOK_LENDING (
DATE_OUTDATE,
DUE_DATEDATE,
BOOK_IDREFERENCESBOOK(BOOK_ID)ONDELETECASCADE,
BRANCH_IDREFERENCESLIBRARY_BRANCH(BRANCH_ID)ONDELETECASCADE, CARD_NO
REFERENCES CARD (CARD_NO) ON DELETE CASCADE,
PRIMARYKEY(BOOK_ID,BRANCH_ID,CARD_NO)
);

DBMSLab(KCS-551)Manual(CSE,VSEM) Page6
 RajKumarGoelInstituteofTechnology,Ghaziabad
Department ofComputerScience&Engineering

InsertionofValuesto Tables

INSERTINTOPUBLISHERVALUES(‗MCGRAW-HILL‘,9989076587,‗BANGALORE‘);
INSERT INTO PUBLISHER VALUES (‗PEARSON‘, 9889076565, ‗NEWDELHI‘);
INSERT INTO PUBLISHER VALUES (‗RANDOM HOUSE‘, 7455679345, ‗HYDRABAD‘);
INSERT INTO PUBLISHER VALUES (‗HACHETTE LIVRE‘, 8970862340, ‗CHENAI‘);
INSERTINTOPUBLISHERVALUES(‗GRUPOPLANETA‘,7756120238,‗BANGALORE‘);

INSERT INTO BOOK VALUES (1,‘DBMS‘,‘JAN-2017‘, ‗MCGRAW-HILL‘);


INSERTINTOBOOKVALUES(2,‘ADBMS‘,‘JUN-2016‘,‗MCGRAW-HILL‘);
INSERT INTO BOOK VALUES (3,‘CN‘,‘SEP-2016‘, ‗PEARSON‘);
INSERTINTOBOOKVALUES(4,‘CG‘,‘SEP-2015‘,‗GRUPOPLANETA‘);
INSERT INTO BOOK VALUES (5,‘OS‘,‘MAY-2016‘, ‗PEARSON‘);
INSERT INTO BOOK_AUTHORS VALUES (‘NAVATHE‘, 1);
INSERT INTO BOOK_AUTHORS VALUES (‘NAVATHE‘, 2);
INSERT INTO BOOK_AUTHORS VALUES (‘TANENBAUM‘, 3);
INSERTINTOBOOK_AUTHORSVALUES(‘EDWARDANGEL‘,4);
INSERT INTO BOOK_AUTHORS VALUES (‘GALVIN‘, 5);

INSERTINTOLIBRARY_BRANCHVALUES(10,‘RRNAGAR‘,‘BANGALORE‘);
INSERT INTO LIBRARY_BRANCH VALUES (11,‘RNSIT‘,‘BANGALORE‘);
INSERTINTOLIBRARY_BRANCHVALUES(12,‘RAJAJINAGAR‘,‘BANGALORE‘);
INSERT INTO LIBRARY_BRANCH VALUES (13,‘NITTE‘,‘MANGALORE‘);
INSERTINTOLIBRARY_BRANCHVALUES(14,‘MANIPAL‘,‘UDUPI‘);

INSERTINTOBOOK_COPIESVALUES(10,1,10);
INSERTINTOBOOK_COPIESVALUES(5,1,11);
INSERTINTOBOOK_COPIESVALUES(2,2,12);
INSERTINTOBOOK_COPIESVALUES(5,2,13);
INSERTINTOBOOK_COPIESVALUES(7,3,14);
INSERTINTOBOOK_COPIESVALUES(1,5,10);
INSERTINTOBOOK_COPIESVALUES(3,4,11);

INSERTINTOCARDVALUES(100);
INSERTINTOCARDVALUES(101);
INSERTINTOCARDVALUES(102);
INSERTINTOCARDVALUES(103);
INSERTINTOCARDVALUES(104);

INSERTINTOBOOK_LENDINGVALUES(‘01-JAN-17‘,‘01-JUN-17‘,1,10,101);
INSERTINTOBOOK_LENDINGVALUES(‘11-JAN-17‘,‘11-MAR-17‘,3,14,101);
INSERTINTOBOOK_LENDINGVALUES(‘21-FEB-17‘,‘21-APR-17‘,2,13,101);
INSERTINTOBOOK_LENDINGVALUES(‘15-MAR-17‘,‘15-JUL-17‘,4,11,101);
INSERTINTOBOOK_LENDINGVALUES(‗12-APR-17‘,‘12-MAY-17‘,1,11,104);
 RajKumarGoelInstituteofTechnology,Ghaziabad
Department ofComputerScience&Engineering
 RajKumarGoelInstituteofTechnology,Ghaziabad
Department ofComputerScience&Engineering

Queries:

1. Retrievedetailsofallbooksinthelibrary –id,title,nameofpublisher,authors,numberofcopies in each


branch, etc.

SELECTB.BOOK_ID,B.TITLE,B.PUBLISHER_NAME,A.AUTHOR_NAME,C.NO_OF_COPIES,
L.BRANCH_ID
FROMBOOKB,BOOK_AUTHORSA,BOOK_COPIESC,LIBRARY_BRANCHL WHERE
B.BOOK_ID=A.BOOK_ID
ANDB.BOOK_ID=C.BOOK_IDAND L.BRANCH_ID=C.BRANCH_ID;

2. Gettheparticularsofborrowers who haveborrowedmorethan3books,butfrom Jan2017to Jun


2017.

SELECTCARD_NOFROM BOOK_LENDING
WHEREDATE_OUTBETWEEN‘01-JAN-2017‘AND‘01-JUL-2017‘
GROUP BY CARD_NOHAVING COUNT (*)>3;

3. DeleteabookinBOOK table.Updatethecontentsofothertablestoreflectthisdata
manipulation operation.

DELETEFROMBOOK
WHERE BOOK_ID=3;
 RajKumarGoelInstituteofTechnology,Ghaziabad
Department ofComputerScience&Engineering

4. PartitiontheBOOK tablebasedonyearofpublication.Demonstrateitsworking
withasimple query.

CREATEVIEWV_PUBLICATIONASSELECTPUB_YEARFROMBOOK;

5. Createaviewofallbooksand itsnumberofcopies
thatarecurrentlyavailableintheLibrary.

CREATEVIEWV_BOOKSASSELECTB.BOOK_ID,B.TITLE,C.NO_
OF_COPIES FROM BOOK B, BOOK_COPIES C,
LIBRARY_BRANCH L
WHEREB.BOOK_ID=C.BOOK_IDAND C.BRANCH_ID=L.BRANCH_ID;
• Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering

Theory & Concept


Objective:- To implement the concept of grouping of Data.

Grouping Data From Tables:

There are circumstances where we would like to apply the aggregate function not only to a single set
of tuples, but also to a group of sets of tuples, we specify this wish in SQL using the group by clause.
The attribute or attributes given in the group by clause are used to form group. Tuples with the same
value on all attributes in the group by clause are placed in one group.

Syntax:

SELECT columnname, columnname


FROM tablename
GROUP BY columnname;

At times it is useful to state a condition that applies to groups rather than to tuples. For example we
might be interested in only those branches where the average account balance is more than 1200. This
condition does not apply to a single tuple, rather it applies to each group constructed by the GROUP
BY clause. To express such Questionry, we use the having clause of SQL. SQL applies predicates in
the having may be used.

Syntax:

SELECT columnname, columnname


FROM tablename
GROUP BY columnname;
HAVING searchcondition;

DBMS Lab (KCS-551) Manual (CSE, V SEM) Page 1


• Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering

DBMS Lab (KCS-551) Manual (CSE, V SEM) Page 2


• Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering

EXPERIMENT NO. 7

Objective- Answer the following Queries:

Q1.- Print the description and total quantity sold for each product.

Q2.- Find the value of each product sold.

DBMS Lab (KCS-551) Manual (CSE, V SEM) Page 3


• Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering

Q3.- Calculate the average quantity sold for each client that has a maximum
order value of 15000.

DBMS Lab (KCS-551) Manual (CSE, V SEM) Page 4


• Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering

Q4.- Find out the products which has been sold to Ivan.

Q5.- Find the names of clients who have ‘CD Drive’.

DBMS Lab (KCS-551) Manual (CSE, V SEM) Page 5


• Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering

Q6.- Find the products and their quantities for the orders placed by ‘Vandana’ and ‘Ivan’.

Q7.- Select product_no, total qty_ordered for each produ

DBMS Lab (KCS-551) Manual (CSE, V SEM) Page 6


• Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering

Q8.- Select product_no, product description and qty ordered for each product.

DBMS Lab (KCS-551) Manual (CSE, V SEM) Page 7


• Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering

Q9.- Display the order number and day on which clients placed their order.

Q10.- Display the month and Date when the order must be delivered.

DBMS Lab (KCS-551) Manual (CSE, V SEM) Page 8


 Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering

Theory & Concept


Objective:- To implement the concept of Sub Queries.

Sub Queries:- A Sub Queries is a form of an SQL statement that appears inside another SQL
statement. It also termed as nested Questionry. The statement containing a Sub Queries called a parent
statement. The rows returned bu the Sub Queries are use by the following statement.
It can be used by the following commands:
1. To insert records in the target table.
2. To create tables and insert records in this table.
3. To update records in the target table.
4. To create view.
5. To provide values for the condition in the WHERE , HAVING IN , SELECT,UPDATE, and
DELETE statements.

Example: Creating client master table from oldclient_master, table

Create table client_master AS SELECT * FROM oldclient_master;

Using the Union, Intersect and Minus Clause:

Union Clause:
The user can put together multiple Queries and combine their output using the union clause . The union
clause merges the output of two or more Queries into a single set of rows and column. The final output
of union clause will be

Output: = Records only in Questionry one + records only in Questionry two + A single set of records
with is common in the both Queries.

Syntax: SELECT columnname, columname FROM tablename 1


UNION SELECT columnname, columnname From tablename2;

Intersect Clause: The use can put together multiple Queries and their output using the interest
clause. The final output of the interest clause will be :

Output =A single set of records which are common in both Queries

Syntax: SELECT columnname, columnname


FROM tablename 1
INTERSECT
SELECT columnname, columnname
FROM tablename 2;

MINUS CLAUSE:- The user can put together multiple Queries and combine their output = records
only in Questionry one

Syntax: SELECT columnname, columnname


FROM tablename MINUS
SELECT columnname, columnname
FROM tablename ;

DBMS Lab (KCS-551) Manual (CSE, V SEM) Page 1


 Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering

Experiment No.8
Objective: Answer the following Queries:

QUERIES:

1. Find the product_no and description of non- moving products.

2. Find the customer name, address, city and pincode for the client who
has placed order no “019001”

DBMS Lab (KCS-551) Manual (CSE, V SEM) Page 2


 Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering

3. Find the client names who have placed order before the month of may 96.

4. Find out if product “1.44 Drive” is ordered by only client and print the
client_no name to whom it was sold.

DBMS Lab (KCS-551) Manual (CSE, V SEM) Page 3


 Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering

5. find the names of client who have placed orders worth Rs.10000 or more.

6. Select the orders placed by ‘Rahul Desai”

7. Select the names of persons who are in Mr. Pradeep’s department and
who have also worked on an inventory control system.

DBMS Lab (KCS-551) Manual (CSE, V SEM) Page 4


 Raj Kumar Goel Institute of Technology, Ghaziabad
Department of Computer Science & Engineering

8. Select all the clients and the salesman in the city of Bombay.

9. Select salesman name in “Bombay” who has atleast one client located at
“Bombay”

10. Select the product_no, description, qty_on-hand,cost_price of


non_moving items in the product_master table.

DBMS Lab (KCS-551) Manual (CSE, V SEM) Page 5


Theory and Concept:

Objective:- To implement the concept of Indexes and views.

Indexes- An index is an ordered list of content of a column or group of columns in a table. An index created
on the single column of the table is called simple index. When multiple table columns are included in the
index it is called composite index.

Creating an Index for a table:-

Syntax (Simple)
CREATE INDEX index_name
ON tablename(column name);

Composite Index:-

CREATE INDEX index_name


ON tablename(columnname,columnname);

Creating an UniQuestion Index:-

CREATE UNIQUESTION INDEX indexfilename


ON tablename(columnname);

Dropping Indexes:- An index can be dropped by using DROP INDEX

SYNTAX:-
DROP INDEX indexfilename;

Views:-

Logical data is how we want to see the current data in our database. Physical data is how this
data is actually placed in our database.

Views are masks placed upon tables. This allows the programmer to develop a method via
which we can display predetermined data to users according to our desire.

Views may be created fore the following reasons:

1. The DBA stores the views as a definition only. Hence there is no duplication of data.
2. Simplifies Queries.
3. Can be Questionried as a base table itself.
4. Provides data security.
5. Avoids data redundancy.
Creation of Views:- Syntax:-

CREATE VIEW viewname AS


SELECT columnname,columnname
FROM tablename
WHERE columnname=expression_list;

Renaming the columns of a view:- Syntax:-

CREATE VIEW viewname AS


SELECT newcolumnname….
FROM tablename
WHERE columnname=expression_list;

Selecting a data set from a view- Syntax:-

SELECT columnname, columnname


FROM viewname
WHERE search condition;

Destroying a view-

Syntax:-
DROP VIEW viewname;
Experiment # 9

Objective: Answer the following Questions

Q1. Create an index on the table


client_master, field client_no. Q2. Create an
index on the sales_order, field s_order_no.
Q3. Create an composite index on the sales_order_details table for the
columns s_order_no and product_no.
Q4. Create an composite index ch_index on challan_header table for the
columns challan no and s_order_no.
Q5. Create an uniQuestion index on the table
salesman_master, field salesman_no. Q6. Drop index ch_index on
table challan_header.
Q7. Create view on salesman_master whose sal_amt is less than 3500.
Q8. Create a view client_view on client_master and rename the columns as
name, add1, add2, city, pcode, state respectively.
Q9. Select the client names from client_view who
lives in city ‘Bombay’. Q10. Drop the view client_view.

OUTPUT:

1.

2.

3.

4.
5.

6.

7.

8.

9.
Theory and Concept

Objective:- To implement the basics of PL/SQL.

Introduction – PL/SQL bridges the gap between database technology and procedural
programming languages. It can be thought of as a development tool that extends the facilities of
Oracles SQL database language. Via PL/SQL you can insert, delete, update and retrieve table data as
well as use procedural techniQuestions such as writing loops or branching to another block of code.

PL/SQL Block structure-

DECLARE
Declarations of memory variables used later
BEGIN
SQL executable statements for manipulating table data.
EXCEPTIONS
SQL and/or PL.SQL code to handle errors.
END;

Displaying user Messages on the screen – Any programming tool requires a method
through which messages can be displayed to the user.

dbms_output is a package that includes a number of procedure and functions that accumulate
information in a buffer so that it can be retrieved later. These functions can also be used to display
message to the user.

put_line: put a piece of information in the buffer followed by a end of line marker. It can also be used
to display message to the user.
Setting the server output on:

SET SERVER OUTPUT ON:

Example: Write the following code in the PL/SQL block to display message to user
DBMS_OUTPUT.PUT_LINE(‘Display user message’);

Conditional control in PL/SQL-


Syntax:
IF <condition> THEN
<Action>
ELSEIF<condition>
<Action>
ELSE
<Action>
ENDIF;
The WHILE LOOP:
Syntax:
WHILE <condition>
LOOP
<Action>
END LOOP;

The FOR LOOP statement:

Syntax:
FOR variable IN [REVERSE] start—end
LOOP
<Action>
END LOOP;

The GOTO statement: The goto statement allows you to change the flow of control within a
PL/SQL Block.
Experiment No.10

Q1. WAP in PL/SQL for addition of two numbers.

Q2. WAP in PL/SQL for addition of 1 to 100 numbers.

Q3. WAP in PL/SQL to check the given number is even or odd.

Q4. WAP in PL/SQL to inverse a number, eg. Number 5639 when inverted must be display
output 9365.

Q5. WAP in PL/SQL for changing the price of product ‘P00001’ to 4000 if the price is less than
4000 in product_master table. The change is recorded in the old_price_table along with
product_no and the date on which the price was changed last.

OUTPUT:

1.

2.
3.

4.
Theory and Concept :
Objective:- To implement the concept of Cursor and Trigger.

Cursor–

We have seen how oracle executes an SQL statement. Oracle DBA uses a work area for its internal
processing. This work area is private to SQL’s operation and is called a cursor.
The data that is stored in the cursor is called the Active Data set. The size of the cursor in memory is
the size required to hold the number of rows in the Active Data Set.

Explicit Cursor-

You can explicitly declare a cursor to process the rows individually. A cursor declared by the user is
called Explicit Cursor. For Queries that return more than one row, You must declare a cursor explicitly.
The data that is stored in the cursor is called the Active Data set. The size of the cursor in memory is
the size required to hold the number of rows in the Active

Why use an Explicit Cursor- Cursor can be used when the user wants to process data one row
at a time.

Explicit Cursor Management-

The steps involved in declaring a cursor and manipulating data in the active data set are:-
 Declare a cursor that specifies the SQL select statement that you want to process.
 Open the Cursor.
 Fetch the data from the cursor one row at a time.
 Close the cursor.

Explicit Cursor Attributes-

Oracle provides certain attributes/ cursor variables to control the execution of the cursor. Whenever
any cursor(explicit or implicit) is opened and used Oracle creates a set of four system variables via
which Oracle keeps track of the ‘Current’ status of the cursor.

 Declare a cursor that specifies the SQL select statement that you want to process.
 Open the Cursor.
 Fetch the data from the cursor one row at a time.
 Close the cursor.

How to Declare the Cursor:-

The General Syntex to create any perticular cursor is as follows:-


Cursor <Cursorname> is Sql Statement;
How to Open the Cursor:-

The General Syntex to Open any perticular cursor is as follows:-


Open Cursorname;

Fetching a record From the Cursor:-

The fetch statement retrieves the rows from the active set to the variables one at a time. Each time a
fetch is executed. The focus of the DBA cursor advances to the next row in the Active set.
One can make use of any loop structute(Loop-End Loop along with While,For) to fetch the records
from the cursor into variable one row at a time.

The General Syntex to Fetch the records from the cursor is as follows:-
Fetch cursorname into variable1,variable2,

Closing a Cursor:-

The General Syntex to Close the cursor is as follows:-


Close <cursorname>;

Database Triggers:-

Database triggers are procedures that are stored in the database and are implicitly executed(fired)
when the contents of a table are changed.

Use of Database Triggers:-

Database triggers support Oracle to provide a highly customized database management system. Some
of the uses to which the database triggers can be put to customize management information in Oracle
are as follows:-
 A Trigger can permit DML statements against a table anly if they are issued, during regular
bussiness hours or on predetermined weekdays.
 A trigger can also be used to keep an audit trail of a table along with the operation performed
and the time on which the operation was performed.
 It can be used to prevent invalid transactions.
 Enforce complex security authorizations.

How to apply DataBase Triggers:-

A trigger has three basic parts:-


1. A triggering event or ststement.
2. A triger restriction
3. A trigger action.
Types of Triggers:-

Using the various options , four types of triggers can be created:-

1. Before Statement Trigger:- Before executing the triggering statement, the trigger action is
executed.

2. Before Row Trigger:- Before modifying the each row affected by the triggering statement and
before appropriate integrity constraints, the trigger is executed if the trigger restriction either
evaluated to TRUE or was not included.’

3. After Ststement Trigger:- After executing the triggering statement and applying any deferred
integrity canstraints, the trigger action is executed.

4. After row Trigger:- After modifying each row affected by the triggering statement and
possibly applying appropriate integrity constraints, the trigger action is executed for the current
row if the trigger restriction either evaluates to TRUE or was not included.

Syntex For Creating Trigger:-

The syntex for Creating the Trigger is as follows:-

Create or replace Trigger<Triggername> {Before,After} {Delete, Insert, Update } On <Tablename>


For Each row when Condition
Declare
<Variable declarations>;
<Constant Declarations>;
Begin
<PL/SQL> Subprogram Body;
Exception
Exception Pl/SQL block;
End;

How to Delete a Trigger:-

The syntex for Deleting the Trigger is as follows:-


Drop Trigger <Triggername>;
Table Name:0- Employee

Column Name Data Type Size Attributes


Emp_Code Varchar2 10 Primary Key
Ename Varchar2 20 The name of the Candidate
Deptno Number 5 The Department No
Job Vrachar2 20 The Employee Job Detail
Salary Number 8,2 The Current salary of Em

Table name:- Emp_raise

Column Name Data Type Size Attributes


Emp_Code Varchar2 10 Primary Key
Raise_Date date The Date On which the raise was given
Raise_Amt Number 8,2 The raise given to the employee

The HRD manager has decided to raise the salary for all the employees in the Dept
No 20 by 5%. Whenever any such raise is given to the employees, a record for the
same is maintained in the emp_raise table. It includes the EmpNo, the date when
the raise was given and the actual raise. Write a PL/SQL block to update the salary
of each employee and insert a record in the emp_raise table.

Q2:- Two Tables are there

Table Name:- Client_Master

Column Name Data Type Size Attributes


Client_No Varchar2 6 Primary Key/First letter must start with ‘C’
Name Varchar2 20 Not Null
City Varchar2 10
State Vrachar2 10
Bal_Due Number 10,2

Table name:- auditclient

Column Name Data Type Size Attributes


Client_No Varchar2 10 Primary Key
Name Varchar2 20
Bal_Due Number 10,2
Operation Varchar2 8
Odate Date

Create a transparent audit system for a table Client_master. The system must keep
track of the records that are being deleted or modified and when they have been
deleted or modified.
Sol 1:

Sol 2:

You might also like