dbms
dbms
Laboratory Manual
NAME
ENROLLMENT NUMBER
BATCH
YEAR
“To create competent professionals in the field of Computer Engineering and promote research
with a motive to serve as a valuable resource for the IT industry and society.”
It gives us immense pleasure to present the first edition of DBMS Practical Book for the B.E.
2nd year students of Ahmedabad Institute of Technology.
The theory and laboratory course of Database Management System, at AIT, AHMEDABAD, is
designed in such a manner that students can develop the basic understanding of the subject during
theory classes and gain hands-on practical experience during their laboratory sessions. The main
objective of the Database Management System laboratory course is: Learning Database Management
System through its basic principles and characteristics. All the experiments are designed to
understand the characteristics of various database concepts. The objective of this DBMS Practical
Book is to provide a comprehensive source for all the experiments included in the DBMS laboratory
course.We acknowledge the authors and publishers of all the books which we have consulted while
developing this Practical book. Hopefully this Database Management System Practical Book will
serve the purpose for which it has been developed.
The student is required to keep a laboratory manual in which the raw data will be recorded as well as
the questions will be kept. The lab write-ups form a permanent record of your work.
Do’s
2 Leave footwear outside and keep bags or any other belongings in designated storage places.
Do not keep any valuable things in bags.
3 Carry only the laboratory notebook into the laboratory and keep other belongings at the place
designated for keeping belongings.
4 Know the location of the fire extinguisher and the first aid box and how to use them in case
of an emergency.
5 Report fires or accidents to your lecturer/laboratory technician immediately
6 Report any broken plugs or exposed electrical wires to your lecturer/laboratory technician
immediately.
7 Read and understand how to carry out an activity thoroughly before coming to the laboratory.
8 For system problems, call laboratory staff for resolving, and do not try to repair the system
on your own.
9 Access to the internet is only on designated systems and against permission.
10 Ensure computer systems are properly shutdown and other equipment are turned-off after
use.
11 Follow the rules of the laboratory strictly. Violation of rules may attract punishment.
Don’ts
2 Do not carry and use any pen drive, electronic gadget or cell phone in the laboratory.
3 Do not install, update or download any software on your own in any computer inside the
laboratory.
4 Do not use any unauthorized software or tools.
11 Do not insert metal objects such as clips, pins and needles into the computer casings. They
may cause fire.
Ahmedabad Institute of Technology
Computer Engineering Department
CERTIFICATE
This is to certify that Mr. / Ms.
Of Enrolment No has Satisfactorily
completed the course in as
by the Gujarat Technological University for Year (B.E.) semester
of Computer Engineering in the Academic year .
Date of Submission:-
From To
THEORY:
DBMS is a collection of interrelated data and a set of programs to access those data.
Primary goal of DBMS is to provide a way to store and retrieve database information
that is both convenient and efficient.
Examples of DBMS are Banking System, Universities, Airlines, etc.
❖ Introduction of Oracle:
The relational model, sponsored by IBM (in June 1970), then came to accepted as the definitive
model for RDBMS. The language developed by IBM to manipulate the data stored within
model was originally called Structured English Query Language (SEQUEL) with the word
English later dropped in favor Structured Query Language (SQL).
In 197 released the first commercially available implementation of SQL. Relational Software
later come to be known as Oracle Corporation. Oracle Corporation is a company that
produces the most widely used, Server based, Multi user RDBMS named Oracle.
❖ Oracle Tools:
▪ Oracle Server tools: Oracle Server Product is either called Oracle Work group Server or
Oracle Enterprise Server. Oracle Workgroup Server or Oracle Enterprise Server is used
for data storage.
▪ Oracle Client tools: The client roll most commonly used for Commercial Application
Development is called Oracle Developer 2000. Oracle’s tool box which consists of
Oracle Forms, Oracle Reports and Oracle Graphics. This suite of tools is used to
capture, validate and display data according to user and system need
▪ SQL*Plus is a separate Oracle client-side tool. Oracle Workgroup or Enterprise Server is bundled with
this SQL*Plus. It is a product that works on Microsoft Windows 95 and Windows NT both of which
are standard Client based GUI operating systems.
▪ Oracle Workgroup Server and Oracle Developer 2000 are separate products and they must be
purchased separately.
❖ Components of SQL:
1) DDL (Data Definition Language):
Is a language, which includes the commands, which are used dynamically to setup, change and
remove any data structure e.g. tables, views and indexes. The examples are CREATE, ALTER &
DROP.
2) DML (Data Manipulation Language):
Is a language, which includes the commands, which are used to enter new rows ,change existing
rows and remove unwanted rows from the tables in data base. The examples are INSERT, UPDATE
& DELETE.
3) DCL (Data Control Language):
Is a language, which includes the commands, which are used to give or remove access rights to both
the Oracle database and the structures with in it. The examples are GRANT & REVOKE.
4) DQL (Data Query Language):
It is the component of SQL statement that allows getting data from the database and imposing
ordering upon it. In includes the SELECT statement. It allows getting the data out of the database
perform operations with it.
❖ The CREATE TABLE command: The CREATE TABLE command defines each column of
the table uniquely. Each column has a minimum of three attributes, a name, data type and size (i.e.
column width).
EXCERCISE:
1) Create a table “emp” with the following fields:
EMPNO ENAME POST HIREDATE SALARY CONTACT DEPTNO ADDR
3) Create a table “stud_master” with the following fields: REG_NO S_NAME BRANCH
EVALUATION:
Involvement (4) Understanding Timely Total(10)
/problem solving (3) Completion(3)
TITLE: How to insert data in a table using insert command and display the records in a table.
THEORY:
❖ Inserting Data into Tables using INSERT INTO command:
Once a table is created, most natural thing to do is load this table with data to be
manipulated later.
When inserting a single raw of data into the table, insert operation:
Note: Character value (expression) placed within the INSERT INTO statement must be
enclosed in single quotes (‘).
Once data has been inserted into a table, the next most logical operation would be to view what
has been inserted. The SELECT SQL verb is used to achieve this. The SELECT command is used
to retrieve rows selected from one or more tables.
▪ The SELECT statement can be used to Display some or all the columns from a specified table.
▪ Display some or all of the rows from a specified table. ▪ Display calculated values from the
table.
▪ Display statistical information from the tables, like averages or sums of column values.
▪ Combine information from two or more tables.
In order to view global table data the syntax is:
SELECT <Column Name 1> TO <Column Name N> from Table Name;
Note: Here, Column Name 1 to Column Name N represents table column names and‘,’.
they separated by
All Rows and All Columns: When data from all rows and columns from the table are to be
viewed the syntax of the SELECT statement will be used. The syntax is:
Oracle allows the use of the Meta character asterisk (*), this is expanded by Oracle to mean all rows
and all columns in the table.
The SELECT DISTINCT * SQL syntax scans through entire rows, andeliminates rows that have
exactly the same contents in each column.
Sort Order can be ascending (use word asc) or descending (use word esc). In case there is no mention
of the sort order, the Oracle engine sorts in ascending order by default.
Examp SELECT * FROM client_master ORDERBYName;(In ascending order)
le: SELECT * FROM emp ORDER BY Job DESC; (Indescendingorder)
EXERCISES:
EVALUATION:
TITLE: Update or Delete records of a table and modifying structure of a table using Alter and
Drop command.
⮚ drop a table.
THEORY:
Example: Update the address details by changing its city name to Ahmedabad.
UPDATE ADDR_DTLS SET City = ‘Ahmedabad’;
Example: Update the branch details by changing the AMP (HO) to HeadOffice.
UPDATE BRANCH_MSTR SET NAME = ‘Head Office’ WHERE
NAME = ‘AMP (HO)’;
❖ Delete Operations:
The DELETE command deletes rows from the table that satisfies theconditionprovided by its
WHERE clause, and returns the number of records deleted.
Removal of All Rows:
Here the WHERE clause is optional. If you are not specify the WHEREclausethen all the from source
table to target table is copied.
Example: Insert only the savings bank accounts details in the target table
ACCT_DTLS from the source table ACCT_MSTR.
INSERT INTO ACCT_DTLS SELECT ACCT_NO,BRANCH_NO,CURBAL
FROMACCT_MSTRWHERE ACCT_NO LIKE ‘SB%’;
Example: Enter a new field called city in the table BRANCH_MSTR. ALTER
TABLE BRANCH_MSTR ADD(CITY VARCHAR2(25));
:
Dropping a Column from a Table:
❖ Destroying Tables:
Sometimes tables within a particular database become obsolete andneedtobe
discarded. In such situation using DROP TABLE statement with the tablenamecan destroy a specific
table. If a table is dropped all records held withinit arelostand cannot be recovered.
Example: Remove the table BRANCH_MSTR along with the data held. DROP
TABLE BRANCH_MSTR;
EXCERCISES:
1) Add a column “SPOUSE” to the emp table that will hold the name of an employee’s
spouse.
2) Add a column “email” to emp table
3) update spouse name 'sunita' for eno=001; 'rita' for eno=002;'mita' for eno=003;
EVALUATION:
Involvement (4) Understanding Timely Total(10)
/problem solving (3) Completion(3)
THEORY:
❖ Character functions:
INITCAP(s) Returns the string s with the first character of INITCAP('hello SIR') ='Hello
Sir'
each word in uppercase and all others lowercas
LOWER(s) Returns the string s with all characters in lowe LOWER('Welcome Sir') ='welco
sir'
case.
VSIZE(s) Returns the number of bytes in the internal VSIZE('SCT on the net') =14
representation of an s.
5) Print the first four character of ‘Ahmedabad’ and 4 character from the last
EVALUATION:
TITLE: Study of number and date functions for manipulation of data items.
❖ Number functions:
Number functions are described as follow:
LEAST Used to Find out Lowest Value from the LEAST (exp1,exp2,.,expn);
Expression Select Least(35,75,25) From
dual;=25
ABS(d) Returns the absolute value of the double d. ABS(-25.52) = 25.52
Returns the smallest integer that is greater CEIL(24.8) = 25
CEIL(d) or equal to d.
CEIL(-24.8)= -24
EXP(d) Returns e^d EXP(5) = 148.413159
FLOOR(24.8) = 24,
FLOOR(d) Returns the largest integer less or equal to d.
FLOOR(-24.8)= -25
LN(d) Returns the natural logarithm of d. LN(10) = 2.30258509
LOG(b, d) Returns logbd. LOG(10,40) = 1.60205999
Returns i1 modulo i2, or the reminder of i1
MOD(i1, i2) MOD(15,7) = 1
divided i2.
POWER(d, p) Returns d to the pth power (d^p). POWER(2,5)= 32
Returns d rounded to i digits of precision to
the right of the decimal point. If i is negative, ROUND(2.6586,2) = 2.66
ROUND(d, i) d is rounded to the left of the ROUND(289.6586,-2)= 300
decimal point.
SIGN(-25) = -1
SIGN(d) Returns -1 if d is negative, 1 if d is positive,
and 0 if d is zero. SIGN(0) = 0
SIGN(25) = 1
SQRT(d) Returns the square root of d. SQRT(81) = 9
❖ Date functions:
Implicit Date-to-String conversion is based on the value of the
NLS_DATE_FORMAT variable. To change its value use the ALTER SESSION
command:
ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MM-YYYY HH24:MI:SS';
Date functions are described as follow:
MONTHS_BETWEEN(
Returns the number of months that '01-JAN-
MONTHS_BETWEEN(dt1,
dt1 is later than dt2. 2009',SYSDATE) = 4
dt2) Months_Between('02-feb-08','
02-jan-08') "Month" from
dual;=1
Function Description
Takes up to three arguments, where x is either a date or a number, fmt is a
TO_CHAR(x[, format string specifying the format that x will appear in, and nls specifies
fmt[, nls]]) language or location formatting string. If x is a
date, fmt is a date format code. If x is a number, fmt is a
numeric format code.
EXCERCISE:
name salary
ashish 23000.562
roma 43250.466
kamal 21111.111
divya 32151.110
a) print salary of each candidate round of two digit in ascending order of salary
b) print name ,round value of salary and pf (square root of sal upto 2 decimal) from
salary table in decreasing order of salary
EVALUATION:
Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)
❖ Join: A join is used when a SQL query requires data from more than
one table on database.
There are two main types of join conditions: -
● Equi-join
● Non-equi join
❖ Equi-join: The relationship between two tables is equi join when any one column
corresponds to the same column in other table e.g. deptno in EMP table as well as
in DEPT table. Here relationship is obtained using “=” operator.
❖ Non Equi-join: The relationship between two tables is non equi join when no
column in one table corresponds directly to a column in other table. Here
relationship is obtained other than “=” operator
❖ Self Joins:
A self join is a join of a table to itself. This table appears twice in the FROM clause
and is followed by table aliases that qualify column names in the join
condition. To perform a self join, Oracle combines and returns rows of the
table that satisfy the join condition.
❖ Inner Joins:
An inner join (sometimes called a "simple join") is a join of two or more tables
that returns only those rows that satisfy the join condition.
SYNTAX: SELECT*FROM <TABLE NAME> INNER JOIN <TABLE
NAME 2> USING (join_predicate);
SELECT * FROM T1 INNER JOIN T2 ON join_predicate;
EXAMPLE: SELECT *FROM orders INNER JOIN order_items USING
(order_id )
SELECT * FROM orders INNER JOIN order_items ON
order_items.order_id = orders.order_id
❖ Cross Joins:
If two tables in a join query have no join condition, Oracle returns their
Cartesian product. Oracle combines each row of one table with each row of the
other. A Cartesian product always generates many rows and is rarely useful.
For example, the Cartesian product of two tables, each with 100 rows, has
10,000 rows. Always include a join condition unless you specifically need a
Cartesian product.
SYNTAX: SELECT * FROM table1 CROSS JOIN table2;
EXAMPLE:
SELECTfoods.item_name,foods.item_unit,company.company_name,compa
n y.company_city FROM foods CROSS JOIN company;
Outer Joins:
An outer join extends the result of a simple join. An outer join returns all rows
that satisfy the join condition and also returns some or all of those rows from
one table for which no rows from the other satisfy the join condition.
● To write a query that performs an outer join of tables A and B and returns
all rows from A (a left outer join), use the LEFT [OUTER] JOIN syntax in
the FROM clause, or apply the outer join operator (+) to all columns of B
in the join condition in the WHERE clause. For all rows in A that have no
matching rows in B, Oracle returns null for any select list expressions
containing columns of B.
● To write a query that performs an outer join of tables A and B and returns
all rows from B (a right outer join), use the RIGHT [OUTER] JOIN syntax
in the FROM clause, or apply the outer join operator (+) to all columns of
A in the join condition in the WHERE clause. For all rows in B that have
no matching rows in A, Oracle returns null for any select list expressions
containing columns of A.
● To write a query that performs an outer join and returns all rows from A
and B, extended with nulls if they do not satisfy the join condition (a full
outer join), use the FULL [OUTER] JOIN syntax in the FROM clause.
EXCERCISE:
4. Write a SQL query to print the name of salesperson and customer who
belongs to same city.
5. Print order id,customer name where purchase amount exists between
500 and 1000.
6. print customer name ,salesman name,city ,commision using inner join
the salesperson(s) and the customer(s) he handle.
7. Write a SQL query to find those customers name who received a
commission from the company more than 13%.
8. Write a SQL query to find the details of an order like order number,
order date, amount of order, customer and salesman name
9. Write a SQL query to combine each row of salesman table with each
row of customer table.
10. Write a SQL statement to make a list in ascending order for the
salesmen who works either for one or more customer or not yet join
under any of the customers.
EVALUATION:
Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)
THEORY:
Constraints are classed as either:
1. Table constraints
These may reference one or more columns and are defined separately from
the definitions of the columns in the table.
2. Column constraints
These reference a single column and are defined within the specification
for the owning column.
Constraint types-
You may define the following constraint types-
1. Primary key
2. Foreign key
3. Unique
4. Null /Not null
5. Check
PRIMARY KEY
● The table in which the foreign key is defined is called a foreign table or Detail
table.
● The table that defines the primary or unique key and is referenced by the
foreign key is called the Primary table or Master table.
● The master table can be referenced in the foreign key definition by using
the REFERENCES adverb. If the name of the column is not specified, by
default, oracle references the primary key in master table.
FOREIGN KEY Constraint Defined at the Column Level:
UNIQUE
<ColumnName 2>)
CREATE TABLE
CUST_MSTR
(CUST_NO VARCHAR2(10) CHECK (CUST_NO LIKE ‘C%’),
FNAME VARCHAR2(20) CHECK (FNAME =
UPPER(FNAME)),
LNAME VARCHAR2(20) CHECK (LNAME = UPPER(LNAME)),
DOB DATE, PANCOPY VARCHAR2(1), PHOTOGRAPH VARCHAR2(25));
EXCERCISE:
1) Create the a table client_master with the following fields:
clientno, name, address, city, pincode, state, bal_due.
Consider the appropriate data type and size for the columns. In addition, define
clientno as the primary key column.
Consider the appropriate data type and size for the columns. In addition, define
Orderno as the primary key column and define its clientno column as a foreign key,
which references the client_master table & sno column as
a foreign key, which references the salesman_master table.
EVALUATION:
Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)
THEORY:
❖ ORDERBY
The ORDER BY keyword sorts the records in ascending order by default. To
sort the records in descending order, use the DESC keyword.
SYNTAX: SELECT column1, column2, ...FROM table_name ORDER BY
column1, column2, ... ASC|DESC;
❖ GROUP BY
The GROUP BY statement groups rows that have the same values into
summary rows, like "find the number of customers in each country".
❖ HAVING BY
The HAVING clause was added to SQL because the WHERE keyword
cannot be used with aggregate functions.
EXCERCISE:
EVALUATION:
Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)
THEORY:
Introduction of Index:
An index is an ordered list of the contents of a column, (or a group of columns) of a table.
Indexing involves forming a two dimensional matrix completely independent of the table
on which the index is being created. This two dimensional matrix will have a single
column, which will hold sorted data, extracted from the table column(s) on which the index
is created. Another column called the address field identifies the location of the record in
the oracle database.
Creation of an Index:
An index can be created on one or more columns. Based on the number of columns
included in the index, an index can be:
1. Simple Index
2. Composite Index
3. Unique Index
Creation of Index:
An index is created on a single column of a table is called a Simple Index. The syntax
for creating simple index that allows duplicate values is as described:
When a table, which has associated indexes, is dropped, the oracle engine automatically
drops all the associated indexes as well.
Introduction of View:
A VIEW is a virtual table in the database whose contents are defined by a query it can
represent.A view holds no data at all, until a specific call to the view is made. This reduces
redundant data on a HDD to a very large extent.
Creation of views:
Syntax: CREATE VIEW <ViewName> AS
SELECT <ColumnName1>, <ColumnName2>
FROM <TableName>
WHERE <ColumnName>=expression list
GROUP BY <Grouping Criteria>
HAVING <Predicate>;
Example: Create view on the emp table for the Department 10 which access for the
columns empno,ename,sal.
Answer: create view vw_emp10 as select empno,ename,sal from emp where deptno = 10;
Example: select * from vw_emp10 where sal < 35000 order by empno;
Introduction of Sequence:
Most application requires automatic generation of numeric value. Sequences are tools used
to generate a unique sequential number that can be used in the data tables. One of the best
features of sequences is that they guarantee that you will get a unique value when you
access the sequence. The value generated can have a maximum of 38 digits.
Creation of Sequence:
Syntax: CREATE SEQUENCE <SequenceName>
[INCREMENT BY <IntegerValue>
START WITH <IntegerValue>
MAXVALUE <IntegerValue> / NOMAXVALUE
MINVALUE <IntegerValue> / NOMINVALUE
CYCLE/ NOCYCLE
CACHE <IntegerValue>/ NOCACHE
ORDER / NOORDER]
Note:
Sequence is always given a name so that it can be referenced later when required. The
ORDER, NOORDER Clause has no significance, if Oracle is configured with Single server
option. It is useful only when you are using Parallel Server in Parallel mode option.
If the CACHE / NOCACHE clause is omitted oracle caches 20 sequence numbers by
default.
Example:
Create sequence order_seq, which will generate numbers from 1 to 9999 in ascending order
with an interval of 1. The sequence must restart from the number 1 after generating number
9999.
CREATE SEQUENCE order_seq INCREMENT BY 1 START WITH 1 MINVALUE
1 MAXVALUE 9999 CYCLE;
Referencing a Sequence: Once a sequence is created SQL can be used to view the
values held in its cache. To simply view sequence value use a select sentence as described
below.
SELECT <sequence_name>.NextVal FROM dual;
This will display the next value held in the cache on the VDU screen. Every time nextval
references a sequence its output is automatically incremented from the old value to the new
value ready for use. After creating a table you can add the data by using the INSERT
command like this:
INSERT INTO sales_order(o_no, o_date, c_no) VALUES (order_seq.nextval,
sysdate, ‘c0001’);
To references the current value of a sequence:
SELECT <sequence_name>.CurrVal FROM dual;
Introduction of Synonyms:
A synonym is an alternative name for objects such as tables, views, sequences, stored
procedures, and other database objects.
Now, users of other schemas can references the table EMP, which is now called
EMPLOYEES without having the prefix the table name with the schema named SCOTT.
For example, SELECT * FROM EMPPLOYEES;
EXPERIMENT NO: 10 DATE: / /
THEORY:
Database table:
1NF Example
2NF (Second Normal Form) Rules
● Rule 1- Be in 1NF
● Rule 2- Single Column Primary Key that does not functionally dependant on any
subset of candidate key relation
It is clear that we can’t move forward to make our simple database in 2 nd Normalization
form unless we partition the table above.
We have divided our 1NF table into two tables viz. Table 1 and Table2. Table 1 contains
member information. Table 2 contains information on movies rented.
We have introduced a new column called Membership_id which is the primary key for
table 1. Records can be uniquely identified in Table 1 using membership id.
Foreign Key references the primary key of another Table! It helps connect your Tables
● A foreign key can have a different name from its primary key
● It ensures rows in one table have corresponding rows in another
● Unlike the Primary key, they do not have to be unique. Most often they aren’t
● Foreign keys can be null even though primary keys can not
The above problem can be overcome by declaring membership id from Table2 as foreign
key of membership id from Table1
Now, if somebody tries to insert a value in the membership id field that does not exist in
the parent table, an error will be shown!
Consider the table 1. Changing the non-key column Full Name may change Salutation.
● Rule 1- Be in 2NF
● Rule 2- Has no transitive functional dependencies
To move our 2NF table into 3NF, we again need to again divide our table.
3NF Example
Below is a 3NF example in SQL database:
We have again divided our tables and created a new table which stores Salutations.
There are no transitive functional dependencies, and hence our table is in 3NF
Now our little example is at a level that cannot further be decomposed to attain higher
normal form types of normalization in DBMS. In fact, it is already in higher normalization
forms. Separate efforts for moving into next levels of normalizing data are normally needed
in complex databases. However, we will be discussing next levels of normalisation in
DBMS in brief in the following.
BCNF (Boyce-Codd Normal Form)
Even when a database is in 3rd Normal Form, still there would be anomalies resulted if it
has more than one Candidate Key.Sometimes is BCNF is also referred as 3.5 Normal
Form.