DBMSlabfile
DBMSlabfile
EXPERIMENT 01
DATABASE :
A database is a collection of data that is organized, which is also called structured
data. It can be accessed or stored in a computer system. It can be managed
through a Database Management System (DBMS), a software used to manage
data. Database refers to related data in a structured form.
In a database, data is organized into tables consisting of rows and columns and it
is indexed so data can be updated, expanded, and deleted easily. Computer
databases typically contain file records data like transactions money in one bank
account to another bank account, sales and customer details, fee details of
students, and product details. There are different kinds of databases, ranging from
the most prevalent approach, the relational database, to a distributed database,
cloud database, and NoSQL databases.
Types of Databases :
NoSQL Databases: Unlike relational databases, which specify how all data
input must be formatted, NoSQL, or non relational databases, permit the storing
and manipulation of unstructured and semistructured data. The prevalence and
complexity of online applications led to the rise in popularity of NoSQL
databases.
Graph Databases: Data is stored in a graph database using entities and their
relationships.
Open source databases: A database system that is open source can have
either a SQL or NoSQL database as its source code.
STEP 12 : Customise Data file, Control file and Redo file Location
c
Experiment No.2
View definition-
The SQL DDL includes commands for defining views.
Transaction Control- SQL includes for specifying the beginning and ending of transactions.
Integrity-
The SQL DDL includes commands for specifying integrity constraints that the data stored in the database must specify.
Updates that violate integrity constraints are allowed.
Authorization-
The SQL DDL includes commands for specifying access rights to relations and views.
The SQL standard supports a variety of built in domain types, including● Char (n)- A
fixed length character length string with user specified length .
● Varchar (n)- A variable character length string with user specified maximum length n.
● Int- An integer.
● Small integer- A small integer.
● Numeric (p, d)-A Fixed point number with user defined precision.
● Real, double precision- Floating point and double precision floating point numbers with machine
dependent precision.
● Float (n)- A floating point number, with precision of at least n digits.
● Date- A calendar date containing a (four digit) year, month and day of the month.
● Time- The time of day, in hours, minutes and seconds Eg. Time ’09:30:00’. ● Number- Number is used
to store numbers (fixed or floating point). DDL statement for creating a table-
Syntax-
Syntax-
Syntax-
Raj Kumar Goel Institute of Technology, Ghaziabad
Syntax-
INSERT INTO tablename SELECT columnname,
columnname,
…….
FROM tablename;
Syntax-
INSERT INTO tablename
SELECT columnname, columnname… FROM tablename
WHERE columnname= expression;
Retrieving of data from the tables-
Syntax-
SELECT * FROM tablename;
The retrieving of specific columns from a table-
Syntax-
SELECT columnname, columnname, ….
FROM tablename;
Elimination of duplicates from the select statement-
Syntax-
i) client_master
Maharashtra 15000
x) List the name, city and state of clients not in the state of ‘Maharashtra’.
OUTPUT
1 i)
ii)
2 i)
ii)
3 i)
Raj Kumar Goel Institute of Technology, Ghaziabad
ii)
iii)
iv)
Raj Kumar Goel Institute of Technology, Ghaziabad
v)
vi)
vii)
viii)
Raj Kumar Goel Institute of Technology, Ghaziabad
ix)
x)
Raj Kumar Goel Institute of Technology, Ghaziabad
Experiment No.3
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 :
/ 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
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.
Raj Kumar Goel Institute of Technology, Ghaziabad
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)
Question.1 Using the table client master and product master answer the following Queries.
price of products. xii. Determine the maximum and minimum prices . Rename the tittle as ‘max_price’ and
i)
min_price respectively.
xiii. Count the number of products having price greater than or equal to 1500.
OUTPUT:
ii)
iii)
Raj Kumar Goel Institute of Technology, Ghaziabad
iv)
v)
vi)
Vii)
Raj Kumar Goel Institute of Technology, Ghaziabad
viii)
ix)
x)
Raj Kumar Goel Institute of Technology, Ghaziabad
xi)
xii)
xiii)
Raj Kumar Goel Institute of Technology, Ghaziabad
Experiment No.4
Data constraints: Besides the cell name, cell length and cell data type there are other parameters i.e. other data
constrains that can be passed to the DBA at check creation time. The constraints can either 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 level constraints.
Null Value Concepts:- while creating tables if a row locks a data value 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:
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 uniQuestion across the column. A multicolumn
primary key is called composite primary key.
UniQuestion key concept:-A uniQuestion is similar to a primary key except that the purpose of a
uniQuestion key is to ensure that information in the column for each record is uniQuestion as with
telephone or devices license numbers. A table may have many uniQuestion keys.
Raj Kumar Goel Institute of Technology, Ghaziabad
Default value concept: At the line of cell creation a default value can be assigned to it. When the user is
loading a record with values and leaves this cell empty, the DBA wil automatically
load this cell with the default value specified. The data type of the default value should match the data
type of the column
Syntax:
Create table tablename
(columnname datatype (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. Foreign key as a column constraint
Syntax :
Create table table name
(columnname datatype (size) references another table name); Foreign key as a
table constraint:
Syntax :
Create table name (columnname datatype
(size)…. primary key (columnname); foreign key
(columnname)references table name);
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.
Raj Kumar Goel Institute of Technology, Ghaziabad
● 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:
Create table tablename
(columnname datatype (size) CONSTRAINT constraintname)
Check (expression));
i. Sales_master
Columnname Datatype Size Attributes
State varchar2 20
Pincode Number 6
Sal_amt Number 8,2 Not null, cannot be 0
ii. Sales_order
Columnname Datatype Size Attributes
Client_no Varchar2 25
Dely_add Varchar2 6
Billed_yn Char 1
Qty_order Number 8
Qty_disp Number 8
500001 Kiran A/14 worli Bomba 400002 Mah 3000 100 50 Good
y
500002 Manish 65,nariman Bomba 400001 Mah 3000 200 100 Good
y
500003 Ravi P-7 Bandra Bomba 400032 Mah 3000 200 100 Good
y
500004 Ashish A/5 Juhu Bomba 400044 Mah 3500 200 150 Good
y
Data for salesorder table:
S_orderno S_orderdate Client no Dely Bill yn Salesman no Delay Orderstatus
type date
OUTPUT:
Creation i)
ii)
iii)
Raj Kumar Goel Institute of Technology, Ghaziabad
Insertion i)
ii)
iii)
Raj Kumar Goel Institute of Technology, Ghaziabad
Experiment No.5
Alter table command is used to changing the structure of a table. Using the alter table clause you cannot perform
the following tasks:
table command.
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.
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.
Raj Kumar Goel Institute of Technology, Ghaziabad
Syntax:
ALTER TABLE tablename
ADD CONSTRAINT constraintname
FOREIGN KEY(columnname) REFERENCES tablename;
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.
OUTPUT
1
i)
Raj Kumar Goel Institute of Technology, Ghaziabad
ii)
2
i)
ii)
Raj Kumar Goel Institute of Technology, Ghaziabad
ii)
Raj Kumar Goel Institute of Technology, Ghaziabad
Experiment No.6
The tables that have to be joined are specified in the FROM clause and the joining attributes in the WHERE clause.
1. Cartesian product:-
Consider two table student and course Select
B.*,P.*
FROM student B, course P;
2. INNER JOIN:
Cartesian product followed by selection
Select B.*,P.*
FROM student B, Course P WHERE
B.course # P.course # ;
Exam:
Select B.*,P.*
From student B RIGHT JOIN course P
B.course# = P course # ;
1. Retrieve details of all books in the library – id, title, name of publisher, authors, number of copies in each
branch, etc.
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.
4. 4. Partition the BOOK table based on year of publication. Demonstrate its working with a simple query.
5. Create a view of all books and its number of copies that are currently available in the Library.
Raj Kumar Goel Institute of Technology, Ghaziabad
OUTPUT
1 i)
Raj Kumar Goel Institute of Technology, Ghaziabad
ii)
iii)
iv)
v)
Raj Kumar Goel Institute of Technology, Ghaziabad
Table Creation
TABLE CARD
TABLE BOOK_LENDING
(DATE_OUT DATE,
DUE_DATE DATE,
Raj Kumar Goel Institute of Technology, Ghaziabad
Queries:
Raj Kumar Goel Institute of Technology, Ghaziabad
1. Retrieve details of all books in the library – id, title, name of publisher, authors, number of copies
in each branch, etc.
2. Get the particulars of borrowers who have borrowed more than 3 books, but from Jan 2017 to Jun
2017.
4. Partition the BOOK table based on year of publication. Demonstrate its working with a simple
query.
5. Create a view of all books and its number of copies that are currently available in the Library.
QUERIES -
1. Find out the product which has been sold to ‘Ivan Sayross.’ 2. Find out the
product and their quantities that will have do delivered.
3. Find the product_no and description of moving products.
4. Find out the names of clients who have purchased ‘CD DRIVE’
5. List the product_no and s_order_no of customers haaving qty ordered less than 5 from the
order details table for the product “1.44 floppies”.
6. Find the products and their quantities for the orders placed by ‘Vandan Saitwal ’ and “Ivan
Bayross”.
7. Find the products and their quantities for the orders placed by client_no “ C00001” and
“C00002”
8. Find the order No,, Client No and salesman No. where a client has been received by more
than one salesman.
9. Display the s_order_date in the format “dd-mm-yy” e.g. “12- feb-96”
10. Find the date , 15 days after date.
Raj Kumar Goel Institute of Technology, Ghaziabad
OUTPUT
Raj Kumar Goel Institute of Technology, Ghaziabad
Experiment No.7
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:
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:
Q1.- Print the description and total quantity sold for each product.
Q3.- Calculate the average quantity sold for each client that has a maximum order value of 15000.
Raj Kumar Goel Institute of Technology, Ghaziabad
Q4.- Find out the products which has been sold to Ivan.
Q6.- Find the products and their quantities for the orders placed by ‘Vandana’ and ‘Ivan’.
Q8.- Select product_no, product description and qty ordered for each product.
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.
OUTPUT
Raj Kumar Goel Institute of Technology, Ghaziabad
Experiment NO.8
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.
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.
Raj Kumar Goel Institute of Technology, Ghaziabad
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
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 ;
QUERIES:
OUTPUT
Raj Kumar Goel Institute of Technology, Ghaziabad
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.
CreatinganIndexforatable:-
Syntax(Simple)
CREATEINDEXindex_name
ON tablename(column name);
CompositeIndex:-
CREATEINDEXindex_name
ONtablename(columnname,columnname);
CREATEUNIQUESTIONINDEXindexfilename
ON tablename(columnname);
DroppingIndexes:-AnindexcanbedroppedbyusingDROP INDEX
SYNTAX:-
DROP INDEX index filename;
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.
Viewsaremasksplacedupontables.Thisallowstheprogrammertodevelopamethodvia which we
can display predetermined data to users according to our desire.
Viewsmaybecreatedforethefollowingreasons:
1. TheDBAstorestheviewsasadefinitiononly.Hencethereisnoduplicationofdata.
2. SimplifiesQueries.
3. CanbeQuestionried asabasetableitself.
4. Providesdata security.
5. Avoidsdata redundancy.
DBMSLab(KCS-551)Manual(CSE,VSEM) Page1
Raj Kumar Goel Institute of Technology, Ghaziabad
CREATEVIEWviewnameAS
SELECT newcolumnname….
FROM tablename
WHEREcolumnname=expression_list;
SELECTcolumnname,columnname
FROM viewname
WHEREsearchcondition;
Destroying a view-
Syntax:-
DROP VIEWviewname;
DBMSLab(KCS-551)Manual(CSE,VSEM) Page2
Raj Kumar Goel Institute of Technology, Ghaziabad
Experiment 9
Q5.CreateanuniQuestionindexonthetablesalesman_master,fieldsalesman_no.
Q9. Select the client names from client_view who lives in city ‘Bombay’.
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.
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:
Example: Write the following code in the PL/SQL block to display message to user
DBMS_OUTPUT.PUT_LINE(‘Display user message’);
The GOTO statement: The goto statement allows you to change the flow of control within a
PL/SQL Block.
Raj Kumar Goel Institute of Technology, Ghaziabad
Experiment No.10
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.
Raj Kumar Goel Institute of Technology, Ghaziabad
3.
4.
Raj Kumar Goel Institute of Technology, Ghaziabad
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.
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.
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.
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.
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.
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.
Name:- Client_Master
Sol 1:
Sol 2: