DBMS Lab-Manual Final
DBMS Lab-Manual Final
DBMS Lab-Manual Final
Laboratory Manual
Year: 2022-2023
Prepared By:
Dr. Ajay N. Upadhyaya,
Prof. Megha Joshi,
Prof. Sachi Bhavsar
INDEX
Page No.
Sr.No. Experiment Date Marks Signature
From To
Introduction of DBMS, SQL
1. and Oracle concepts and Create 3 5
a table.
How to insert data in a table
2. using insert command and 6 9
display the records in a table.
Update or Delete records of a
3. table and modifying structure 10 12
of a table using Alter and Drop
command.
Study of system defined
4. functions for manipulation of 13 16
data items in SQL.
Study of numeric/math function
5. and date functions for 17 19
manipulation of data items.
6. To perform join operation 20 23
between various tables.
7. Study and Implementation of 24 27
different types of constraints.
How to retrieve data from
8. different tables using sub 28 29
queries and correlated queries.
Understanding of Database
9. Objects: synonym, sequence, 30 33
index and view.
10. To study the concepts of 34 35
Normalization.
THEORY:
Introduction of Oracle:
The relational model, sponsored by IBM (in June 1970), then came too accepted
as the definitive model for RDBMS. The language developed by IBM to
manipulate the data stored within model (Dr. E.F.Codd model) was originally
called Structured English Query Language (SEQUEL) with the word English
later dropped in favor Structured Query Language (SQL).
In 1979 a company called Relational Software, Inc. 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:
The Oracle product is primarily divided into
Oracle Server tools: Oracle Server Product is either called Oracle Workgroup
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 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 needs.
Components of SQL:
1) DDL (Data Definition Language):
Is a language, which includes the commands, which are used dynamically to set
up, 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 database.
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 within 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.
EXCERCISE:
1) Create a table ‚emp‛ with the following fields:
EMPNO ENAME JOB HIREDATE SAL COMM DEPTNO
EVALUATION:
Problem
Understanding Timely Total
Analysis & Mock
Level Completion
Solution (2) (10)
(3) (2)
(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:
Creates a new raw (empty) in the database table.
Loads the values passed (by the SQL insert) into the columns specified.
Note: Character value (expression) placed within the INSERT INTO statement
must be enclosed in single quotes (‘).
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, and
eliminates rows that have exactly the same contents in each column.
EXERCISES:
EVALUATION:
Problem
Understanding Timely Total
Analysis & Mock
Level Completion
Solution (2) (10)
(3) (2)
(3)
THEORY:
Updating Rows: The UPDATE command is used to change or modify data values
in table.
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 Head Office.
UPDATE BRANCH_MSTR SET NAME = ‘Head Office’
WHERE NAME = ‘AMP (HO)’;
Delete Operations:
The DELETE command deletes rows from the table that satisfies the condition
provided by its WHERE clause, and returns the number of records deleted.
Example: Remove only the savings bank account details from the ACCT_DTLS
table.
DELETE FROM ACCT_DTLS WHERE ACCT_NO LIKE ‘SB%’;
Here the WHERE clause is optional. If you are not specify the WHERE clause
then 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.
Destroying Tables:
Sometimes tables within a particular database become obsolete and need to be
discarded. In such situation using DROP TABLE statement with the table name
can destroy a specific table. If a table is dropped all records held within it are lost
and cannot be recovered.
Syntax: DROP TABLE <TableName>;
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) Modify the job of employees to ‚programmer‛ whose job is ‚trainee‛.
3) Delete record whose location is ‚Baroda‛ from dept table.
4) Drop a table ‚stud_master‛.
5) Create a table ‚ManagerHist‛ from emp whose job is ‚Manager‛.
6) Copy all the information of ‚department‚ into the ‚ManagerHist‛ table.
EVALUATION:
Problem
Understanding Timely Total
Analysis & Mock
Level Completion
Solution (2) (10)
(3) (2)
(3)
THEORY:
Aggregate Function: These are system defined functions which deal with numbers
Sum(), AVG(), MAX(), MIN(), COUNT() etc. are some example
String Function: LTRIM(), RTRIM(), LEN(), LEFT(), RIGHT(), LOWER() etc. are
some of the example
Date Function: GETDATE(), DATEADD(), DAY(), MONTH(), YEAR() etc. are some
of the example
COUNT() function:
The COUNT() function returns the number of rows that matches a specified
criterion.
COUNT() Syntax:
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
AVG() function:
The AVG() function returns the average value of a numeric column.
AVG() Syntax:
SELECT AVG(column_name)
FROM table_name
WHERE condition;
SUM() function
The SUM() function returns the total sum of a numeric column.
SUM() Syntax:
SELECT SUM(column_name)
FROM table_name
WHERE condition;
MIN() Function:
The MIN() function returns the smallest value of the selected column.
MIN() Syntax:
SELECT MIN(column_name)
FROM table_name
WHERE condition;
MAX() function
The MAX() function returns the largest value of the selected column.
String functions:
String functions are used to perform an operation on input string and return an
output string.
Following are the string functions defined in SQL:
Date functions:
Date functions are generally used with date and time fields.
Advanced Functions:
1. CURRENT_USER(): It returns the user name and host name for the SQL
account used by the server to authenticate the current client.
2. IIF(): It returns a value if a condition is TRUE, or another value if a condition is
FALSE.
3. ISNULL() : It returns the specified value IF the expression is NULL, otherwise
return the expression.
4. CONVERT() : It converts a value (of any type) into a specified datatype.
5. CAST(): The CAST() function converts a value (of any type) into a specified
datatype.
1. From the above table, write a SQL query to find the minimum purchase amount.
2. Write a SQL query to count the number of orders.
3. Write a SQL query to find the highest purchase amount ordered by each
customer. Return customer ID, maximum purchase amount.
EVALUATION:
Problem
Understanding Timely Total
Analysis & Mock
Level Completion
Solution (2) (10)
(3) (2)
(3)
Number functions:
Number functions are described as follow:
Function Description
Takes up to three arguments, where x is either a date or a number, fmt is
a format string specifying the format that x will appear in, and nls
TO_CHAR(x[,
specifies language or location formatting string.
fmt[, nls]])
If x is a date, fmt is a date format code.
If x is a number, fmt is a numeric format code.
Converts string s to DATE datatype accordingly the format string fmt.
TO_DATE(s[,
fmt[, nls]])
The fmt string uses the same date format code. The default is the value
stored in the NLS_DATE_FORMAT session variable.
TO_NUMBER(s[, Returns the numeric value represented by the string s. The format string
fmt[, nls]]) fmt specifies the format the that s appears in.
EXCERCISE:
1) Write down the query that ‚Display each employee name with hire date, and salary
review date. Assume review date is after one year after hire date. Order the output in
ascending review date order‛.
2) Differentiate: ROUND and TRUNC functions.
3) The __________ function returns number of months between two dates.
4) The TO_DATE() function also disallows part insertion of a DATE value into a column.
(State True / False with justification.)
5) The __________ function converts a value of a DATE datatype to CHAR value. (State
True / False with justification.)
EVALUATION:
Problem
Understanding Timely Total
Analysis & Mock
Level Completion
Solution (2) (10)
(3) (2)
(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: EQUI JOIN creates a JOIN for equality or matching column(s) values of
the relative tables. EQUI JOIN also create JOIN by using JOIN with ON and then
providing the names of the columns with their relative tables to check equality using
equal sign (=).
Syntax :
SELECT column_list
FROM table1, table2....
WHERE table1.column_name = table2.column_name;
Example :
SELECT student.name, student.id, record.class, record.city
FROM student, record
WHERE student.city = record.city;
Non Equi-join: NON EQUI JOIN performs a JOIN using comparison operator
other than equal (=) sign like >, <, >=, <= with conditions.
Syntax :
SELECT *
FROM table_name1, table_name2
WHERE table_name1.column [> | < | >= | <= ]
table_name2.column;
SQL Join: This statement is used to combine data or rows from two or more
tables based on a common field between them. Different types of Joins are as
follows:
INNER JOIN
LEFT JOIN
RIGHT JOIN
FULL JOIN
Inner Joins:
This join returns all rows from multiple tables where the join condition is met.
Note: We can also write JOIN instead of INNER JOIN. JOIN is same as INNER
JOIN.
Syntax :
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column = table2.column;
Left Joins:
This join returns all the rows of the table on the left side of the join and matches
rows for the table on the right side of the join. LEFT JOIN is also known as
LEFT OUTER JOIN.
Syntax :
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;
Syntax :
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;
Full Joins:
FULL JOIN creates the result-set by combining results of both LEFT JOIN and
RIGHT JOIN. The result-set will contain all the rows from both tables. For the
rows for which there is no matching, the result-set will contain NULL values.
Syntax :
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;
EXCERCISE:
1) Define: Join. Explain self join.
2) Retrieve employee number, employee name and their department name, in department
name order.
3) Show all employee details who lives in Baroda.
4) Display the name, salary and department number of employees whose salary is more
than 10000.
5) List the employee name, job, and salary and department name for everyone in the
company except clerks. Sort on salary displaying the highest salary first.
6) List all employees by name and number along with their manager’s name and number.
7) Display all the employees who earn less than their managers.
8) Consider following tables Customers and Salesman.
EVALUATION:
Problem
Understanding Timely Total
Analysis & Mock
Level Completion
Solution (2) (10)
(3) (2)
(3)
THEORY:
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 constraint: A primary key is a one or more column(s) in a table used to
uniquely identify each row in the table. None of the fields that are part of the primary key
can contain a null value. A table can have only one primary key.
are derived from the primary key or unique key of some other table.
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
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
Unique constraint: The Unique column constraint permits multiple entries of NULL
into a column. These NULL values are clubbed at the top the column in order in which
they were entered into the table. This is the essential difference between the Primary Key
and Unique Constraints when applied to table column(s).
EVALUATION:
Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)
TITLE: How to retrieve data from different tables using sub queries and
correlated queries.
THEORY:
In SQL, a Subquery can be simply defined as a query within another query. In other words
we can say that a Subquery is a query that is embedded in WHERE clause of another SQL
query.
Types of Subqueries:
3. Correlated Subquery
Syntax:
There is not any general syntax for Subqueries. However, Subqueries are seen to
be used most frequently with SELECT statement as shown below:
SELECT column_name [, column_name ]
FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE])
Steps:
1. The inner queries must be enclosed in parentheses, and must be on the right hand
side of the condition.
4. Sub queries are always executed from the most deeply nested to the least deeply
nested, unless they are correlated queries.
5. Logical and SQL operators may not be used as well as ANY and ALL.
Correlated Query:
In Correlated Query, Outer query executes first and for every Outer query row Inner
query is executed. Hence, Inner query uses values from Outer query.
EXCERCISE:
1. Find the employees who earn the maximum salary for their department. Display the
result in ascending order of salary.
2. Find the most recently hired employees in each department. Order by hire date.
3. Find the employees who earn the highest salary in each job type. Sort in descending
salary order.
4. Show the following details for any employee who earns a salary less than the average
for their department.
ENAME SALARY DNAME JOB
5. Who are the top three earners in the company? Display their name and salary.
6. Display the empno, name, job and deptno for employees whose salary is greater than
the highest salary in any SALES department.
EVALUATION:
Problem
Understanding Timely Total
Analysis & Mock
Level Completion
Solution (2) (10)
(3) (2)
(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:
Simple Index
Composite Index
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:
Dropping Index:
Indexes associated with the tables can be removed by using the DROP INDEX
command.
Syntax: DROP INDEX <IndexName>;
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;
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.
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;
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.
EXCERCISE:
1) Create view on the emp table for the job ‚Clerk‛ which access for the columns empno,
ename, job, sal and rename the column empno as ‚empnumber‛. And access the data of
view.
2) Create a sequence ‚seq3‛ with the following parameters:
Increment by -1, cache 20, cycle, noorder and which will generate the numbers from 1 to
5000 in descending order.
3) Create a simple index on ‚orderid‛ column of a table ‘order’.
4) Create a synonym ‚employee‚ from the table emp.
EVALUATION:
Problem
Understanding Timely Total
Analysis & Mock
Level Completion
Solution (2) (10)
(3) (2)
(3)
THEORY:
WHAT IS NORMALIZATION?
‚Normalization is essentially the process of taking a wide table with lots of columns
but few rows and redesigning it as several narrow tables with fewer columns but
more rows.‛
A properly normalized design allows you to use storage space efficiently, eliminate
redundant data, reduce or eliminate inconsistent data, and ease the data
maintenance burden. Before looking at the forms of normalization, you need to
know one cardinal rule for normalizing a database:
‚You must be able to reconstruct the original flat view of the data.‛
Forms of normalization:
Relational database theorists have divided normalization into several rules called
normal forms.
First Normal Form: No repeating groups.
Second Normal Form: No nonkey attributes depend on a portion of the primary
key.
Third Normal Form: No attributes depend on other non-key attributes.
Boyce-Codd normal form (BCNF): Every non-trivial functional dependency in
the table is a dependency on a superkey.
Fourth Normal Form: Every non-trivial multivalued dependency in the table is a
dependency on a superkey.
EXCERCISE:
1) Normalize the following table upto third normal form:
Author Author
Collection or
Last First Book Title Subject Publisher Building
Library
Name Name
PCL General
Berdahl Robert Politics History Wiley B – Block
Stacks
Legal
Yudof Mark Child Abuse Person Law Library C – Block
Procedures
Greek
Graves Robert The Golden Fleece Wiley Classics Library D – Block
Literature
Library and
Charles Ammi Library Information
Miksa Francis Person B – Block
Cutter Biography Science
Collection
EVALUATION:
Problem
Understanding Timely Total
Analysis & Mock
Level Completion
Solution (2) (10)
(3) (2)
(3)
Write SQL statements for the following query from Employee table.
1. List the E_no, E_name, Salary of all employees working for MANAGER.
2. Display all the details of the employee whose salary is more than the Sal of any IT
PROFF.
3. List the employees in the ascending order of Designations of those joined after
1981.
4. List the employees along with their Experience and Daily Salary.
5. List the employees who are either ‘CLERK’ or ‘ANALYST’ .
6. List the employees who joined on 1-MAY-81, 3-DEC-81, 17-DEC-81,19-JAN-80 .
7. List the employees who are working for the Deptno 10 or20.
8. List the Enames those are starting with ‘S’ . 9. Dislay the name as well as the first
five characters of name(s) starting with ‘H’
1. Write a query to find the salary of a person where age is <= 26 and salary >= 25000 from
customer table.
Name Type
---------- ----------------------
EMPNO NUMBER (6)
ENAME VARCHAR2 (20)
JOB VARCHAR2 (10)
DEPTNO NUMBER (3)
SAL NUMBER (7,2)
1. Allow NULL for all columns except ename and job.
2. Add constraints to check, while entering the empno value (i.e) empno > 100.
3. Define the field DEPTNO as unique.
4. Create a primary key constraint for the table(EMPNO).
5. Write queries to implement and practice constraints.