DBMS LAB MANUAL MGM

Download as pdf or txt
Download as pdf or txt
You are on page 1of 59

MGM’s

Jawaharlal Nehru Engineering College Aurangabad

MGM University, Aurangabad

Department of Computer Science & Engineering

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

____________________________________________

Department of Computer Science & Engineering

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.

Good Luck for your Enjoyable Laboratory Sessions

Dr.Vijaya Musande Dr.D.S.Deshpande


Ms.P.M.Ramgirwar
HOD, CSE Asst. Prof., CSE Dept.
MGM’s

Jawaharlal Nehru Engineering College, Aurangabad


Department of Computer Science and Engineering

Vision of CSE Department:

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.

Mission of the CSE Department:

I. Preparing graduates to work on multidisciplinary platforms associated with


their professional positions both independently and in a team environment.
II. Preparing graduates for higher education and research in Computer Science
And Engineering enabling them to develop systems for society development.

Programme Educational Objectives: Graduates will be able to

I. To analyze, design and provide optimal solution for Computer Science


and Engineering and multidisciplinary problems.

II. To pursue higher studies and research by applying knowledge of mathematics


and fundamentals of computer science.

II. To exhibit professionalism, communication skills and adapt to current trends


by engaging in lifelong learning.
Programme Outcomes (POs): Engineering Graduates will be able to:

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

Course Code: 20UCS508L

Course Title: Database Management Ssytem lab

Sr. No Name of the experiment Page No.

1 Defining Schema for application.


-Designing a form using schema designer tool to understand schema
relationship.

2 Creation of database and writing SQL queries to implement database


language command to create, access, manipulate and to set integrity
constraint on the database.

3 Implementation of different types of functions with suitable examples.


 Number function
 Aggregate function
 Character Function
 Conversion Function
 Data Function

4 Implementation of different types of operators in sql.


 Arithmetic operators
 Logical operators
 Comparison operator
 Special operator
 Set operator

5 Implementation of types of Join.


 Inner Join
 Outer Join
 Right Join
 Left Join
 Self-Join
 Natural Join
 Equip Join
6 Study and implementation of
 Group by &having Clause
 Order by clouse
 Indexing

7 Study and implementation of


 Sub Queries
 views

8 Study and implementation of


 Database Administrative commands for creating and managing
database users’
Backup &Recovery Commands.

9 Creating Database/ Table Space

10 Creation of procedures, trigger and cursor.

11 Assignment in Design and Implementation of Database systems or


packages for applications such as office automation, hotel management,
hospital management etc. and applies the concept of normalization (NF:
First, Second,Third And Boyce Codd Normal Forms.)

12 Study Of open source NoSQL Database (installation, Basic Operation


and Execution
LABORATORY OUTCOMES

The practical/exercises in this section are psychomotor domain Learning


Outcomes (i.e. subcomponents of the COs), to be developed and assessed to
lead to the attainment of the competency.

LO-1: Implement SQL commands to create, manipulate and query databases.


LO-2: Design and implement a database schema for a given problem domain.
LO-3: Design relational databases and apply proper techniques, such as
normalization.
LO-4:Use commercially available/ open source database management system
tools such as PL/SQL, NoSQL, Firebase etc.
DOs and DON’Ts in Laboratory:

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.

4. Do not change the terminal on which you are working.

5. All the students are expected to get at least the algorithm of the program/concept to be
implemented.

6. Strictly follow the instructions given by the teacher/Lab Instructor.

Instruction for Laboratory Teachers

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.

4. The promptness of submission should be encouraged by way of marking and evaluation

patterns that will benefit the sincere student.


. Pre-Requisite Experiment
Title: a) Installation of ORACLE b) Implement file management system in C

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 Architecture

An Oracle database is a collection of data treated as a unit. The purpose of a database is to


store and retrieve related information. A database server is the key to solving the problems of
information management. In general, a server reliably manages a large amount of data in a
multiuser environment so that many users can concurrently access the same data. All this is
accomplished while delivering high performance. A database server also prevents unauthorized
access and provides efficient solutions for failure recovery.

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.

Oracle Database Features

This section contains the following topics:

 Overview of Scalability and Performance Features


 Overview of Manageability Features
 Overview of Database Backup and Recovery Features
 Overview of High Availability Features
 Overview of Business Intelligence Features
 Overview of Content Management Features
 Overview of Security Features
 Overview of Data Integrity and Triggers
 Overview of Information Integration Features

Oracle Initial Initial Termina Terminal


Database Release Release l Marquee
Version Version Date Patchset Patchset Features
Version Date

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]

Support for client/server


5.0.22 computing and distribute
Oracle v5 (5.1.17) 1985 5.1.22 d database systems. First
version available
for OS/2.[11]

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

Oracle 7.1 7.1.0 May 1994 Parallel SQL Execution

Shared Server, XA
Oracle 7.2 7.2.0 May 1995 Transactions,
Transparent Application
Failover

Oracle 7.3 7.3.0 February 7.3.4 Object-relational


1996 database

Recovery Manager,
Oracle8 8.0.3 June 1997 8.0.6 Partitioning. First
Database version[13]
available for
Linux.

Oracle8iDatabas August Native internet protocols


e 8.1.5.0 1998 8.1.7.4 2000 and Java, Virtual Private
Database

Oracle9iDatabas Decembe Oracle Real Application


e 9.0.1.0 2001 9.0.1.5 r 2003 Clusters (RAC), Oracle
XML DB

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

Oracle Database 11.1.0.6 September 11.1.0.7 Septembe Active Data Guard,


11g Release 1 2007 r 2008 Secure Files, Exadata

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

September Native Sharding, Zero


Oracle Database 12.2.0.1 2016 Data Loss Recovery
12c Release 2 (cloud) Appliance, Exadata
Cloud Service, Cloud at
March 2017 Customer
(on-prem)

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]

Installing Oracle Database 10g on Windows

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.

2. The Oracle Universal Installer starts.


3. You will perform a basic installation with a starter database. Enter orcl for the Global Database
Name and oracle for the Database Password and Confirm Password. Then click Next.
. When the check successfully completes (with or without warnings), click Next.
5. If you received any warnings, you can proceed. Click Yes.
6. Review the Summary window to verify what is to be installed. Then, click Install.
7. The progress window appears.
8. The Configuration Assistants window appears.
9. Your database is now being created
10. When the database has been created, you can unlock the users you want to use. Click
Password Management.

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.

12. Click OK again.


13. Click Exit.
14. Click Yes to confirm exit.

Post Installation Tasks


For additional functionality within DB Control, functionality such as starting and stopping the
database, an operating system user must belong to the ORA_DBA group. An existing user can
be used or a new user can be created. This topic shows you how to create the operating system
user oracle and make the user part of the ORA_DBA group.
1. Click Start > Settings > Control Panel. Select Administrative
Tools.
2. Select Computer Management.
3. Select Local Users and Groups.
4. In the right hand panel, right click Users. Select New User .
5. In the New User window enter:
User name: oracle
Description: Oracle Administration User
Password: <a secure
password> Confirm: <a
secure password>
For this example the password oracle is used.
Deselect User must change password at next logon
Create.
Testing Your Installation
To test that your installation completed successfully, perform the following:

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.

B] Implement file management system in c


Theory:
A file represents a sequence of bytes on the disk where a group of related data is stored. File is
created for permanent storage of data. It is a ready made structure.
In C language, we use a structure pointer of file type to declare a file.
FILE
*fp;
C provides a number of functions that helps to perform basic file operations. Following are the
functions,

Function Description

fopen() create a new file or open a existing file

fclose() closes a file

getc() reads a character from a file

putc() writes a character to a file

fscanf() reads a set of data from a file

fprintf() writes a set of data to a file

getw() reads a integer from a file

putw() writes a integer to a file


fseek() set the position to desire point

ftell() gives current position in the file

rewind() set the position to the begining point

Opening a File or Creating a File


The fopen()function is used to create a new file or to open an existing file.
General Syntax:
*fp = FILE *fopen(const char *filename, const char
*mode);
Here, *fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or
created) file.
filename is the name of the file to be opened and mode specifies the purpose of opening the
file. Mode can be of following types,

Mode Description

R opens a text file in reading mode

W opens or create a text file in writing mode.

A opens a text file in append mode

r+ opens a text file in both reading and writing mode

w+ opens a text file in both reading and writing mode

a+ opens a text file in both reading and writing mode

Rb opens a binary file in reading mode

Wb opens or create a binary file in writing mode

Ab opens a binary file in append mode

rb+ opens a binary file in both reading and writing mode

wb+ opens a binary file in both reading and writing mode

ab+ opens a binary file in both reading and writing mode

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

Title: Defining Schema for application.


Designing a form using schema designer tool to understand schema relationship.

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).

Points to be consider while designing a schema:

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

SQL language is sub-divided into several language elements, including:

 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. DATA DEFINITION LANGUAGE (DDL)

2. DATA MANIPULATION LANGUAGE (DML)

3. TRANSATIONAL CONTROL LANGUAGE (TCL)

4.DATA CONTROL LANGUAGE (DCL)


1. DATA DEFINITION LANGUAGE (DDL): The Data Definition Language (DDL) is used
to create and destroy databases and database objects. These commands will primarily be used
by database administrators during the setup and removal phases of a database project. Let's
take a look at the structure and usage of four basic DDL commands:

1. CREATE 2. ALTER 3. DROP 4. RENAME

1. CREATE:
(a)CREATE TABLE: This is used to create a new relation (table)

Syntax: CREATE TABLE <relation_name/table_name >


(field_1 data_type(size),field_2 data_type(size), .. . );

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.

Syntax: ALTER TABLE relation_name MODIFY (field_1 newdata_type(Size), field_2


newdata_type(Size),... field_newdata_type(Size));
Example: SQL>ALTER TABLE student MODIFY(sname VARCHAR(10),class
VARCHAR(5));

c) ALTER TABLE..DROP...: This is used to remove any field of existing relations.

Syntax: ALTER TABLE relation_name DROP COLUMN (field_name);

Example: SQL>ALTER TABLE student DROP column (sname);

d) ALTER TABLE..RENAME...: This is used to change the name of fields in existing


relations.

Syntax: ALTER TABLE relation_name RENAME COLUMN (OLD field_name) to


(NEW field_name);

Example: SQL>ALTER TABLE student RENAME COLUMN sname to stu_name;

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;

4. RENAME: It is used to modify the name of the existing database object.


Syntax: RENAME TABLE old_relation_name TO new_relation_name;
Example: SQL>RENAME TABLE std TO std1;
2.DATA MANIPULATION LANGUAGE (DML): The Data Manipulation Language
(DML) is used to retrieve, insert and modify database information. These commands will be
used by all database users during the routine operation of the database. Let's take a brief look at
the basic DML commands:
1. INSERT 2. UPDATE 3. DELETE
1. INSERT INTO: This is used to add records into a relation. These are three type of
INSERT INTO queries which are as
a) Inserting a single record
Syntax: INSERT INTO < relation/table name> (field_1,field_2……field_n)VALUES
(data_1,data_2, ...... data_n);
Example: SQL>INSERT INTO student(sno, sname,class,address)VALUES
(1,‟Ravi‟,‟M.Tech‟,‟Palakol‟);
b) Inserting a single record
Syntax: INSERT INTO < relation/table name>VALUES (data_1,data_2,. . data_n);
Example: SQL>INSERT INTO student VALUES (1,‟Ravi‟,‟M.Tech‟,‟Palakol‟);

c) Inserting all records from another relation


Syntax: INSERT INTO relation_name_1 SELECT Field_1,field_2,field_n FROM
relation_name_2 WHERE field_x=data;
Example: SQL>INSERT INTO std SELECT sno,sname FROM student WHERE
name = „Ramu„;

d) Inserting multiple records


Syntax: INSERT INTO relation_name field_1,field_2, .... field_n) VALUES
(&data_1,&data_2, ....... &data_n);
Example: SQL>INSERT INTO student (sno, sname, class,address)
VALUES (&sno,‟&sname‟,‟&class‟,‟&address‟);
Enter value for sno: 101
Enter value for name: Ravi
Enter value for class: M.Tech
Enter value for name: Palakol

2. UPDATE-SET-WHERE: This is used to update the content of a record in a relation.


Syntax: SQL>UPDATE relation name SET Field_name1=data,field_name2=data,
WHERE field_name=data;
Example: SQL>UPDATE student SET sname = „kumar‟ WHERE sno=1;

3. DELETE-FROM: This is used to delete all the records of a relation but it will retain the
structure of that relation.

a) DELETE-FROM: This is used to delete all the records of relation.


Syntax:SQL>DELETE FROM relation_name;
Example: SQL>DELETE FROM std;

b) DELETE -FROM-WHERE: This is used to delete a selected record from a relation.


Syntax: SQL>DELETE FROM relation_name WHERE condition;
Example: SQL>DELETE FROM student WHERE sno = 2;

5. TRUNCATE: This command will remove the data permanently. But structure will not be
removed.

Difference between Truncate & Delete:-


 By using truncate command data will be removed permanently & will not get back
where as by using delete command data will be removed temporally & get back by
using roll back command.
 By using delete command data will be removed based on the condition where as by
using truncate command there is no condition.
 Truncate is a DDL command & delete is a DML command.

Syntax: TRUNCATE TABLE <Table name>


Example TRUNCATE TABLE student;

 To Retrieve data from one or more tables.

1. SELECT FROM: To display all fields for all records.

Syntax : SELECT * FROM relation_name;


Example : SQL> select * from dept;
DEPTNO DNAME LOC
-------- ----------- ----------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
2. SELECT FROM: To display a set of fields for all records of relation.

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;

Example: SQL> select * FROM dept WHERE deptno<=20;

DEPTNO DNAME LOC


------ ----------- ------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS

LAB PRACTICE ASSIGNMENT:

1) Create table Employee with attribute emp_id as varchar(6),name as


varchar(15),phone_no as number(10).
2) Add 3 more column to table employee salary number(5),designation varchar(10),doj date.
3) Employee name must be stored as fname,lname,mname.
4) Column phone_no is replaced with contact_no also add email_id as varchar(10)
5) Emp_id must be 4 digit integer number and make changes such that we can store 7 digit
salaryalso.
6) Change name of table as HRFaculty.
Constraints:
1) Write SQL statement to create student table with given attribute where class is
compulsory and add a column gender to the table student with default values(M/F).
2) Create table employee with attributes emp_no,name and salary where emp_no and
salary must be not null also emp_no must be unique.Add column gender as char(1)
with default value M.
3) Write SQL statement to create table worker with attributes worker_id,name and age
where age should must be between 18 to 50 years.
4) Create table dept with attributes dept_no and dept_name.Also create table student
with columns reg_no,fname,lname and dept_no is foreign key from dept table.
5) Create table Imaster with columns Icode,Iname,quantity,rate where quantity should
be greater than or equal to zero.
6) Write Sql to create table order with columns order_no,order_date,quantity. Where
quantity must be >=one.
7) Write SQL to create a given table with given attribute .Use suitable data types for
attributes and insert given data.
Experiment No: 3

Title: Implementation of different types of functions with suitable examples.


 Number function
 Aggregate function
 Character Function
 Conversion Function
 Datae Function

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;

SQL>select deptno,min(sal) from emp group by deptno having min(sal)>1000;

DEPTNO MIN (SAL)

101300

MATHEMATICAL / NUMBER FUNCTION:

Abs(n) :Select abs(-15) from dual;


Exp(n): Select exp(4) from dual;
Power(m,n): Select power(4,2) from dual;
Mod(m,n): Select mod(10,3) from dual;
Round(m,n): Select round(100.256,2) from dual;
Trunc(m,n): ;Select trunc(100.256,2) from dual;
Sqrt(m,n);Select sqrt(16) from dual;

CHARACTER FUNCTION:

initcap(char) : select initcap(“hello”) from dual;


lower (char): select lower („HELLO‟) from dual;
upper (char) :select upper („hello‟) from dual;
ltrim (char,[set]): select ltrim („cseit‟, „cse‟) from dual;

rtrim (char,[set]): select rtrim („cseit‟, „it‟) from dual;

replace (char,search ): select replace(„jack and jue‟,„j‟,„bl‟) from dual;

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:

Create a table EMPLOYEE with following schema:


(Emp_no, E_name, E_address, E_ph_no, Dept_no, Dept_name,Job_id, Designation , Salary)
Write SQL statements for the following query.
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’
10. List all the emps except ‘PRESIDENT’ & ‘MGR” in asc order of Salaries..

**************************************
Experiment No: 4

Title : Implementation of different types of operators in SQL.


 Arithmetic Operator
 Logical Operator
 Comparision Operator
 Special Operator
 Set Operator
Objective:

To learn different types of operator.

Theory:

ARIHMETIC OPERATORS:

(+) : Addition - Adds values on either side of the operator .

(-):Subtraction - Subtracts right hand operand from left hand operand .

(*):Multiplication - Multiplies values on either side of the operator .

(/):Division - Divides left hand operand by right hand operand .

(^):Power- raise to power of .


(%):Modulus - Divides left hand operand by right hand operand and returns remainder.

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: Returns all distinct rows selected by both the queries

Union all: Returns all rows selected by either query including the duplicates.

Intersect: Returns rows selected that are common to both queries.

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:

To implement different types of


joins

Theory :

TheSQLJoinsclauseisusedtocombinerecord from two or more tables in a database. A JOIN is


means for combining fields from two tables by using values common to each. The join is actually
performed by the ‘where’ clause which combines specified rows of tables.

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 :

A join, which is based on equalities, is called equi-join.

Example:

Select * from item, cust where


item.id=cust.id;
In the above statement, item-id = cust-id performs the join statement. It retrieves rows
from both the tables provided they both have the same id as specified by the where clause.
Since the where clause uses the comparison operator (=) to perform a join, it is said to
be.

equijoin. It combines the matched rows of tables. It can be used


as follows:

 To insert records in the target


table.
 To create tables and insert
records in this table.
 To update records in the target
table.
 To create views.

Non Equi-join:

It specifies the relationship between columns belonging to different tables by making use
of relational operators other than’=’.

Example:

Select * from item, cust where


item.id<cust.id;

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:

select * from emp x ,emp y where


x.salary >= (select avg(salary) from
x.emp
where x. deptno =y.deptno);

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

LAB PRACTICE ASSIGNMENT:

Consider the following schema:

Sailors (sid, sname, rating, age)


Boats (bid, bname, color)
Reserves (sid, bid, day(date))

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

Title: Study and implementation of


 Group by &having Clause
 Order by clause
 Indexing
 Sequence

Objective:

To learn the concept of group functions

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.

Syntax: SELECT <set of fields> FROM <relation_name>


GROUP BY <field_name>;

Example: SQL> SELECT EMPNO, SUM (SALARY) FROM EMP GROUP BY


EMPNO;

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.

Syntax: SELECT column_name, aggregate_function(column_name) FROM table_name


WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value;

Example : SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders


FROM (Orders
INNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID) GROUP BY LastName
HAVING COUNT (Orders.OrderID) > 10;
JOIN using GROUP BY: This query is used to display a set of fields from two relations by matching a
common field in them and also group the corresponding records for each and every value of a
specified key(s) while displaying.

Syntax: SELECT <set of fields (from both relations)> FROM relation_1,relation_2


WHERE relation_1.field_x=relation_2.field_y GROUP BY field_z;
Example:

SQL> SELECT empno,SUM(SALARY) FROM emp,dept


WHERE emp.deptno =20 GROUP BY empno

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;

 INDEXING: An index is an ordered set of pointers to the data in a table. It is based on


the data values in one or more columns of the table. SQL Base stores indexes separately
from tables.

An index provides two benefits:

 It improves performance because it makes data access faster.


 It ensures uniqueness. A table with a unique index cannot have two rows with the same values
in the column or columns that form the index key.

Syntax:

CREATE INDEX <index_name> on <table_name> (attrib1,attrib 2....attrib n);

Example:

CREATE INDEX id1 on emp(empno,dept_no);

LAB PRACTICE ASSIGNMENT:

Create a relation and implement the following queries.

1. Display total salary spent for each job category.


2. Display lowest paid employee details under each manager.
3. Display number of employees working in each department and their department name.
4. Display the details of employees sorting the salary in increasing order.
5. Show the record of employee earning salary greater than 16000 in each department.
6. Write queries to implement and practice the above clause.
Experiment 7:

Title: Study and implementation of


 Sub Queries
 Views

Objective:

– To perform nested Queries and joining Queries using DML command


– To understand the implementation of views.

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.

Syntax: CREATE VIEW <view_name> AS SELECT <set of fields>


FROM relation_name WHERE (Condition)

Example:

SQL> CREATE VIEW employee AS SELECT empno,ename,job FROM EMP


WHERE job = ‘clerk’;
SQL> View created.
Example:
CREATE VIEW [Current Product List] AS
SELECT ProductID, ProductName
FROM Products
WHERE Discontinued=No;

UPDATING A VIEW : A view can updated by using the following syntax :


Syntax : CREATE OR REPLACE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition

DROPPING A VIEW: A view can deleted with the DROP VIEW command.
Syntax: DROP VIEW <view_name> ;

LAB PRACTICE ASSIGNMENT:

Consider the following schema:


Sailors (sid, sname, rating, age)
Boats (bid, bname, color)
Reserves (sid, bid, day(date))
Write subquery statement for the following queries.

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

 Database Administrative commands for creating and managing database users’


 Backup &Recovery Commands.

Objective:

To understand the concept of administrative commands

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.

Syntax: SQL> COMMIT;


Example: SQL> COMMIT;

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.

Syntax: SQL> SAVE POINT ID;


Example: SQL> SAVE POINT xyz;

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:

ROLLBACK (current transaction can be role back)


ROLLBACK to save point ID;

Example: SQL> ROLLBACK;


SQL> ROLLBACK TO SAVE POINT xyz;

LAB PRACTICE ASSIGNMENT:

1. Write a query to implement the save point.


2. Write a query to implement the rollback.
3. Write a query to implement the commit.

****************************
Experiment: 9

Title: Creating Database/ Table Space

 Managing Users: - Create User, Delete User


 Managing Passwords
 Managing roles: - Grant , Revoke

Objective:

To understand the concept of administrative commands

Theory:

DATABASE is collection of coherent data.


To create database we have :

Syntax: CREATE DATABASE <database_name>

Example : CREATE DATABASE my_db;

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<tablespace name> DATAFILE'C:\oraclexe\app\oracle\product\10.2.0\


server \<file name.dbf ’SIZE 50M;
Example:

Create tablespace te_cs DATAFILE 'C:\oraclexe\app\oracle\product\10.2.0\


server\usr.dbf ’SIZE 50M;

CREATE USER:

The DBA creates user by executing CREATE USER statement.


The user is someone who connects to the database if enough privilege is granted.

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

Eg: create user James identified by bob;


(The user does not have privilege at this time, it has to be granted.These privileges determine what
user can do at database level.)
PRIVILEGES:

A privilege is a right to execute an SQL statement or to access another user's object.


In Oracle, there are two types of privileges.

 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.

Eg: Create Session,Create Table,Create user etc..

 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

Eg: Grant create session, create table, create view to James;


Object privileges vary from object to object.An owner has all privilege or specific privileges
on object.
SQL> GRANT object_priv [(column)]
ON object

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>

Eg: ALTER USER James


IDENTIFIED BY sam
REVOKE:

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;

Eg: Grant custom to James, Steve;

LAB PRACTICE ASSIGNMENT:

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

Title: Creation of procedures, trigger and cursor.

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:

 As individual objects (the default method) or


 As operations in a container

Creation of stored Procedures and Execution of Procedures and Modification of


Procedures.

Ex1: CREATE PROCEDURE BUS_PROC1() BEGIN

SELECT * FROM BUS;

END$$

CALL BUS_PRO

Ex2: CREATE PROCEDURE SAMPLE2()

BEGIN DECLARE X INT(3);

SET X=10; SELECT X;

END$$

Mysql> CALL SAMPLE2()$$


Database Triggers:

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:

create trigger [trigger_name]

[before | after]

{insert | update | delete}

on [table_name]

[for each row]

[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.

Syntax : DECLARE cursor_name CURSOR FOR select_statement;

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

Title:Study Of open source NoSQL Database (installation ,BAsicOperation and Execution.

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:

Follow this procedure to install the Oracle NoSQL Database:

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:

Copyjava -Xmx64m -Xms64m -jar <KVHOME>/lib/kvclient.jar

You should see some output that looks like this:

Copy11gR2.M.N.O (....)

where M.N.O is the package version number.

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.

NoSQL CRUD Operations( Basic operation of NoSQL):


CRUD(Create,Read,Update,Delelet)

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.

1) NoSQL CRUD Operations: Creating Documents


TO Create in the nosql CRUD Operations in mongodb indicates the creation of a data document.

The two important commands to create documents in MongoDB are:

 insertOne()
 insertMany()

CODE:

db.monuments.insertOne(

{ "name": "The Pyramids of Giza",

"city": "Giza",

"country": "Egypt",

"gps": {

"lat": 29.976480,

"lng": 31.131302 }}})

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 }}

2) NoSQL CRUD Operations: Reading Documents

you can query the database to retrieve the Document from the database and read its data.

There are two methods to read data in MongoDB

 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()

3) NoSQL CRUD Operations: Updating Documents

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.

4) NoSQL CRUD Operations: Deleting Documents

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" }
)

Alternatively, you can delete Documents that have a common attribute.

CODE:

db.monuments.deleteMany(

{ "country": "France" }
****************************************

You might also like