DBMS LAB MANUAL MGM
DBMS LAB MANUAL MGM
DBMS LAB MANUAL MGM
LAB MANUAL
____________________________________________
Program (UG/PG) : UG
Year : Third Year
Semester :V
Course Code : 20UCS508L
Course Title : Database management system Lab
Prepared By : Dr.D.S.Deshpande Ms.P.M.Ramgirwar
____________________________________________
2022-23
FOREWORD
It is my great pleasure to present this laboratory manual for Third year engineering
students for the subject of Computer networks.
As a student, many of you may be wondering with some of the questions in your mind
regarding the subject and exactly what has been tried is to answer through this manual.
As you may be aware that MGM has already been awarded with ISO 9001:2000
certifications and it is our duty to technically equip our students taking the advantage of
the procedural aspects of ISO 9001:2000 Certification.
Faculty members are also advised that covering these aspects in the initial stage itself will
greatly relieve them in future as much of the load will be taken care of by the enthusiasm
energies of the students once they are conceptually clear.
Dr. H. H. Shinde
Principal
LABORATORY MANUAL CONTENTS
This manual is intended for the Third year students of Computer Science and Engineering
in the subject of . This manual typically contains practical/Lab Sessions related Computer
Network covering various aspects related to the subject to enhanced understanding.
Students are advised to thoroughly go through this manual rather than only topics
mentioned in the syllabus as practical aspects are the key to understanding and
conceptual visualization of theoretical aspects covered in the books.
To develop computer engineers with necessary analytical ability and human values who can
creatively design, implement a wide spectrum of computer systems for welfare of the
society.
1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals, and
an engineering specialization to the solution of complex engineering problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and
engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the public
health and safety, and the cultural, societal, and environmental considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern engineering
and IT tools including prediction and modeling to complex engineering activities with an understanding of
the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering solutions in
societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in diverse
teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports and
design documentation, make effective presentations, and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the engineering and
management principles and apply these to one’s own work, as a member and leader in a team, to manage
projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
LIST OF EXPERIMENTS
1. Make an entry in the Log Book as soon as you enter the Laboratory.
2. All the students should sit according to their roll numbers starting from their left to right.
3. All the students are supposed to enter the terminal number in the log book.
5. All the students are expected to get at least the algorithm of the program/concept to be
implemented.
1. Submissions related to whatever lab work has been completed should be done during the next
lab session.
2. The immediate arrangements for printouts related to submission on the day of practical
assignments.
3. Students should be taught to take the printouts under the observation of the lab teacher.
Objective:
To understand the advantages of DBMS over file processing system.
To understand the procedure to install and manage application software
A] Installation of oracle
Oracle is the first company designed Relational database management system, known
as Oracle DB. It is the biggest vendors in the present IT market. It has an RDBMS database
that formally known as an Oracle database. Many IT companies access this database, it
supports multiple transaction processes and BI and analytical applications.
Oracle Database is the first database designed for enterprise grid computing, the most flexible
and cost effective way to manage information and applications. Enterprise grid computing
creates large pools of industry-standard, modular storage and servers. With this architecture,
each new system can be rapidly provisioned from the pool of components. There is no need for
peak workloads, because capacity can be easily added or reallocated from the resource pools as
needed.
The database has logical structures and physical structures. Because the physical and logical
structures are separate, the physical storage of data can be managed without affecting the
access to logical storage structures.
First commercially
Oracle v2 2.3 1979 available SQL-based
RDBMS
Concurrency control,
Oracle v3 3.1.3 1983 data distribution,
and scalability
Multiversion read
Oracle v4 4.1.4.0 1984 4.1.4.4 consistency. First
version available
for MS-DOS.[9][10]
Row-level locking,
scalability, online
backup and
Oracle v6 6.0.17 1988 6.0.37 recovery, PL/SQL. First
version available
for Novell Netware
386.[12]
Oracle 6.2 6.2.0 Oracle Parallel Server
PL/SQL stored
procedures, Triggers,
Oracle7 7.0.12 June 1992 Distributed 2-phase
commit, Shared Cursors,
Cost Based Optimizer
Shared Server, XA
Oracle 7.2 7.2.0 May 1995 Transactions,
Transparent Application
Failover
Recovery Manager,
Oracle8 8.0.3 June 1997 8.0.6 Partitioning. First
Database version[13]
available for
Linux.
Advanced
Oracle9iDatabas 9.2.0.1 2002 9.2.0.8 April Queuing, Data Mining,
e Release 2 2007 Streams, Logical
Standby
Automated Database
Management, Automatic
Oracle Database February Database Diagnostic
10g Release 1 10.1.0.2 2003 10.1.0.5 2006 Monitor, Grid
infrastructure, Oracle
ASM, Flashback
Database
Real Application
Testing, Database Vault,
Oracle Database July April Online Indexing,
10g Release 2 10.2.0.1 2005 10.2.0.5 2010 Advanced Compression,
[14] Data Guard Fast-Start
Failover, Transparent
Data Encryption
Edition Based
Redefinition, Data
September Redaction, Hybrid
Oracle Database 11.2.0.1 2009 [15] 11.2.0.4 August Columnar Compression,
11g Release 2 2013 Cluster File System,
Golden Gate
Replication, Database
Appliance
Multitenant architecture,
Oracle Database July In-Memory Column
12c Release 1 12.1.0.1 2013 12.1.0.2 July 2014 Store, Native JSON,
[16] SQL Pattern Matching,
Database Cloud Service
February
2018
(cloud:
18.1.0 [citati [cita Polymorphic Table
Oracle Database o 18.1.0)
tio Functions, Active
18c n needed] n needed] Directory Integration
July 2018
(on-prem:
18.3.0)[cita
tio
n needed]
February
2019
(Exadata)
Active Data Guard DML
April 2019 Redirection, Automatic
(Linux and Index Creation, Real-
Oracle 19.0.0 other Time Statistics
Database 19c platforms) Maintenance, SQL
June 2019 Queries on Object
(cloud) Stores, In-Memory for
IoT Data Streams, and
August many more.
2019 (most
recent patch
set)[17]
To install the Oracle software, you must use the Oracle Universal installer.
1. For this installation you need either the DVDs or a downloaded version of the DVDs. In this
tutorial, you install from the downloaded version. From the directory where the DVD files were
unzipped, double-
click setup.exe.
11. Unlock SH, OE and HR users by clicking on the check mark in the Lock Account? column.
Enter the same name as the user in the New Password and Confirm Password fields. For
example, to
unlock SH user, enter SH in the New Password and Confirm Password fields. Then, click OK.
1. When you click exit from the previous section, a browser opens and the Database Control URL is
already launched. If this does not happen, open a browser and enter the following URL:
http://<hostname>:1158/em
Enter system as the User Name and oracle as the Password and click Login.
2. The Licensing window appears. Scroll to the bottom and click I agree.
3. The Database Control Home Page appears. Your Installation was successful.
Function Description
Mode Description
Closing a File
The fclose()function is used to close an already opened file.
General Syntax :
int fclose( FILE
*fp);
Here fclose() function closes the file and returns zero on success, or EOF if there is an error
in closing the file. This EOF is a constant defined in the header file stdio.h.
*************************************
Experiment No: 1
Objective:
To understand the structure of logical schema based on the system requirements.
To design and develop physical scheme using modern tools.
Theory/Description:
A database schema is a collection of metadata that describes the relationships between objects
and information in a database. It’s a structure that holds tables, stored procedures, views, and
related data assets. A schema defines the infrastructure of this box. Schema is a structural
definition or description of an entire database. Once you declare the schema of a database, it
should not be changed frequently as it will disturb the organization of data in a database.
Schema of a database can be displayed in the form of a diagram called schema diagram. The
schema diagram displays what tables’ do a database contains, what are variables in those
tables. How the tables are associated with each other. Though the schema diagram does not
show each and every aspect of the database like, it does not show instances of the database,
type of the attributes.
A relational database schema helps you to organize and understand the structure of a database.
This is particularly useful when designing a new database, modifying an existing database to
support more functionality, or building integration between databases.
The process of doing database design generally consists of a number of steps which will be
carried out by the database designer. Usually, the designer must:
Determine the data to be stored in the database.
Determine the relationships between the different data elements.
Superimpose a logical structure upon the data on the basis of these relationships.
The structure of a relational database will inevitably change over time as data needs change. A
database schema is the blueprints of your database, it represents the description of a database
structure, data types, and the constraints on the database. At its most basic level, the schema
serves as a container for data assets. And designing database schemas is one of the very first
and important steps to start developing any software/website.
There are two steps to creating a relational database schema: creating the logical schema and
creating the physical schema.The logical schema depicts the structure of the
database, showing the tables, columns and relationships with other tables in the database and can be
created with modeling tools or spreadsheet and drawing software. The physical schema is created by
actually generating the tables, columns and relationships in the relational database management
software (RDBMS).
1. Design a schema logically based on business requirements. This can be defined as building
a logical model. This design step will play an important part in how the database is
developed. These requirements can translate into useful information that programmers can
utilize during the physical design of the database. Part of this process is also defining a set
of rules, called constraints. These constraints define how the data in the various tables relate
to each other.
2. Define the physical layout of the database. The physical schema defines the location of: data
files, logs, controls and other related objects. The schema adds logic and clarity to the
environment by clearly defining all of its attributes.
3. Define the security for the schema. Schema based security, bases itself on the user of the
schema and determines the tables to which a given user, or given security level, have
access.
4. Define and use the appropriate naming conventions. Understanding your data and the
attributes surrounding each element is important. Each element of data will need to be
considered as you are building out your scope. A successful build will avoid using
collations, reserved words, or data types that will hinder development and query
performance. Whether you are building based on existing data, or planning for additional
data, this step is vital.
Design a database schema model for Online Job Portal, where both employers and job
seekers expect the following functionalities from an online job site:
People can register as job seekers, build their profiles, and look for jobs matching
their skill sets.
Users can upload their existing resumes. If they do not have one, they should be able to
fill out a form and have a resume built for them.
People can apply directly to posted jobs.
Companies can register, post jobs, and search job seeker profiles.
Multiple representatives from a company should be able to register and post jobs.
Company representatives can view a list of job applicants and can contact them,
initiative an interview, or perform some other action related to their post.
Registered users should be able to search for jobs and filter the results based on
location, required skills, salary, experience level, etc.
Building the Data Model
After considering the above requirements, I came up with three broad functional categories:
Managing Users – How the portal manages users, i.e. job seekers, HR personnel, and
independent or consulting recruiters. (For the purpose of this model, individual HR
representatives and independent or consulting recruiters are treated as companies, at
least in terms of how they use the portal.)
Building Profiles – How the portal allows job seekers and organizations to create
profiles and resumes.
Posting and Looking Up Jobs – How the portal facilitates the process of posting,
searching, and applying for jobs.
****************************
Experiment No: 2
Title: Creation of database and writing SQL queries to implement database language command to
create, access, manipulate and to set integrity constraint on the database.
Objective:
To understand the different issues involved in the design and implementation of a database
system
To understand and use data definition language to write query for a database
DATA TYPES:
1. CHAR (Size): This data type is used to store character strings values of fixed length. The
size in brackets determines the number of characters the cell can hold. The maximum
number of character is 255 characters.
2. VARCHAR (Size) / VARCHAR2 (Size): This data type is used to store variable length
alphanumeric data. The maximum character can hold is 2000 character.
3. NUMBER (P, S): The NUMBER data type is used to store number (fixed or floating
point). Number of virtually any magnitude may be stored up to 38 digits of precision.124
Number as large as 9.99 * 10. The precision (p) determines the number of places to
the right of the decimal. If scale is omitted then the default is zero. If precision is
omitted, values are stored with their original precision up to the maximum of 38 digits.
4. DATE: This data type is used to represent date and time. The standard format is DD-
MM-YY as in 17-SEP-2009. To enter dates other than the standard format, use the
appropriate functions. Date time stores date in the 24-Hours format. By default the time in
a date field is 12:00:00 am, if no time portion is specified. The default date for a date field
is the first day the current month.
5. LONG: This data type is used to store variable length character strings containing up to
2GB. Long data can be used to store arrays of binary data in ASCII format. LONG values
cannot be indexed, and the normal character functions such as SUBSTR cannot be applied.
6. RAW: The RAW data type is used to store binary data, such as digitized picture or
image. Data loaded into columns of these data types are stored without any further
conversion. RAW data type can have a maximum length of 255 bytes. LONG RAW data
type can contain up to 2GB
Clauses, which are in some cases optional, constituent components of statements and
queries.
Expressions, which can produce either scalar values or tables consisting of columns and
rows of data.
Predicates which specify conditions that can be evaluated to SQL three-valued logic
(3VL) Boolean truth values and which are used to limit the effects of statements and
queries, or to change program flow.
Queries which retrieve data based on specific criteria.
Statements which may have a persistent effect on schemas and data, or which may
control transactions, program flow, connections, sessions, or diagnostics.
SQL statements also include the semicolon (";") statement terminator. Though not
required on every platform, it is defined as a standard part of the SQL grammar.
Insignificant white space is generally ignored in SQL statements and queries, making it
easier to format SQL code for readability.
There are five types of SQL statements. They are:
1. CREATE:
(a)CREATE TABLE: This is used to create a new relation (table)
Example:
SQL> CREATE TABLE Student (sno NUMBER (3), sname CHAR (10), class CHAR (5));
2. ALTER:
(a) ALTER TABLE ...ADD...: This is used to add some extra fields into existing
relation.
Syntax: ALTER TABLE relation_name ADD (new field_1 data_type(size), new field_2
data_type(size),..);
Example: SQL>ALTER TABLE std ADD (Address CHAR(10));
(b) ALTER TABLE...MODIFY...: This is used to change the width as well as data
type of fields of existing relations.
3. DROP TABLE: This is used to delete the structure of a relation. It permanently deletes the
records in the table.
Syntax: DROP TABLE relation_name;
Example: SQL>DROP TABLE std;
3. DELETE-FROM: This is used to delete all the records of a relation but it will retain the
structure of that relation.
5. TRUNCATE: This command will remove the data permanently. But structure will not be
removed.
DEPTNO DNAME
10 ACCOUNTING
20 RESEARCH
30 SALES
3. SELECT - FROM -WHERE: This query is used to display a selected set of fields for a
selected set of records of a relation.
Syntax: SELECT a set of fields FROM relation_name WHERE condition;
Objective:
To understand and implement various types of function in SQL.
Theory:
Aggregate Function: In addition to simply retrieving data, we often want to perform some
computation or summarization. SQL allows the use of arithmetic expressions. We now
consider a powerful class of constructs for computing aggregate values such as MIN and SUM.
1. Count: COUNT following by a column name returns the count of tuple in that column. If
DISTINCT keyword is used then it will return only the count of unique tuple in the column.
Otherwise, it will return count of all the tuples (including duplicates) count (*) indicates all the
tuples of the column.
Syntax: COUNT (Column name)
Example: SELECT COUNT (Sal) FROM emp;
2. SUM: SUM followed by a column name returns the sum of all the values in that column.
Syntax: SUM (Column name)
Example: SELECT SUM (Sal) From emp;
3. AVG: AVG followed by a column name returns the average value of that column values.
Syntax: AVG (n1, n2...)
Example: Select AVG (10, 15, 30) FROM DUAL;
4. MAX: MAX followed by a column name returns the maximum value of that column.
Syntax: MAX (Column name)
Example: SELECT MAX (Sal) FROM emp;
SQL> select deptno, max(sal) from emp group by deptno;
DEPTNO MAX (SAL)
SQL> select deptno, max (sal) from emp group by deptno having max(sal)<3000; DEPTNO
MAX(SAL)
302850
5. MIN: MIN followed by column name returns the minimum value of that column.
Syntax: MIN (Column name)
Example: SELECT MIN (Sal) FROM emp;
101300
CHARACTER FUNCTION:
CONVERSION FUNCTIONS:
To_char: TO_CHAR (number) converts n to a value of VARCHAR2 data type, using the
optional number format fmt. The value n can be of type NUMBER, BINARY_FLOAT, or
BINARY_DOUBLE.
SQL>select to_char(65,'RN')from dual;
LXV
To_number : TO_NUMBER converts expr to a value of NUMBER data type.
SQL>Select to_number ('1234.64') from Dual;
1234.64
To_date: TO_DATE converts char of CHAR, VARCHAR2, NCHAR, or
NVARCHAR2 data type to a value of DATE data type.
SQL>SELECT TO_DATE('January 15, 1989, 11:00 A.M.')FROM DUAL;
TO_DATE
---------
15-JAN-89
DATE FUNCTIONS:
1) Sysdate:
SQL>SELECT SYSDATE FROM DUAL;
29-DEC-08
2) next_day:
SQL>SELECT NEXT_DAY(SYSDATE,’WED’)FROM DUAL;
05-JAN-09
3) add_months:
SQL>SELECT ADD_MONTHS(SYSDATE,2)FROM DUAL;
28-FEB-09
4) last_day:
SQL>SELECT LAST_DAY(SYSDATE)FROM DUAL;
31-DEC-08
5) months_between:
SQL>SELECT MONTHS_BETWEEN(SYSDATE,HIREDATE)FROM EMP;
4
6) Least:
SQL>SELECT LEAST('10-JAN-07','12-OCT-07')FROM DUAL;
10-JAN-07
7) Greatest:
SQL>SELECT GREATEST('10-JAN-07','12-OCT-07')FROM DUAL;
10-JAN-07
8) Trunc:
SQL>SELECT TRUNC(SYSDATE,'DAY')FROM DUAL;
28-DEC-08
Round
SQL>SELECT ROUND(SYSDATE,'DAY')FROM DUAL;
28-DEC-08
to_char:
SQL> select to_char(sysdate, "dd\mm\yy") from dual;
24-mar-05.
to_date:
SQL> select to date (sysdate, "dd\mm\yy") from dual;
24-mar-o5.
LAB PRACTICE ASSIGNMENT:
**************************************
Experiment No: 4
Theory:
ARIHMETIC OPERATORS:
LOGICAL OPERATORS:
AND : The AND operator allows the existence of multiple conditions in an SQL statement's
WHERE clause.
OR: The OR operator is used to combine multiple conditions in an SQL statement's WHERE
clause.
24
NOT: The NOT operator reverses the meaning of the logical operator with which it is used.
Eg: NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate operator.
COMPARISION OPERATORS:
(=):Checks if the values of two operands are equal or not, if yes then condition becomes true.
(!=):Checks if the values of two operands are equal or not, if values are not equal then
condition becomes true.
(< >):Checks if the values of two operands are equal or not, if values are not equal then
condition becomes true.
(>):Checks if the value of left operand is greater than the value of right operand, if yes then
condition becomes true
(<):Checks if the value of left operand is less than the value of right operand, if yes then
condition becomes true.
(>=):Checks if the value of left operand is greater than or equal to the value of right operand,
if yes then condition becomes true.
(<=):Checks if the value of left operand is less than or equal to the value of right operand, if
yes then condition becomes true.
SPECIAL OPERATOR:
BETWEEN: The BETWEEN operator is used to search for values that are within a set of
values, given the minimum value and the maximum value.
IS NULL: The NULL operator is used to compare a value with a NULL attribute value.
ALL: The ALL operator is used to compare a value to all values in another value set
ANY: The ANY operator is used to compare a value to any applicable value in the list
according to the condition.
LIKE: The LIKE operator is used to compare a value to similar values using wildcard
operators.It allows to use percent sign(%) and underscore ( _ ) to match a given string pattern.
IN: The IN operator is used to compare a value to a list of literal values that have been
specified.
EXIST: The EXISTS operator is used to search for the presence of a row in a specified table
that meets certain criteria.
SET OPERATORS:
The Set operator combines the result of 2 queries into a single result. The following
are the operators:
Union
Union all
Intersect
Minus
Union all: Returns all rows selected by either query including the duplicates.
Minus: Returns all distinct rows selected by the first query and are not by the second
LAB PRACTICE ASSIGNMENT:
1. Display all the dept numbers available with the dept and emp tables avoiding duplicates.
2. Display all the dept numbers available with the dept and emp tables.
3. Display all the dept numbers available in emp and not in dept tables and vice versa.
*********************************
****************************88
paExperiment No: 5
Title: Implementation of types of Join.
Inner Join
Outer Join
Right Join
Left Join
Self Join
Natural Join
Equip Join
Objective:
Theory :
Syntax:
SELECT column 1, column 2,
column 3...
FROM table_name1, table_name2
WHERE table_name1.column name
= table_name2.columnname;
Types of Joins :
1. Simple Join
2. Self Join
3. Outer Join
Simple Join:
It is the most common type of join. It retrieves the rows from 2 tables having a common
column and is further classified into.
Equi-join :
Example:
Non Equi-join:
It specifies the relationship between columns belonging to different tables by making use
of relational operators other than’=’.
Example:
Table Aliases
Table aliases are used to make multiple table queries shorted and more readable. We give
an alias name to the table in the ‘from’ clause and use it instead of the name throughout
the query.
Self join:
Joining of a table to itself is known as self-join. It joins one row in a table to another. It
can compare each row of the table to itself and also with other rows of the same table.
Example:
Outer Join:
It extends the result of a simple join. An outer join returns all the rows returned by simple
join as well as those rows from one table that do not match any row from the table. The
symbol(+) represents outer join.
– Left outer join
– Right outer join
– Full outer join
1. Find all information of sailors who have reserved boat number 101.
2. Find the name of boat reserved by Bob.
3. Find the names of sailors who have reserved a red boat, and list in the order of age.
4. Find the names of sailors who have reserved at least one boat.
5. Find the ids and names of sailors who have reserved two different boats on the same day.
6. Find the ids of sailors who have reserved a red boat or a green boat.
7. Find the name and the age of the youngest sailor.
8. Count the number of different sailor names.
9. Find the average age of sailors for each rating level.
10. Find the average age of sailors for each rating level that has at least two sailors.
**********************************
Experiment No: 6
Objective:
Theory:
GROUP BY: This query is used to group to all the records in a relation together for each
and every value of a specific key(s) and then display them for a selected set of fields the
relation.
GROUP BY-HAVING : The HAVING clause was added to SQL because the WHERE
keyword could not be used with aggregate functions. The HAVING clause must follow the
GROUP BY clause in a query and must also precede the ORDER BY clause if used.
ORDER BY: This query is used to display a selected set of fields from a relation in an
ordered manner base on some field.
Syntax: SELECT <set of fields> FROM <relation_name>
ORDER BY <field_name>;
Example: SQL> SELECT empno, ename, job FROM emp ORDER BY job;
JOIN using ORDER BY: This query is used to display a set of fields from two relations by
matching a common field in them in an ordered manner based on some fields.
Syntax: SELECT <set of fields (from both relations)> FROM relation_1, relation_2
WHERE relation_1.field_x = relation_2.field_y ORDER BY field_z;
Example: SQL> SELECT empno,ename,job,dname FROM emp,dept
WHERE emp.deptno = 20 ORDER BY job;
Syntax:
Example:
Objective:
Theory:
SUBQUERIES: The query within another is known as a sub query. A statement containing sub query
is called parent statement. The rows returned by sub query are used by the parent statement or in other
words A subquery is a SELECT statement that is embedded in a clause of another SELECT statement
You can place the subquery in a number of SQL clauses:
WHERE clause
HAVING clause
FROM clause
OPERATORS( IN.ANY,ALL,<,>,>=,<= etc..)
Types
1. Sub queries that return several values Sub queries can also return more than one value. Such results
should be made use along with the operators in and any.
2. Multiple queries Here more than one sub query is used. These multiple sub queries are combined by
means of ‘and’ & ‘or’ keywords.
3. Correlated sub query A sub query is evaluated once for the entire parent statement whereas a
correlated Sub query is evaluated once per row processed by the parent statement.
VIEW:
In SQL, a view is a virtual table based on the result-set of an SQL statement.A view contains
rows and columns, just like a real table. The fields in a view are fields from one or more real
tables in the database.You can add SQL functions, WHERE, and JOIN statements to a view
and present the data as
if the data were coming from one single table. A view is a virtual table, which consists of a set
of columns from one or more tables. It is similar to a table but it does not store in the
database. View is a query stored as an object.
Example:
DROPPING A VIEW: A view can deleted with the DROP VIEW command.
Syntax: DROP VIEW <view_name> ;
1. Find all information of sailors who have reserved boat number 101.
2. Find the name of boat reserved by Bob.
3. Find the names of sailors who have reserved a red boat, and list in the order of age.
4. Find the names of sailors who have reserved at least one boat.
5. Find the ids and names of sailors who have reserved two different boats on the same day.
6. Find the ids of sailors who have reserved a red boat or a green boat.
7. Find the name and the age of the youngest sailor.
8. Count the number of different sailor names.
9. Find the average age of sailors for each rating level.
10. Find the average age of sailors for each rating level that has at least two sailors.
**********************************
Experiment: 8
Title: Study and implementation of
Objective:
Theory:
A transaction is a logical unit of work. All changes made to the database can be referred to as a
transaction Transaction changes can be made permanent to the database only if they are committed a
transaction begins with an executable SQL statement & ends explicitly with either rollback or commit
statement.
1. COMMIT: This command is used to end a transaction only with the help of the commit
command transaction changes can be made permanent to the database.
2. SAVE POINT: Save points are like marks to divide a very lengthy transaction to smaller
once. They are used to identify a point in a transaction to which we can latter role back. Thus, save
point is
used in conjunction with role back.
3. ROLLBACK: A role back command is used to undo the current transactions. We can role
back the entire transaction so that all changes made by SQL statements are undo (or) role back a
transaction to a save point so that the SQL statements after the save point are role back.
Syntax:
****************************
Experiment: 9
Objective:
Theory:
TABLESPACE:]
The oracle database consists of one or more logical storage units called tablespaces. Each table space
in an Oracle database consists of one or more files called datafiles, which are physical structures that
confirm to the operating system in which Oracle is running.
Syntax:
CREATE USER:
Syntax:
SQL> CREATE USER < username> -- (name of user to be created )
IDENTIFIED BY <password> -- (specifies that the user must
login with this password)
SQL> user create
System Privileges
Object Privileges
System Privileges : are those through which the user can manage the performance of database
actions. It is normally granted by DBA to users.
Object Privileges : allow access to objects or privileges on object, i.e. tables, table columns.
tables,views etc..It includes alter,delete,insert,select update etc.
(After creating the user, DBA grant specific system privileges to user)
GRANT:
The DBA uses the GRANT statement to allocate system privileges to other user.
Syntax:
SQL> GRANT privilege [privilege.... ... ]
TO USER ;
SQL> Grant succeeded
TO user;
SQL>GRANT select, insert ON emp TO James;
SQL>GRANT select ,update (e_name,e_address)
ON emp TO James;
CHANGE PASSWORD:
The DBA creates an account and initializes a password for every user.You can change
password by using ALTER USER statement.
Syntax:
Alter USER <some user name>
IDENTIFIED BY<New password>
REVOKE statement is used to remove privileges granted to other users.The privileges you specify are
revoked from the users.
Syntax:
REVOKE [privilege.. ...]
ON object
FROM user
Eg:
REVOKE create session,create table from James;
REVOKE select ,insert
ON emp
FROM James
ROLE:
A role is a named group of related privileges that can be granted to user.In other words, role is a
predefined collection of previleges that are grouped together,thus privileges are easier to assign user.
SQL> Create role custom;
SQL> Grant create table, create view TO custom;
SQL> Grant select, insert ON emp TO custom;
1. Create user and implement the following commands on relation (Emp and Dept).
2. Develop a query to grant all privileges of employees table into departments table.
3. Develop a query to grant some privileges of employees table into departments table.
4. Develop a query to revoke all privileges of employees table from departments table.
5. Develop a query to revoke some privileges of employees table from departments table.
**********************
Experiment:10
Database Procedures:
Database Procedures (sometimes referred to as Stored Procedures or Procs) are subroutines that can
contain one or more SQL statements that perform a specific task. They can be used for data
validation, access control, or to reduce network traffic between clients and the DBMS servers.
Extensive and complex business logic can be embedded into the subroutine, thereby offering better
performance.
Database Procedures are similar to Database Functions. The major difference is the way in which
they are invoked - Database Functions can be used in the same way as for any other expression
within SQL statements, whereas Database Procedures must be invoked using the CALL or EXEC
statement, depending on the DBMS.
In Enterprise Architect, Database Procedures can be modeled in one of two ways:
END$$
CALL BUS_PRO
END$$
Triggers are the SQL codes that are automatically executed in response to certain events on a
particular table. These are used to maintain the integrity of the data. A trigger in SQL works similar to
a real-world trigger.
Create triggers: A trigger is a stored procedure in database which automatically invokes whenever a
special event in the database occurs. For example, a trigger can be invoked when a row is inserted
into a specified table or when certain table columns are being updated.
Syntax:
[before | after]
on [table_name]
[trigger_body]
Database Cursors:
Cursors In MySQL, a cursor allows row-by-row processing of the result sets. A cursor is used for the
result set and returned from a query. By using a cursor, you can iterate, or by step through the results
of a query and perform certain operations on each row. The cursor allows you to iterate through the
result set and then perform the additional processing only on the rows that require it. In a cursor
contains the data in a loop. Cursors may be different from SQL commands that operate on all the rows
in the returned by a query at one time. There are some steps we have to follow, given below :
Declare a cursor
Open a cursor statement
Fetch the cursor
Close the cursor
1 . Declaration of Cursor : To declare a cursor you must use the DECLARE statement. With the help of
the variables, conditions and handlers we need to declare a cursor before we can use it. first of all we
will give the cursor a name, this is how we will refer to it later in the procedure. We can have more
than one cursor in a single procedure so its necessary to give it a name that will in some way tell us
what its doing. We then need to specify the select statement we want to associate with the cursor. The
SQL statement can be any valid SQL statement and it is possible to use a dynamic where clause using
variable or parameters as we have seen previously.
2 . Open a cursor statement : For open a cursor we must use the open statement.If we want to fetch
rows from it you must open the cursor.
Syntax : OPEN cursor_name;
3 . Cursor fetch statement : When we have to retrieve the next row from the cursor and move the
cursor to next row then you need to fetch the cursor.
Synatx : FETCH cursor_name INTO var_name; If any row exists, then the above statement fetches
the next row and cursor pointer moves ahead to the next row.
4 . Cursor close statement : By this statement closed the open cursor.
Syntax: CLOSE_name; By this statement we can close the previously opened cursor. If it is not closed
explicitly then a cursor is closed at the end of compound statement in which that was declared.
LAB PRCTICE:
Create procedure p1(in_customer_id int) begin
declare v_id int;
declare v_name varchar(20); declare v_finished integer default 0;
declare c1 cursor for select sid,sname from students where sid=in_customer_id; declare
continue handler for NOT FOUND set v_finished=1;
open c1; std:LOOP
fetch c1 into v_id,v_name; if v_finished=1 then
leave std;
end if; select concat(v_id,v_name);
end LOOP std;
close c1; end;
Experiment: 12
Objective:
Installation of NoSQL and Execution.
To find how the various NoSQL databases perform compared to each other against various operations.
Theory:
NoSQL is a term used to describe a non-relational database. A NoSQL database does not use the traditional
table-based relational database management system (RDBMS). It’s often used in Big Data applications because
they can scale more easily and handle large amounts of data. They are often more scalable than relational
databases. These databases can also offer improved performance as they are designed to be distributed; they can
take advantage of parallel processing to speed up data access.
NoSQL databases can also be more flexible because they don’t have to adhere to the rigid table structure of an
RDBMS. However, NoSQL databases can be more difficult to query and less reliable than relational databases.
NoSQL databases are increasing in popularity as more and more organizations look to adopt them for their data
storage needs. There are many benefits that NoSQL databases can offer, including scalability, improved
performance, and easier management
Installation:
1. Choose a directory where the Oracle NoSQL Database package files (libraries, Javadoc, scripts, and so
forth) should reside. We recommend using the same directory path on all nodes in the installation. Use
different directories for the Oracle NoSQL Database package files (referred to as <KVHOME> in this
document) and the Oracle NoSQL Database data (referred to as KVROOT). Both
the <KVHOME> and KVROOT directories should be local to the node, and not on a Network File
System.
Note:
To make future software upgrades easier, adopt a convention for <KVHOME> that includes the release
number. Always use a <KVHOME> location such as /var/kv/kv-M.N.O, where M.N.O represent the
software release.major.minor numbers. You can achieve this easily by using unzip or untar on the
distribution into a common directory (/var/kv in this example).
2. Extract the contents of the Oracle NoSQL Database package (kv-M.N.O.zip or kv-M.N.O.tar.gz) to
create the <KVHOME> directory. For example, <KVHOME> is the kv-M.N.O/ directory created by
extracting the package). If <KVHOME> resides on a shared network directory (which we do not
recommend) you need only unpack it on one machine. If <KVHOME> is local to each machine, unpack
the package on each node.
3. Verify the installation using the following command on one of the nodes:
Copy11gR2.M.N.O (....)
Note:
Oracle NoSQL Database is a distributed system and the runtime needs to be installed on every node in
the cluster. While the entire contents of the Oracle NoSQL Database package do not need to be installed
on every node, the contents of the lib directory must be present. How this distribution is done is beyond
the scope of this manual.
Depending on your preferences and development environment, there are a few different ways to implement
NoSQL CRUD operations. In this case, MongoDB, a powerful NoSQL database is used to showcase the
implementation of CRUD Operations. Before implementing the CRUD operations, you first need to connect to
the MongoDB Server. For that, you need to open the Mongo Shell and connect it to a MongoDB database by
using the following command.
ssh admin@your_server_ip
Then you need to connect a MongoDB user with privileges to write and read data.
insertOne()
insertMany()
CODE:
db.monuments.insertOne(
"city": "Giza",
"country": "Egypt",
"gps": {
"lat": 29.976480,
You can use the insertmany() command when you want to insert multiple inputs. Use the following
command to insert multiple values in the Document.
CODE:
db.monuments.insertMany([ {"name": "The Valley of the Kings", "city": "Luxor", "country": "Egypt", "gps": {
"lat": 25.746424, "lng": 32.605309 }},
{"name": "Arc de Triomphe", "city": "Paris", "country": "France", "gps": { "lat": 48.873756, "lng": 2.294946
}},
{"name": "The Great Wall of China", "city": "Huairou", "country": "China", "gps": { "lat": 40.431908, "lng":
116.570374 }},
{"name": "The Eiffel Tower", "city": "Paris", "country": "France", "gps": { "lat": 48.858093, "lng": 2.294694
}},
{"name": "The Statue of Liberty", "city": "New York", "country": "USA", "gps": { "lat": 40.689247, "lng": -
74.044502 }}
you can query the database to retrieve the Document from the database and read its data.
find()
findOne()
You can use the following command to retrieve all the documents from a database:
db.monuments.find()
You can also give an objectId as an identifier to return only a specific document:
db.monuments.find({"country": "France"}).pretty()
The Update in NoSQL CRUD Operations can be implemented in MongoDB by updating the Documents
using the following two methods:
updateOne()
updateMany()
You can use it to update one or all Document(s) in the database. Use the following code to update Arc de
Triomphe to Arc de Triomphe de l’Étoile, it’s full name.
CODE:
db.monuments.updateOne(
{ "name": "Arc de Triomphe" },
{
$set: { "name": "Arc de Triomphe de l'Étoile" }
}
)
Similarly, updateMany() can be used to add more attributes to the Documents collection.
The Delete in the NoSQL CRUD Operations can be implemented by deleting records from a MongoDB
collection. The method to do this are as follows:
deleteOne()
deleteMany()
You can begin by removing the Arc de Triomphe de l’Étoile monument Document you modified
previously:
CODE:
db.monuments.deleteOne(
{ "name": "Arc de Triomphe de l'Étoile" }
)
CODE:
db.monuments.deleteMany(
{ "country": "France" }
****************************************