0% found this document useful (0 votes)
6 views

DBMS Lab Manual

The document is a laboratory manual for a Database Management System course at Dilkap Research Institute of Engineering & Management Studies. It outlines the lab objectives, outcomes, and a series of experiments designed to teach students about relational models, SQL commands, and transaction processing. Each experiment includes specific aims, required resources, theoretical background, and expected outcomes to enhance students' practical skills in database management.

Uploaded by

silverff073
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

DBMS Lab Manual

The document is a laboratory manual for a Database Management System course at Dilkap Research Institute of Engineering & Management Studies. It outlines the lab objectives, outcomes, and a series of experiments designed to teach students about relational models, SQL commands, and transaction processing. Each experiment includes specific aims, required resources, theoretical background, and expected outcomes to enhance students' practical skills in database management.

Uploaded by

silverff073
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Suman Educational Trust’s

Dilkap Research Institute of


Engineering &Management Studies

SUBJECT TEACHER

PROF. SHITAL AGRAWAL

DEPARTMENT OF COMPUTER
ENGINEERING
LABORATORY MANUAL

COURSE: Database Management system Lab

COURSE CODE: CSL402


Semester-IV

University Syllabus for the lab

Lab Code Lab Name Credit


CSL402 Database Management 1
system Lab

Prerequisite: Discrete Structures


Lab Objectives:
1 To explore design and develop of relational model.
2 To present SQL and procedural interfaces to SQL comprehensively.
3 To introduce the concepts of transactions and transaction processing.

Lab Outcomes: Students will be able: -


DRIEMS
1 Design ER /EER diagram and convert to relational model for the real world
application.
2 Apply DDL, DML, DCL and TCL commands.
3 Write simple and complex queries.
4 Use PL / SQL Constructs.
5 Demonstrate the concept of concurrent transactions execution and frontend-
backend connectivity.

SR.NO Name of the Experiment


1 Identify the case study and detail statement of problem. Design an Entity-
Relationship (ER) / Extended Entity-Relationship (EER) Model.
2 Mapping ER/EER to Relational schema model.

3 Create a database using Data Definition Language (DDL) and apply integrity
constraints for the specified System.

4 Apply DML Commands for the specified system.

5 Perform Simple queries, string manipulation operations and aggregate functions.

6 Implement various Join operations.

7 Perform Nested and Complex queries.

8 Perform DCL and TCL commands.

9 Implement procedure and functions.

10 Implementation of Views and Triggers.

11 Demonstrate Database connectivity.

12 Implementation and demonstration of Transaction and Concurrency control


techniques using locks.
DRIEMS

LIST OF EXPERIMENTS

Expt. Name of the Experiment Page COs


No. No.
1. Identify the case study and detail statement of problem. 1 CO1
Design an Entity-Relationship (ER) /
Extended Entity- Relationship (EER) Model.
2. Mapping ER/EER to Relational schema model. 5 CO1

3. Create a database using Data Definition Language (DDL) 10 CO2

and apply integrity constraints for the CO5


specified System
4. Apply DML Commands for the specified system. 16 CO2

CO5

5. Perform string manipulation operations and aggregate 18 CO4


functions with group by... Having clause
6. Perform Join operations 23 CO4

7. Perform TCL and DCL commands. 25 CO4

CO5
8. Implementation of Views and Triggers 29 CO4

CO5

9. Write PL/SQL code block to calculate the area of circle for a 33 CO6
value of radius varying from 5 to 10. Store the radius and the
corresponding values of calculated area in a table named
areas (radius, area)

10. Demonstrate Database connectivity 35 CO4

11. Case Study on MongoDB (Content Beyond Syllabus) 37

12. Virtual Lab


DRIEMS

EXPERIMENT NO- 1

AIM: Identify the case study and detail statement of problem. Design an Entity-Relationship
(ER) / Extended Entity-Relationship (EER) Model.

RESOURCES REQUIRED: P I and above, RAM 128MB, Printers and Cartridges, Windows
machine.

THEORY:

The entity-relationship E-R model is very useful in mapping the meanings and interactions of
real-world enterprises onto a conceptual schema. Because of this usefulness, many database-
design tools draw on concepts from the E-R model. The E-R data model employs three basic
concepts: entity sets, relationship sets, and attributes. The E-R model also has an associated
diagrammatic representation, the ER diagram, which can express the overall logi cal structure
of a database graphically.

An entity is an object that exists and is distinguishable from other objects. Example: specific
person, company, event, plant

An entity set is a set of entities of the same type that share the same properties. Example: set
of all persons, companies, trees, holidays

An entity is represented by a set of attributes; i.e., descriptive properties possessed by all members
of an entity set.
Example:
DRIEMS
instructor = (ID, name, street, city, salary )

course= (course_id, title, credits)

A subset of the attributes forms a primary key of the entity set; i.e., uniquely identifying each
member of the set.

Attribute types:

• Simple and composite attributes.


• Single-valued and multivalued attributes

Example: multivalued attribute: phone_numbers

• Derived attributes: can be computed from other attributes Example: age, given
date_of_birth
Domain – the set of permitted values for each attribute

Express the number of entities to which another entity can be associated via a relationship set.
Most useful in describing binary relationship sets.

For a binary relationship set the mapping cardinality must be one of the following types:

• One to one
• One to many
• Many to one
• Many to many
DRIEMS
Symbols Used in E-R Notation

CONCLUSION: Hence, we have successfully designed ER model for Bank.

VIVA QUESTIONS:
3

1. What is an ER model in database?


2. What is the meaning of ER modelling?
3. What is an ER model used for?
4. What are the two main components of an ER modedl?

REFERENCES :

1. https://www.interviewbit.com/blog/er-model-in-dbms/
2. https://www.scaler.com/topics/what-is-er-model-in-dbms/
3. https://www.simplilearn.com/tutorials/sql-tutorial/er-diagram-in-dbms
4. https://www.youtube.com/watch?v=wOD02sezmX8
DRIEMS

EXPERIMENT NO- 2

AIM: Mapping ER/EER to Relational schema model.

RESOURCES REQUIRED: P I and above, RAM 128MB, Printers and Cartridges, Linux or Windows
machine, Oracle.

THEORY:

The set of allowed values for each attribute is called the domain of the attribute values are
(normally) required to be atomic; that is, indivisible

The special value null is a member of every domain. Indicated that the value is

“unknown”

The null value causes complications in the definition of many operations A1, A2, …, An are
attributes

R = (A1, A2, …, An) is a relation schema Example:

instructor = (ID, name, dept_name, salary)

Formally, givensets D1,D2 ….Dn a relation r is a subset of D1 x D2 x … x Dn

Thus, a relation is a set of n-tuples (a1, a2, …, an) where each ai € Di

The current values (relation instance) of a relation are specified by a table An element t of r is
a tuple, represented by a row in a table

Primary keys allow entity sets and relationship sets to be expressed uniformly as relation
schemas that represent the contents of the database.

A database which conforms to an E-R diagram can be represented by a collection of schemas.

For each entity set and relationship set there is a unique schema that is assigned the name of
the corresponding entity set or relationship set.

Each schema has a number of columns (generally corresponding to attributes), which have
unique names.
DRIEMS
Representing Entity Sets as Schemas

A strong entity set reduces to a schema with the same attributes.

A weak entity set becomes a table that includes a column for the primary key of the identifying
strong entity set

payment = (loan_number, payment_number, payment_date, payment_amount )

A many-to-many relationship set is represented as a schema with attributes for the primary
keys of the two participating entity sets, and any descriptive attributes of the relationship set.

Example: schema for relationship set borrower

borrower = (customer_id, loan_number )

Many-to-one and one-to-many relationship sets that are total on the many-side can be
represented by adding an extra attribute to the “many” sides, containing the primary key of
the “one” side

Example: Instead of creating a schema for relationship set account_branch, add an attribute
branch_name to the schema arising from entity set account

For one-to-one relationship sets, either side can be chosen to act as the “many”

side

That is, extra attribute can be added to either of the tables corresponding to the two entity
sets

If participation is partial on the “many” sides, replacing a schema by an extra attribute in the
schema corresponding to the “many” sides could result in null values.

The schema corresponding to a relationship set linking a weak entity set to its identifying strong
entity set is redundant.
DRIEMS
Example: The payment schema already contains the attributes that would appear in the
loan_payment schema (i.e., loan_number and payment_number).

Composite attributes are flattened out by creating a separate attribute for each component
attribute.

Example: given entity set customer with composite attribute name with component attributes
first_name and last_name the schema corresponding to the entity set has two attributes

name.first_name and name.last_name

A multivalued attribute M of an entity E is represented by a separate schema EM

Schema EM has attributes corresponding to the primary key of E and an attribute


corresponding to multivalued attribute M

Example: Multivalued attribute dependent_names of employee is represented by a schema:

employee_dependent_names = ( employee_id, dname)

Each value of the multivalued attribute maps to a separate tuple of the relation on schema EM
For example, an employee entity with primary key 123-45-6789 and dependents Jack and Jane
maps to two tuples:

(123-45-6789 , Jack) and (123-45-6789 , Jane)

Representing Specialization via Schemas

Form a schema for each entity set with all local and inherited attributes schema attributes

Person name, street, city

customer name, street, city, credit_rating

employee name, street, city, salary

If specialization is total, the schema for the generalized entity set (person) not required to store
information

Can be defined as a “view” relation containing union of specialization

relations

But explicit schema may still be needed for foreign key constraints
DRIEMS
Drawback: street and city may be stored redundantly for people who are both customers and
employees

Schemas Corresponding to Aggregation

To represent aggregation, create a schema containing primary key of the aggregated


relationship, the primary key of the associated entity set any descriptive attributes

For example, to represent aggregation manages between relationship works_on and entity set
manager, create a schema

manages (employee_id, branch_name, title, manager_name)

Schema works_on is redundant provided we are willing to store null values for attribute
8

manager_name in relation on schema manages

CONCLUSION: Hence we have successfully mapped our ER model to Relational Schema.

VIVA QUESTIONS :

1. What is relational schema?


2. What is the function of relational schema?
DRIEMS
EXPERIMENT NO- 3

AIM: Create a database using Data Definition Language (DDL) and apply integrity constraints
for the specified System.

RESOURCES REQUIRED: P I and above, RAM 128MB, Printers and Cartridges, Linux or Windows
machine, Oracle.

THEORY:

Data-definition language (DDL): The SQL DDL provides commands for defining relation
schemas, deleting relations, and modifying relation schemas.

Data-manipulation language (DML): The SQL DML provides the ability to query information
from the database and to insert tuples into, delete tuples from, and modify tuples in the
database.

SQL Data Definition

The set of relations in a database must be specified to the system by means of a data-definition
language (DDL). The SQL DDL allows specification of not only a set of relations, but also
information about each relation, including:

• The schema for each relation.


• The types of values associated with each attribute.
• The integrity constraints.
• The set of indices to be maintained for each relation.
• The security and authorization information for each relation.
• The physical storage structure of each relation on disk

Basic types

The SQL standard supports a variety of built-in types, including:


• char(n): A fixed-length character string with user-specified length n. The full form,
character, can be used instead.
• varchar(n): A variable-length character string with user-specified maximum length n.
The full form, character varying, is equivalent.
• int: An integer (a finite subset of the integers that is machine dependent). The full form,
integer, is equivalent.
DRIEMS
• smallint: A small integer (a machine-dependent subset of the integer type).
• numeric(p, d): A fixed-point number with user-specified precision. The number consists
of p digits (plus a sign), and d of the p digits are to the right of the decimal point. Thus,
numeric(3,1) allows 44.5 to be stored exactly, but neither 444.5 or 0.32 can be stored
exactly in a field of this type.
• real, double precision: Floating-point and double-precision floating-point numbers with
machine-dependent precision.
• float(n): A floating-point number, with precision of at least n digits.

Each type may include a special value called the null value. A null value indicates an absent
value that may exist but be unknown or that may not exist at all.

Create table construct

An SQL relation is defined using the create table command:

create table r (A1D1, A2D2, ..., AnDn,

(integrity-constraint1),

...,

(integrity-constraintk))

• r is the name of the relation


• each Ai is an attribute name in the schema of relation r

• Di is the data type of values in the domain of attribute Ai

Drop and Alter Table Constructs

The drop table command deletes all information about the dropped relation from the
database.

The alter table command is used to add attributes to an existing relation:

alter table r add A D

where A is the name of the attribute to be added to relation r and D is the domain of A.

All tuples in the relation are assigned null as the value for the new attribute. The alter table
command can also be used to drop attributes of a relation:
DRIEMS
alter table r drop A

Where A is the name of an attribute of relation r.

TRUNCATE: Remove all records from table, including spaces allocated for the records are
removed.

Syntax:

TRUNCATE TABLE <TABLE NAME>;

Integrity Constraints

Integrity constraints guard against accidental damage to the database, by ensuring that
authorized changes to the database do not result in a loss of data consistency.

• A checking account must have a balance greater than $10,000.00


• A salary of a bank employee must be at least $4.00 an hour
• A customer must have a (non-null) phone number

Constraints on a Single Relation


• not null
• primary key
• unique
• check (P), where P is a predicate

Not Null Constraint

Declare branch_name for branch is not null

branch_name char(15) not null

The Unique Constraint

unique (A1, A2, …, Am)

The unique specification states that the attributes A1, A2, …, Am form a candidate key.

Candidate keys are permitted to be null (in contrast to primary keys).

The check clause

check (P), where P is a predicate


DRIEMS
Example: Declare branch_name as the primary key for branch and ensure that the values of
assets are non-negative.

create table branch (branch_name, char(15),

branch_city ,char(30),

assets integer,

primary key (branch_name),

check (assets >= 0))

Referential Integrity

Ensures that a value that appears in one relation for a given set of attributes also appears for a
certain set of attributes in another relation.

Example: If “Perryridge” is a branch name appearing in one of the tuples in the ṅ “Perryridge”.

Primary and candidate keys and foreign keys can be specified as part of the SQL

create table statement:

The primary key clause lists attributes that comprise the primary key. The unique key clause
lists attributes that comprise a candidate key.

The foreign key clause lists the attributes that comprise the foreign key and the name of the
relation referenced by the foreign key. By default, a foreign key references the primary key
attributes of the referenced table.

create table account (account_number, char(10),

branch_name,char(15), balance,integer,

primary key (account_number),

foreign key (branch_name) references branch)

CONCLUSION: Hence, we have successfully execute DDL commands using SQL command line

VIVA QUESTIONS :

1. What are the 4 commands of DDL?


2. What is the difference between DDL and DML?
DRIEMS
3. Why is DDL used?

REFERENCES:
1. https://docs.snowflake.com/en/sql-reference/sql-ddl-
summary.html#:~:text=DDL%20commands%20are%20used%20to,%2C%20functions%
2C%20and%20stored%20procedures.
2. https://www.techtarget.com/whatis/definition/Data-Definition-Language-DDL
3. https://www.edureka.co/community/30109/list-few-commands-of-ddl-dml-and-dcl
4. https://www.youtube.com/watch?v=LzeeuDvhygc
DRIEMS
EXPERIMENT NO- 4

AIM: Perform DML Commands for the specified System.

RESOURCES REQUIRED: P I and above, RAM 128MB, Printers and Cartridges, Linux or Windows
machine, Oracle.

THEORY:

DML Commands: Data Manipulation Language statements

It is the area of SQL that allows changing data within the database.

Examples:

• INSERT: Insert data into a table.

Syntax:

INSERT INTO tablename VALUES (value list);

• UPDATE: Updates existing data within a table.

Syntax:

UPDATE tablename SET column_name =value [ WHERE condition] Example: update emp
set sal=20000 where empno=7369;

• DELETE: Deletes all records from a table

Syntax:

DELETE FROM tablename WHERE condition

DQL Commands: Data Query Language

It is the components of SQL statements that allows getting data from database.
Examples:

• SELECT: Retrieve data from database.

SQL is based on set and relational operations with certain modifications and enhancements

A typical SQL query has the form:

select A1, A2, ..., An


DRIEMS

from r1, r2, ..., rm

where P

Ai represents an attribute Ri represents a relation

P is a predicate.

SELECT * FROM tablename

CONCLUSION: Hence, we have successfully used DML commands on our specified system using
SQL Command Line.

VIVA QUESTIONS:

1. What are 3 DML commands?


2. What is an example of DML?
3. What is DML syntax?

REFERENCES :

1. https://www.educba.com/sql-dml-commands/
2. https://docs.snowflake.com/en/sql-reference/sql-dml.html
3. https://www.scaler.com/topics/dml-commands-in-sql/
4. https://study.com/learn/lesson/ddl-dml-commands-examples.html
DRIEMS

EXPERIMENT NO.5

AIM: Perform string manipulation operations and aggregate functions with group by Having
clause.

RESOURCES REQUIRED: H/W Requirements: P I and above, RAM 128MB, Printers and
Cartridges, Linux or Windows machine, Oracle.

THEORY:

Like Condition

A LIKE condition specifies a test involving pattern matching.

We describe patterns by using two special characters: Percent (%): The % character matches
any substring.

Underscore (_): The character matches any character.

Syntax:

SELECT columns FROM tables

WHERE column1 LIKE ’%_’;

Example:

List the customers whose name begin with the letters ’Ch'

SELECT FName,LName

FROM cust

WHERE FName LIKE ‘Ch%’;

The % indicates that any number of characters can follow the letter Ch. select lower(name) ||
DRIEMS
upper(name) from try;

select lower('RINA') from dual; select upper(name) from try;

select * from try where name like '%mal%'

Logical Operator

1. OR Operator
The OR condition allows you to create an SQL statement where records are returned
when any one of the conditions are met. It can be used in any valid SQL statement -
select, insert, update, or delete.
Syntax:
SELECT columns
FROM tables
WHERE column1 = ‘value1’ or column2 = ‘value2’

The OR condition requires that any of the conditions must be met for the record to be
included in the result set. In this case, column1 has to be equal to ‘value1’ OR column2
has to be equal to ‘value2’.

Example

SELECT *

FROM suppliers

WHERE city = 'New York' or city = 'Newark';

This would return all suppliers that reside in either New York or Newark. Because the *
is used in the select, all fields from the suppliers table would appear in the result set.

2. AND Operator
The AND operator displays a record if both the first condition and the second condition
is true.
Syntax:
SELECT columns FROM tables
WHERE column1 = 'value1' and column2 = 'value2'
Example:
SELECT *
DRIEMS
FROM EMP
WHERE EmpTown = 'London' AND EmpAge > 30
3. NOT Operator:
If you want to find rows that do not satisfy a condition, you can use the logical operator,
NOT. NOT results in the reverse of a condition. That is, if a condition is satisfied, then
the row is not returned.
Example:
If you want to find out the names of the students who do not play football, the
query would be like:
SELECT first_name, last_name, games
FROM student_details
WHERE NOT games = 'Football’;

ORDER BY clause: Sorting of data in table

The ORDER BY keyword is used to sort the result-set by a specified column. The ORDER BY
keyword sort the records in ascending order by default.

If you want to sort the records in a descending order, you can use the DESC keyword

Syntax:

SELECT "column_name"

FROM "table_name" [WHERE "condition"]

ORDER BY "column_name" [ASC, DESC];

Aggregate Functions

Aggregate functions return a single result row based on groups of rows, rather than on single
rows.

avg: average value

min: minimum value

max: maximum value

sum: sum of values

count: number of values


DRIEMS

Find the average account balance at the Perryridge branch

select avg (balance)

from account

where branch_name = 'Perryridge'

Find the number of tuples in the relation

select count (*)

from customer

Find the number of depositors in the bank

select count (distinct customer_name) from depositor

Aggregate Functions – Group By

Find the number of depositors for each branch.

select branch_name, count (distinct customer_name) from depositor, account


where depositor.account_number = account.account_number group by branch_name

Find the names of all branches where the average account balance is more than 1,200.

select branch_name, avg (balance) from account

group by branch_name having avg (balance) > 1200

predicates in the having clause are applied after the formation of groups whereas predicates
in the where clause are applied before forming groups

select count(ename),dno from emp group by dno;

CONCLUSION: Hence, we have successfully preformed string manipulation operations and


aggregate functions with group by and having clause using SQL Command Line Client

VIVA QUESTIONS:

1. Can aggregate functions be used with having clause?


2. Can we use group by and having clause together?
3. Is string_agg an aggregate functions?
DRIEMS
REFERENCES:

1. https://www.simplilearn.com/tutorials/sql-tutorial/group-by-in-sql
2. https://www.sqlshack.com/string_agg-function-in-sql/
3. https://www.datacamp.com/tutorial/group-by-having-clause-sql
4. https://intellipaat.com/blog/tutorial/sql-tutorial/sql-functions/
5. https://www.sqlshack.com/learn-sql-aggregate-functions/

EXPERIMENT NO.6

AIM: To Perform Join operations.

RESOURCES REQUIRED: P I and above, RAM 128MB, Printers and Cartridges, Linux or Windows
machine, Oracle, Notepad.

THEORY:

Different type of joins in SQL:

• (INNER) JOIN: Returns records that have matching values in both tables
• LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records
from the right table.
• RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records
from the left table.
DRIEMS
• FULL (OUTER) JOIN: Returns all records when there is a match in either left or right
table.

select master.rno, demo.rno, demo.name from master

right outer join demo

on master.rno=demo.rno;

CONCLUSION: Hence, we have successfully performed various join operations using SQL
Command Line.

VIVA QUESTIONS:

1. What is an join operation?


2. What are the different types of joins?
3. Why we use join operation?
4. Which type of join is faster?
5. Where is join used?

REFERENCES :

1. https://www.ibm.com/docs/SSULQD_7.1.0/com.ibm.nz.dbu.doc/c_dbuser_types_join
s.html
2. https://docs.oracle.com/javadb/10.6.2.1/ref/rrefsqlj29840.html
3. https://learn.microsoft.com/en-us/dotnet/csharp/programming-
guide/concepts/linq/join-operations
4. https://www.scaler.com/topics/dbms/joins-in-dbms/
DRIEMS

EXPERIMENT NO- 7

AIM: Perform TCL and DCL commands.

RESOURCES REQUIRED: P I and above, RAM 128MB, Printers and Cartridges, Linux or Windows
machine, Oracle.

THEORY:

Transaction Control Language (TCL):


DRIEMS

TCL commands are used to manage transactions in the databases. These are used to manage
the changes made to the data in a table by DML statements. It also allows statements to be
grouped together into logical transactions.

• COMMIT Command:
COMMIT command is used to permanently save any transaction into the database.
When we use any DML command like INSERT, UPDATE or DELETE, the changes made by
these commands are not permanent, until the current session is closed, the changes
made by these commands can be rolled back.
To avoid that, we use the COMMIT command to mark the changes as permanent.
Following is commit command's syntax,
Commit;
• ROLLBACK Command:

This command restores the database to last committed state. It is also used with
SAVEPOINT command to jump to a savepoint in an ongoing transaction.

If we have used the UPDATE command to make some changes into the database, and
realise that those changes were not required, then we can use the ROLLBACK command
to rollback those changes, if they were not committed using the COMMIT command.

Following is rollback command's syntax, Rollback;

• SAVEPOINT Command:
SAVEPOINT command is used to temporarily save a transaction so that you can rollback
to that point whenever required.
Following is savepoint command's syntax, savepoint (savepoint-name);

Data control language (DCL):

As always, begin by connecting to your server where Oracle is hosted, then connect to Oracle
itself as the SYSTEM account.

The SYSTEM account is one of a handful of predefined administrative accounts generated


automatically when Oracle is installed. SYSTEM is capable of most administrative tasks, but the
task we’re particularly interested in is account management.

• Creating a user:
DRIEMS

Once connected as SYSTEM, simply issue the CREATE USER command to generate a new
account.

Create user <username> identified by <password>;

Here, we’re simply creating a user account that is identified or authenticated by the
specified password.

• The GRANT statement:


With our new account created, we can now begin adding privileges to the account using
the GRANT statement. GRANT is a very powerful statement with many possible options,
but the core functionality is to manage the privileges of both users and roles throughout
the database.
• Providing Roles:
Typically, you will first want to assign privileges to the user through attaching the
account to various roles, starting with the CONNECT role:

GRANT CONNECT TO <username>;


In some cases, to create a more powerful user, you may also consider adding the
RESOURCE role (allowing the user to create named types of custom schemas) or even
the DBA role, which allows the user to not only create custom named types but alter
and destroy them as well.
GRANT CONNECT, RESOURCE, DBA TO <username>;
• Assigning Privileges:
Next, you’ll want to ensure the user has privileges to actually connect to the database
and create a session using GRANT CREATE SESSION. We’ll also combine that with all
privileges using GRANT ANY PRIVILEGES.
GRANT CREATE SESSION TO <username>;
We also need to ensure our new user has disk space allocated in the system to actually
create or modify tables and data, so we’ll GRANT TABLESPACE like so:
GRANT UNLIMITED TABLESPACE TO <username>;
GRANT RESOURCE TO <username>;
GRANT SELECT, INSERT, UPDATE, DELETE ON demo TO <username>;
GRANT ALL ON demo TO <username>;
DRIEMS
CONNECT <username>/<password>;
SELECT * FROM system.demo;
DELETE FROM system.demo WHERE rno = 1;
CONNECT system/oracle;
REVOKE DELETE ON demo FROM <username>;

CONCLUSION: Hence, we have successfully performed TCL and DCL commands in SQL
Command Line.

VIVA QUESTIONS:

1. What are DCL and TCL commands?

2. What is the difference between DCL and TCL commands?


3. Why TCL is used in SQL?
4. What are the 3 TCL commands?

REFERENCES :

1. https://blog.sqlauthority.com/2008/01/15/sql-server-what-is-dml-ddl-dcl-and-tcl-
introduction-and-examples/
2. https://www.c-sharpcorner.com/blogs/ddl-dml-dcl-and-tcl-commands-in-sql-server1
3. https://www.tableauexpert.co.in/2014/12/drl-ddl-dml-tcl-and-dcl-commands.html
4. https://m.youtube.com/watch?v=ngwBXljY0No
5. https://www.youtube.com/watch?v=bZ2uDF6XKGA
DRIEMS

EXPERIMENT NO- 8

AIM: Write a PL/SQL block to create Triggers for update, delete and insert.

RESOURCES REQUIRED: P I and above, RAM 128MB, Printers and Cartridges, Linux or Windows
machine, Oracle.

THEORY:

Views:

A view is a virtual table, which provides access to a subset of column from one or more tables.
A view can derive its data from one or more table. An output of query can be stored as a view.
A view in oracle is nothing but a stored sql script.

Create view v11 as (select empid, ename, dname frfom emp, dept where emp.dno =
dedpt.dno);

Views maybe created for the following reasons:

1. The DBA stores the views as a definition only. Hence there is no duplication of data.
2. Simplifies Queries.
3. Can be Queried as a base table itself.
4. Provides data security.
5. Avoids data redundancy.
• Creation of views:
Syntax:
CREATE VIEW <viewname> AS
SELECT <column1>, <column2>
FROM <table>
WHERE column = expression list;
• Renaming the columns of a view:
DRIEMS
Syntax:
CREATE VIEW <viewname> AS
SELECT newcolumn
FROM table
WHERE column = expression_list;
• Selecting a dataset from a view:
Syntax:
SELECT column1, column2 AS
FROM viewname
WHERE search condition;
• Destroying a view:
Syntax:
DROP VIEW <viewname>;

Triggers:

Triggers are stored programs, which are automatically executed or fired when some events
occur. Triggers are, in fact, written to be executed in response to any of the following events −

• A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)


• A database definition (DDL) statement (CREATE, ALTER, or DROP).
• A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).

Triggers can be defined on the table, view, schema, or database with which the event is
associated.

• Benefits of Triggers

Triggers can be written for the following purposes −

o Generating some derived column values automatically


o referential integrity
o Event logging and storing information on table access
o Auditing
o Synchronous replication of tables
o Imposing security authorizations
DRIEMS
o Preventing invalid transactions
• The syntax of creating triggers:

CONCLUSION: Hence, we have successfully implemented views and triggers in MySQL


Command Line.

VIVA QUESTIONS:

1. What are views and triggers?


2. Which triggers are used in views?
3. What are 3 types of SQL triggers?

REFERENCES :

1. https://www.mssqltips.com/sqlservertip/5984/sql-server-trigger-on-view-example/
2. https://databasefaqs.com/sql-server-trigger-on-view/

3. https://www.youtube.com/watch?v=f6VWSlnHGCE
4. https://www.ibm.com/docs/SSGU8G_14.1.0/com.ibm.sqls.doc/ids_sqs_0637.htm
DRIEMS

EXPERIMENT NO- 9

AIM: Write PL/SQL code block to calculate the area of circle for a value of radius varying from
1 to 10. Store the radius and the corresponding values of calculated area in a table named areas
(radius, area).

RESOURCES REQUIRED: P I and above, RAM 128MB, Printers and Cartridges, Linux or Windows
machine, Oracle.

THEORY:

BEGIN

DECLARE pi float(5,4) DEFAULT 3.14; DECLARE r int(5);

DECLARE a float(7,2); SET r = 1;

WHILE r<=10 DO

SET a = pi*r*r;

INSERT INTO area values(r,a); SET r = r+1;


DRIEMS
END WHILE;

END

CONCLUSION: Hence, we have successfully calculated area of circle for radius varying from 1
to 10 using code block in SQL Command Line.

VIVA QUESTIONS:

1. What is a block code in SQL?


2. How do we run a SQL block?
3. How do we code SQL in terminal?

REFERENCES :
1. https://www.oracletutorial.com/plsql-tutorial/plsql-anonymous-
block/#:~:text=PL%2FSQL%20is%20a%20block,exception%2Dhandling%20sections%20
are%20optional.
2. https://docs.oracle.com/cd/F49540_01/DOC/server.815/a66736/ch22.htm
3. https://www.youtube.com/watch?v=IHEuMqnq640

EXPERIMENT NO- 10

AIM: Demonstrate Database connectivity

RESOURCES REQUIRED:

H/W Requirements: P I and above, RAM 128MB, Printers and Cartridges. S/W Requirements:
Linux or Windows machine, Oracle, Python Compiler.

THEORY:

Step1: Install python and set the path.

Step2: Using any IDE or in terminal write the following command to install mysql connector:

pip install mysql-connector-python or

Python -m pip install mysql-connector-python (if upper command doesn’t


DRIEMS
work)

After installing above library, we’re ready to use it in our python files

(Note: If you create Virtual Environment you need to install it in your Virtual Environment.)

Step3: Create a Python file of your desired name (extension: .py)

Step4: You need to write following code at the top to import mysql connector: from mysql
import connector

Step5: Now we need to connect to database using mysql.connector object, for that we have
following syntax:

Object_name = connector.connect( host=“hostname”, username=”db_username”, password =


“user_password”, database = “db_name”)

Hostname: In our case hostname is local host since we’re not hosting it

anywhere

db_username: It is a database username it should exist or else code will raise an error.

Password: user password should be correct or code will raise an error. db_name: database
name which you’re going to use if not exist it will raise an error.

Step6: If everything is correct in Step 5, we have successfully connected to our database and
we can write queries using our Object.

CONCLUSION: Hence, we have successfully demonstrated MySQL database connectivity in


Python.

REFERENCES :

1. https://www.youtube.com/watch?v=DCgRF4KOYIY
2. https://dev.mysql.com/doc/workbench/en/wb-getting-started-tutorial-create-
connection.html
3. https://docs.oracle.com/cd/E19182-01/820-6209/ghvre/index.html
DRIEMS

EXPERIMENT NO- 11

AIM: Case study on MongoDB.

THEORY:

MongoDB:

MongoDB is a document-oriented NoSQL database used for high volume data storage. Instead
DRIEMS
of using tables and rows as in the traditional relational databases, MongoDB makes use of
collections and documents. Documents consist of key-value pairs which are the basic unit of
data in MongoDB. Collections contain sets of documents and function which is the equivalent
of relational database tables. MongoDB is a database which came into lig ht around the mid-
2000s.

MongoDB is an open source NOSQL database which falls under the classification of document
database. It was initiated by 10gen Company. It was written in C++.

MongoDB documents are stored in binary form of JSON called BSON format. BSON supports
string, integer, date, Boolean, float and binary types. MongoDB is schema less so it gives the
freedom to user for inserting new fields to the document or updating the previous structure of
document. It does not use joins like relational databases as it has embedded documents which
can be accessed quickly. MongoDB also support Master Slave replication where slave nodes
contain the replicas of master nodes and are used for backups and reads.

MongoDB cluster is built up of three components.

1. Shard node: it contains one of more shards. Each master shard has its one or more slave
shards. The slave shards contain the copies of actual data which can be used at the time
of failures.

2. Configuration Server: A group of servers in MongoDB are called the configuration


servers. The role of configuration server is to store the routing information and send
the request to the right shard.
3. Mongos: Mongos are stateless and can be run in parallel. It is responsible for serving
the task requests from the clients. The request can need multiple shards. So, mongos
collect the data from different shards and merge them nicely before handing it over to
the client.
DRIEMS

Working of MongoDB:

MongoDB is a server process that runs on Linux, Windows and OS X. It can be run both as a 32
or 64-bit application. Clients connect to the MongoDB process.

MongoDB stores its data in files (default location is /data/db./), and uses memory mapped files
for data management for efficiency.

Main Features:
DRIEMS
1. Document-oriented

Since MongoDB is a NoSQL type database, instead of having data in a relational type
format, it stores the data in documents. This makes MongoDB very flexible and
adaptable to real business world situation and requirements.

2. Ad hoc Queries:
MongoDB supports searching by field, range queries, and regular expression searches.
Queries can be made to return specific fields within documents.
3. Indexing:
Indexes can be created to improve the performance of searches within MongoDB. Any
field in a MongoDB document can be indexed.
4. Replication:

MongoDB can provide high availability with replica sets. A replica set consists of two or
more mongo DB instances. Each replica set member may act in the role of the primary
or secondary replica at any time. The primary replica is the main server which interacts
with the client and performs all the read/write operations. The Secondary replicas
maintain a copy of the data of the primary using built-in replication. When a primary
replica fails, the replica set automatically switches over to the secondary and then it
becomes the primary server.
5. Load balancing:
MongoDB uses the concept of sharding to scale horizontally by splitting data across
multiple MongoDB instances. MongoDB can run over multiple servers, balancing the
load and/or duplicating data to keep the system up and running in case of hardware
failure.
6. File storage:
MongoDB can be used as a file system, called GridFS, with load balancing and data
replication features over multiple machines for storing files.
This function, called grid file system, is included with MongoDB drivers. MongoDB
exposes functions for file manipulation and content to developers. GridFS can be
accessed using mongofiles utility or plugins for Nginx and lighttpd. GridFS divides a file
into parts, or chunks, and stores each of those chunks as a separate document.
7. Transactions:
MongoDB claims to support multi-document ACID transactions since the 4.0 release in
DRIEMS
June 2018. This claim was found to not be true as MongoDB violates snapshot isolation.
8. Flexibility:
MongoDB stores data in document format using JSON. It is a schema less document and
maps to native programming language types.
9. Rich query language:

It gives the feature of RDBMS what we are used to with additional features of its own.
Dynamic queries, sorting, secondary indexes, rich updates, easy aggregation, upsets
(update if document exists and insert if it does not) are few RDBMS features and
flexibility and scalability are the additional ones.
10. Ease of use:
It is very easy to install, use, maintain and configure.
11. High performance:
It provides high performance data persistence. It reduces I/O activity on database
system by supporting embedded documents. Use of indexing supports faster queries.
12. High availability:
MongoDB support replication facility called; replica set. Replica set is a group of servers
that maintains same dataset. It provides automatic failover, redundancy and increased
data availability
13. Support for multiple storage engines:
It supports multiple storage engines such as WiredTiger storage engine, MMAPv1
storage engine. It also supports pluggable storage engine API that allows third party to
develop storage engine for MongoDB.

Advantages:

• Schema less: MongoDB is a document database in which one collection holds different
documents. Number of fields, content and size of the document can differ from one
document to another.
• Structure of a single object is clear.
• No complex joins.
• Deep query-ability. MongoDB supports dynamic queries on documents using a
document-based query language that's nearly as powerful as SQL.
• Tuning.
• Ease of scale-out: MongoDB is easy to scale.
DRIEMS
• Conversion/mapping of application objects to database objects not needed.
• Uses internal memory for storing the (windowed) working set, enabling faster access of
data.

Fig. terms and concepts in database


DRIEMS

Fig. Basic queries in Databases

Limitations:

• Joins between two collections because it is difficult to scale out.

• Transaction: because documents are stored in hierarchical manner so it is not possible


to access those items atomically.
• Naming Restrictions
• Database Name Case Sensitivity
• BSON Documents
• BSON Document Size
• Max connection number is hardcoded to 20k.
DRIEMS
• Auto rollback is not for more than 300 MB; more than this manual intervention is
needed.
• To shard a collection, it must be smaller than 256 GB, or else it will likely fail to shard.
• Map / Reduce are single-threaded.
• Map / Reduce cannot output to sharded collections.

CONCLUSION: Hence, we have successfully studied MongoDB.

REFERENCES :

1. https://www.mongodb.com/
2. https://www.youtube.com/user/mongodb
3. https://www.youtube.com/watch?v=ofme2o29ngU
4. https://www.youtube.com/watch?v=1g00SP56iSE
5. https://www.youtube.com/watch?v=bFrO8piASKg

You might also like