0% found this document useful (0 votes)
10 views62 pages

Lab Manual-DBMS

The document is a lab manual for the Database Management System course (BTIT601P) at Nagpur Institute of Technology, outlining the program's vision, mission, educational objectives, and specific outcomes. It details course objectives, practical exercises, and expected competencies for students upon completion. The manual emphasizes the importance of technical knowledge, ethical values, and lifelong learning in the field of Information Technology.

Uploaded by

Devendra Tayade
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)
10 views62 pages

Lab Manual-DBMS

The document is a lab manual for the Database Management System course (BTIT601P) at Nagpur Institute of Technology, outlining the program's vision, mission, educational objectives, and specific outcomes. It details course objectives, practical exercises, and expected competencies for students upon completion. The manual emphasizes the importance of technical knowledge, ethical values, and lifelong learning in the field of Information Technology.

Uploaded by

Devendra Tayade
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/ 62

Lab Manual

For

Database Management System


(BTIT601P)

Department
of
Information Technology
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

---------------------------------------------------------------------------------------------------------------------------------------------

Department of Information Technology


---------------------------------------------------------------------------------------------------------------------------------------------
Vision of the Institute:
Service to the Society by creating Technical & Skilled Manpower through value based Technical
Education

Mission of the Institute:


• To provide quality technical Education to meet the requirement of industries and society.
• To equip students with need based technical skills through continual improvement inTeaching
Learning Processes and research activity.
• To inculcate ethical values for overall holistic development of students.
Vision of the Department
Foster Information Technology graduates by imparting quality technical education through need
based technical skills with ethical values

Mission of the Department


• To provide quality initiatives in skill-based teaching learning process to improve technical
knowledge in Information Technology.
• To enhance intellectual capital of stakeholders by providing research and innovation avenues
and improved industry interaction.
• To increase societal, connect for need based problem through extra-curricular activities.

Program Educational Objectives (PEO):

• PEO1. Our graduates will work on design, operation and practice in electrical field by
addressing intricacies of engineering and technology applications.

• PEO2. Our graduates will work in multidisciplinary fields and adapt to new technologies, new
work environments, pursue additional skills and knowledge leading to professional
development.

• PEO3. Our graduates will progress in their career by demonstrating in practice the technical
and communication skills with an understanding of ethical and social responsibilities.

Program Specific Outcomes (PSO):

PSO1 : Students should understand the overview of Generation, Transmission and distribution of
Electric Power and its control.
PSO2: Student should be able to understand Electrical power system and awareness about various
equipments in the field of Electrical Engineering.
PSO3: Student should be able to use computational techniques to design and analyse Electrical
systems

I
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

--------------------------------------------------------------------------------------------------------------------------------------------

Department of Information Technology


--------------------------------------------------------------------------------------------------------------------------------------------
Program Outcomes (UG)

• PO1. Engineering knowledge: Apply the knowledge of mathematics, science,


engineering fundamentals to the solution of engineering problems.
• PO2. Problem analysis: Identify, formulate, review literature, and analyze complex
engineering problems using first principles of mathematics, natural sciences, and
engineering sciences.
• PO3. 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 safety, societal and environmental
considerations.
• PO4. Conduct problem investigations: Use research-based knowledge including
experimentation, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
• PO5. Modern tool usage: Select, and apply appropriate techniques, resources, and
modern engineering and IT tools for analyzing the engineering activities with an
understanding of the limitations.
• PO6. The engineer, industry and society: Apply contextual knowledge to assess
industrial, societal and safety related issues and understand consequent relevance to the
professional engineering practice.
• PO7. 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.
• PO8. Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
• PO9. Individual and team work: Function effectively as an individual, and as a member
or leader in diverse teams, and in multidisciplinary settings.
• PO10. Communication: Communicate effectively on complex engineering activities such
as, being able to understand and write effective reports, make effective presentations,
and give and receive clear instructions.
• PO11. 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 in multidisciplinary environments.
• PO12. 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.

II
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology

Semester/ Branch: - VI Sem/IT Subject code:- BTIT601P


Subject Name: Database Management System

Course Objectives

SN Objectives
1 To understand the fundamental concepts of Database Management System
2 To acquire the knowledge of database query languages and transaction processing
3 To understand systematic database design approaches

Course Outcomes
At the end of the course students are able to:
SN Objectives
CO1 Analyze and design Database Management System using ER Model
CO2 Apply indexing concepts in database languages
CO3 Implement database queries using database languages
CO4 Create normalized database design using normal forms
CO5 Apply Transaction Management concepts in real-time situations

III
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS: 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id: [email protected] Web: www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


POs, PEO’s & PSO’s
PROGRAMME OUTCOMES
At the end of this program graduate should 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 and analyze real world problems to reach substantial
conclusions using computer science and engineering concepts.
3. Design/development of solutions: Design a system component and process to meet desired
needs.
4. Conduct investigations of complex problems: use research based knowledge and methods
including design, interpretation of data, analysis & synthesis of the information to provide valid
conclusion.
5. Modern tool usage: 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: communicate effectively both in written & oral formats.
7. Environment and sustainability: Understand the impact of professional engineering solutions in
societal and environmental contexts.
8. Ethics: Demonstrate professional skills and ethics.
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: Ability to communicate effectively with peer community and society on
complex software/system engineering activities through unambiguous spoken language,
written reports, presentations.
11. Project management and finance: Ability to apply the knowledge of Engineering and
Management principles to manage projects as a team member or leader in multidisciplinary
teams.
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.

IV
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS: 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id: [email protected] Web: www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

The Program Educational Objectives(PEO’s) are given below:

PEO’s

PEO-1 Competent Professionals with knowledge of Information Technology to pursue


variety of career/higher education.

PEO-2 Capable of adapting to new technologies and constantly upgrade their skills with
an attitude towards lifelong learning.

To create and sustain a community of learning in which students acquire


PEO-3
knowledge and apply in their concerned fields with due consideration for ethical,
ecological, and economic issue.

PEO-4 Capable to understand , analyse, design and create innovative computing products
and solutions for real life problems.

The Program Specific Outcomes(PSO’s) are given below:

PSO’s

PSO-1 Analyse and solve real world problems by applying a combination of hardware and
software .Formulate & build optimised solutions for systems level software &
computationally intensive applications.

PSO-2 Design & model applications for various domains using standard software
engineering practices. Design & develop solutions for distributed processing &
communication.
PSO-3 Graduate will be able to become entrepreneur, zest for higher studies and to
persue career in IT industry.

V
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


2023-24
Subject: Database Management System Subject Code: BTIT601P
Practical List

SN PR Practical Title Page No


Code

1. PR01 To Study Entity Relationship (ER) model & Normalization. 01

2. PR02 To Execute Data Definition Language (DDL), Data Manipulation 07


Language (DML) & Transaction Control Language (TCL) Statements.

3. PR03 SQL Queries- all types of Join, Sub-Query 14

4. PR04 To execute pl/sql stored procedures and functions 17

5. PR05 To study & perform structure of SQL(Select, From And Where). 21

6. PR06 To Execute Various SQL Aggregate Functions 26

7. PR07 To study & perform clauses in SQL 29

8. PR08 Study & Implementation of Various Type Of Integrity Constraints 33

9. PR09 To Study & Execute Views 36

10. PR10 To study pl/sql block 39

11. PR11 Write a PL/SQL block to satisfy some conditions by accepting 43


input from the user.

12. PR12 To understand and Implement Describe Statement which can be 46


used to view the structure of the table created by the
user.(Virtual Lab)

13. PR13 Data Manipulation Language(Virtual Lab) 48

14. PR14 Database Trigger 50

15. PR15 Database Connectivity 52

Note : Minimum 10 practicals to be executed...

Prof. Pankaj Sonewane Dr. M. Makesar


Practical Incharge HoD
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


PRACTICAL NO. 01

Aim: To study Entity Relationship (ER) model & Normalization.

Theory:
The entity-relationship (E-R) data model is based on a perception of a real world that consists of a set of basic
objects called entities, and of relationships among these objects. The model is intended primarily for the database-
design process. It was developed to facilitate database design by allowing the specification of an enterprise
schema. Such a schema represents the overall logical structure of the database. This overall structure can be
expressed graphically by an E-R diagram.
• An entity is an object that exists in the real world and is distinguishable from other objects. We
express the distinction by associating with each entity a set of attributes that describes the object.
• A relationship is an association among several entities. The collection of all entities of the same
type is an entity set, and the collection of all relationships of the same type is a relationship set.

Entity-Relationship Diagram

As we saw briefly in Section 1.4, an E-R diagram can express the overall logical structure of a database
graphically. E-R diagrams are simple and clear qualities that may well account in large part for the
widespread use of the E-R model. Such a diagram consists of the following major components:

• Rectangles, which represent entity sets

• Ellipses, which represent attributes

• Diamonds, which represent relationship sets

• Lines, which link attributes to entity sets and entity sets to relationship sets

• Double ellipses, which represent multivalued attributes

• Dashed ellipses, which denote derived attributes

• Double lines, which indicate total participation of an entity in a relation-ship set

• Double rectangles, which represent weak entity sets

The relationship set borrower may be many-to-many, one-to-many, many-to-one, or one-to-one. To


distinguish among these types, we draw either a directed line (→) or an undirected line ( — ) between the
relationship set and the entity set in question.

An attribute, as used in the E-R model, can be characterized by the following attribute Types:
1) Simple and composite attributes
2) Single-valued and multi valued attributes
3) Derived attribute.

P a g e 1 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology

Fig 1: E-R diagram corresponding to customers and loans.

The following major components are use to create E-R diagram.

1. Rectangles, which represent entity sets


2. Ellipses, which represent attributes
3. Diamonds, which represent relationship sets
4. Lines, which link attributes to entity sets and entity sets to relationship sets
5. Double ellipses, which represent multi valued attributes
6. Dashed ellipses, which denote derived attributes
7. Double lines, which indicate total participation of an entity in a relationship set.
8. Double rectangles, which represent weak entity sets

P a g e 2 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


Fig 2: E-R diagram with composite, multi-valued, and derived attributes.

Mapping cardinalities:
Mapping cardinalities express the number of entities to which another entity can be associated
via a relationship set. For a binary relationship set R between entity sets A and B, the mapping
cardinality must be one of the following:
1) One to one. An entity in A is associated with at most one entity in B, and an entity in B is associated
with at most one entity in A.
2) One to many. An entity in A is associated with any number (zero or more) of entities in B. An
entity in B, however, can be associated with at most one entity in A.
3) Many to one. An entity in A is associated with at most one entity in B. An entity in B, however,
can be associated with any number (zero or more) of entities in A.

4) Many to many. An entity in A is associated with any number (zero or more) of entities in B, and
an entity in B is associated with any number (zero or more) of entities in A.

Fig. 3Mapping cardinalities. (a) One to one. (b) One to many.

Fig.3 Mapping cardinalities. (c) Many to one. (d) Many to many.

P a g e 3 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology

• A super key of an entity set is a set of one or more attributes that, taken collectively, allows us to
identify uniquely an entity in the entity set. We choose a minimal super key for each entity set
from among its super keys; the minimal super key is termed the entity set’s primary key.
Similarly, a relationship set is a set of one or more attributes that, taken collectively, allows us to
identify uniquely a relationship in the relationship set. Likewise, we choose a minimal superkey
for each relationship set from among its superkeys; this is the relationship set’s primary key.

• An entity set that does not have sufficient attributes to form a primary key is termed a weak entity
set. An entity set that has a primary key is termed a strong entity set.

Fig.4: E-R diagram with a weak entity set.

• Specialization and generalization define a containment relationship between a higher-level entity set
and one or more lower-level entity sets. Specialization is the result of taking a subset of a higher-level
entity set to form a lower level entity set. Generalization is the result of taking the union of two or more
disjoint (lower-level) entity sets to produce a higher-level entity set. The attributes of higher-level entity
sets are inherited by lower-level entity sets.

P a g e 4 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


Fig.5: Specialization and generalization.

• Aggregation is an abstraction in which relationship sets (along with their associated entity sets)
are treated as higher-level entity sets, and can participate in relationships.

Fig.6: E-R diagram with aggregation.

CONCLUSION: Thus, we have studied ER-Diagram.

P a g e 5 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology

VIVA-QUESTIONS-:

1. What is ER diagram?
2. What are major components in ER diagram?
3. What do you mean by specialization and generalization?
4. What is mapping cardinalities?
5. Explain various types of attributes?

P a g e 6 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


PRACTICAL NO. 02
AIM : To Execute Data Definition Language (DDL), Data Manipulation Language (DML)
& Transaction Control Language (TCL) Statements

THEORY:-
SQL statements are divided into two major categories:
I)Data Definition Language(DDL)
II)Data Manipulation Language(DML)
DDL statements are used to build and modify the structure of your tables and other objects in the database.

1) CREATE TABLE
The SQL CREATE TABLE statement is used to create a new table.
Syntax:

Basic syntax of CREATE TABLE statement is as follows:

CREATE TABLE table_name


(attribute1 datatype,
attribute2 datatype,
attribute3 datatype,
.....
attributeN datatype,
PRIMARY KEY( one or more columns )
);

CREATE TABLE is the keyword telling the database system what you want to do. In this case,
you want to create a new table. The unique name or identifier for the table follows the CREATE TABLE
statement. Then in brackets comes the list defining each column in the table and what sort of data type it
is. The syntax becomes clearer with an example below.

Query 1:Following is an example, which creates a PRODUCT table with P_ID as primary key
and NOT NULL are the constraints showing that these fields cannot be NULL while creating records in
this table:

CREATE TABLE products


(p_id int not null,
P_name varchar (20) not null,
qnt int not null,
price decimal (6, 2),
primary key (p_id)
);

mysql> CREATE TABLE products


-> (p_id int not null,
-> P_name varchar (20) not null,
-> qnt int not null,
-> price decimal (6, 2),

P a g e 7 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


-> primary key (p_id)
-> );
Query OK, 0 rows affected (0.70 sec)
Output: - Table created

Query 2: Write a query to create a table name Department having did as primary key,pid as foreign key
and different columns are dname,location.

CREATE TABLE department


(did int not null,
dname varchar (20) not null,
pid int not null,
loc varchar(30),
primary key (did),
foreign key (pid) references products (p_id));

Query 3: Describe products and department table.

mysql> desc PRODUCTS;


+--------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+--------------+------+-----+---------+-------+
| p_id | int(11) | NO | PRI | NULL | |
| P_name | varchar(20) | NO | | NULL | |
| qnt | int(11) | NO | | NULL | |
| price | decimal(6,2) | YES | | NULL | |
+--------+--------------+------+-----+---------+-------+
4 rows in set (0.03 sec)

2) DROP TABLE

The SQL DROP TABLE statement is used to remove a table definition and all data,
indexes, triggers, constraints, and permission specifications for that table.

NOTE: You have to be careful while using this command because once a table is deleted then all the
information available in the table would also be lost forever.

Syntax:

syntax of DROP TABLE statement is as follows:

DROP TABLE table_name;

Query 4: Drop table products;


mysql> DROP TABLE products;
Query OK, 0 rows affected (0.19 sec)

Output : Table dropped.

P a g e 8 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


3) ALTER TABLE

ALTER TABLE statement will allow you to add new column or constraint, modify existing
column or constraint, and drop existing constraint after the table is created.

Query 5: The following will add a middle name column to the customers table.

Mysql> ALTER TABLE products


ADD P_description VARCHAR (20);

Output : Table altered.

MYSQL> desc products;

Output :

mysql> desc products;


+---------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+-------+
| p_id | int(11) | NO | PRI | NULL | |
| P_name | varchar(20) | NO | | NULL | |
| qnt | int(11) | NO | | NULL | |
| price | decimal(6,2) | YES | | NULL | |
| P_description | varchar(20) | YES | | NULL | |
+---------------+--------------+------+-----+---------+-------+
5 rows in set (0.01 sec)

Query 6:To modify the column p_id in the products table, the query would be like

mysql>
ALTER TABLE products
MODIFY p_id int(20);

Output : Table altered;

Query 7:To modify the column qnt in the products table, the query would be like

mysql>
ALTER TABLE products
MODIFY qnt int(15);

Output : Table altered;

P a g e 9 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology

mysql> desc products;

mysql> desc products;


+---------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+-------+
| p_id | int(10) | NO | PRI | 0 | |
| P_name | varchar(20) | NO | | NULL | |
| qnt | int(15) | YES | | NULL | |
| price | decimal(6,2) | YES | | NULL | |
| P_description | varchar(20) | YES | | NULL | |
+---------------+--------------+------+-----+---------+-------+
5 rows in set (0.00 sec)

Query 8 : Add date column in department table.


mysql> alter table department add ddate date;
Query OK, 0 rows affected (0.84 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc department;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| did | int(11) | NO | PRI | NULL | |
| dname | varchar(20) | NO | | NULL | |
| pid | int(11) | NO | MUL | NULL | |
| loc | varchar(30) | YES | | NULL | |
| ddate | date | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
5 rows in set (0.08 sec)
Query: Change p_id to pid.
mysql> alter table products change p_id pid int(10);
Query OK, 0 rows affected (0.69 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> select * from products;
+-----+---------+------+-------+---------------+
| pid | P_name | qnt | price | P_description |
+-----+---------+------+-------+---------------+
| 1 | soap | 100 | 30.00 | bathspoap |
| 2 | biscuit | 200 | 30.00 | bathspoap |
| 3 | cake | 300 | 30.00 | bathspoap |
| 4 | soap | 100 | 30.00 | bathspoap |
| 5|A | 200 | 30.00 | aa |
+-----+---------+------+-------+---------------+
5 rows in set (0.00 sec)
Query 9: mysql> insert into department values(3,'A',1,'ngp','2015/09/21');
Query OK, 1 row affected (0.05 sec)
mysql> select * from department;
+-----+-------+-----+------+------------+
| did | dname | pid | loc | ddate |
+-----+-------+-----+------+------------+
| 1 | A | 1 | ngp | 0000-00-00 |
| 2 | A | 1 | ngp | 2016-08-05 |

P a g e 10 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


| 3 | A | 1 | ngp | 2015-09-21 |
+-----+-------+-----+------+------------+
3 rows in set (0.00 sec)

DML COMMANDS:

4) INSERT INTO

INSERT INTO Statement is used to add new rows of data to a table in the database.
Syntax:
INSERT INTO statement as follows:
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)]
VALUES (value1, value2, value3,...valueN);

Or

INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);

Example:

Following statements would create records in PRODUCTS table:

Query 10: Insert values into product table

mysql> insert into products values(1,'soap',100,30.00,'bathspoap');


Query OK, 1 row affected (0.06 sec)

Output :

1 row created.

mysql> select * from products;

Output:

+------+--------+------+-------+---------------+
| p_id | P_name | qnt | price | P_description |
+------+--------+------+-------+---------------+
| 1 | soap | 100 | 30.00 | bathspoap |
+------+--------+------+-------+---------------+
1 row in set (0.00 sec)

Query 11: Inserting multiple rows

mysql> insert into products values(4,'soap',100,30.00,'bathspoap'),


-> (5,'A',200,30,'aa');
Query OK, 2 rows affected (0.06 sec)
Records: 2 Duplicates: 0 Warnings: 0

P a g e 11 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


mysql> select * from products;
+------+---------+------+-------+---------------+
| p_id | P_name | qnt | price | P_description |
+------+---------+------+-------+---------------+
| 1 | soap | 100 | 30.00 | bathspoap |
| 2 | biscuit | 200 | 30.00 | bathspoap |
| 3 | cake | 300 | 30.00 | bathspoap |
| 4 | soap | 100 | 30.00 | bathspoap |
| 5|A | 200 | 30.00 | aa |
+------+---------+------+-------+---------------+
5 rows in set (0.00 sec)

5) SELECT COMMAND

mysql> select * from products;

Output:

+------+--------+------+-------+---------------+
| p_id | P_name | qnt | price | P_description |
+------+--------+------+-------+---------------+
| 1 | soap | 100 | 30.00 | bathspoap |
+------+--------+------+-------+---------------+
1 row in set (0.00 sec)

6) UPDATE COMMAND

It is used to modify data in a table.

Syntax: UPDATE table_name SET column=value, column1=value1,... WHERE


someColumn=someValue

Query 12: Update product table put qnt =200 having product id =1.

mysql> update products set qnt = 200 where p_id=1;

Output:

Query OK, 1 row affected (0.08 sec)


Rows matched: 1 Changed: 1 Warnings: 0

mysql> select * from products;


+------+--------+------+-------+---------------+
| p_id | P_name | qnt | price | P_description |
+------+--------+------+-------+---------------+
| 1 | soap | 200 | 30.00 | bathspoap |
+------+--------+------+-------+---------------+
1 row in set (0.00 sec)

Query 13: Update product table set product name = file having product name = soap.

P a g e 12 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


7) DELETE COMMAND

Delete from statement is used to delete data from table.

Syntax:
DELETE FROM tableName WHERE someColumn = someValue

Query 14: Delete product name from product table having product name is soap
mysql> delete from products where p_name='soap';
Query OK, 1 row affected (0.06 sec)

mysql> select * from products;


Empty set (0.00 sec)

Conclusion: Thus we have executed DDL and DML statements.

Viva Questions:
1) What are different DDL and DML commands? Explain.
2) Explain difference between Drop, Delete and Truncate statement.
3) Explain update and Insert command.
4) Give the syntax of Create table.
5) How to insert multiple rows.

P a g e 13 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


PRACTICAL NO : 03

AIM : - TO EXECUTE VARIOUS TYPE OF JOINS.


THEORY:
Joins:
Using SQL Joins, you can retrieve data more than one table or views using the keys
[Primary & foreign] references.

The syntax for joining multiple tables is as follows:

SELECT column,

FROM table1, table2

WHERE table1, join_ column= table2,join _column;

The SELECT statement contains the columns to retrieve and may come from two or more
tables. If the selected column exists both tables, specify the table [table. column]. You have to
specify the tables in the FROM clause and the join condition is done in the WHERE clause. In the
WHERE clause, you need the table name and dot followed by column name. The column name in
the WHERE clause is the joint column [keys]. AND & OR also normally used to make multiple joint
conditions,
Equality Joins
Equality Joins happens when two table are joined based on values in one table being
equal to values in anther table. For example, product table and inventory table may have joint
column of product_id as it show in the following tables.

Product Table
Product ID Name Description Price Cost
100000000 Printer Inkjet 300 color Printer 120 80
100000001 Printer 1220XI Inkjet Printer 200 130
100000002 Printer Photo 890 Inkjet Printer 250 200
100000003 Printer Photo 890 Inkjet Printer 300 270
Inventory Table
Product ID qty_on_hand qty_on_order min_req mx_req
100000000 20 0 10 25
100000001 10 5 2 15
100000002 2 10 1 12
100000003 1 15 1 15

P a g e 14 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


The query to perform equality joins might look like this:

SELECT product. product_id, name, price, qty_on_hand, qty_on_order FROM


product, inventory
WHERE product. product_id = inventory. product_id

Product table is specified in the SELECT statements to issue the product the product_id and the
reason is, product_id exists both tables and if you don’t specified which table to select from, you
will receive ambiguous error. The query will select all the selected rows from both tables since
there is always product_id equal to product_id in the other table.

Outer Joins

Outer Joins is joint condition where all the rows of a table are selected along with then matching
rows in the other table. For example you might want select all your customers along with their
orders if they have orders. + sign is used in the WHERE clause beside the child table within
parentheses. The following is SQL joint statements to select every customer in the customer table
along with their orders if they have orders and if they.

SELECT customer. customer_id, firstname, lastname, item_id, qty_ordered, price FROM


customer, order
WHERE customer. customer_id = order. customer_id (+);
Or
SELECT customer. customer_id, firstname, lastname, item_id, qty_ordered, price FROM
customer left outer join order on customer. customer_id = order. customer_id

Self Joins

Self Joins is joint of table by itself. For example, if you want retrieve customers whom
ordered same products twice or more assuming there is num_order column that keeps track the
number of orders customers made. Here is how you would do this using a self joins:

SELECT 01. customer_id

FROM order 01, order 02

WHERE 01. item_id = 02. item_id AND 01.num_order>1;

This query simply created two table alias, 01 and 02 which represents two copies of the table
order then compares if item_id exists both table when order is placed two or more times by a
customer.

Query1: Write a query to select product name, price of the product and department name

P a g e 15 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


mysql> select products.pid,p_name,price,dname from products,department where pro
ducts.pid=department.pid(+);
+-----+--------+-------+-------+
| pid | p_name | price | dname |
+-----+--------+-------+-------+
| 1 | soap | 30.00 | A |
| 1 | soap | 30.00 | A |
| 1 | soap | 30.00 | A |
+-----+--------+-------+-------+
3 rows in set (0.03 sec)

Query2: : Write a query to select product name,quantity of the product and department
location name having product id is equql to 1.

Query3: Write a query to display product id,name,price and department name of that product
also show product ids that are not present in department table

mysql> select products.pid,p_name,price,dname from products left outer join department on


products.pid=department.pid;

+-----+---------+-------+-------+
| pid | p_name | price | dname |
+-----+---------+-------+-------+
| 1 | soap | 30.00 | A |
| 1 | soap | 30.00 | A |
| 1 | soap | 30.00 | A |
| 2 | biscuit | 30.00 | NULL |
| 3 | cake | 30.00 | NULL |
| 4 | soap | 30.00 | NULL |
| 5|A | 30.00 | NULL |
| 6 | abc | NULL | NULL |
+-----+---------+-------+-------+
8 rows in set (0.01 sec)

Query 4: Write a query to display the use of right outer join on product and department table.

Viva Questions:

1) What is the need of joins.


2) What are different types of joins.
3) What is the difference between left outer join and right outer join.
4) What is equi joins.
5) Explain the use of self joins.

CONCLUSION: We have executed Various types of JOINS successfully.

P a g e 16 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


PRACTICAL NO: 04

AIM : - TO STUDY AND EXECUTE PL/SQL STORED PROCEDURES AND FUNCTIONS


THEORY:
Stored procedure:
A stored procedure is a named PL/SQL block which performs one or more specific task. This is
similar to a procedure in other programming languages.
A procedure has a header and a body. The header consists of the name of the procedure and
the parameters or variables passed to the procedure. The body consists or declaration section,
execution section and exception section similar to a general PL/SQL Block.
A procedure is similar to an anonymous PL/SQL Block but it is named for repeated usage.

Procedures: Passing Parameters


We can pass parameters to procedures in three ways.
1) IN-parameters
2) OUT-parameters
3) IN OUT-parameters
A procedure may or may not return any value.

Syntax:

CREATE [OR REPLACE] PROCEDURE procedure_name [(parameter_name [IN | OUT | IN OUT]


type [, ...])]
{IS | AS}
BEGIN
< procedure_body >
END;

Query 1: Write a query to create stored procedure.

mysql> DELIMITER //
mysql> CREATE PROCEDURE Country_procedure(IN countryName VARCHAR(255))
-> BEGIN
-> SELECT *
-> FROM country
-> WHERE name = countryName;
-> END //
Query OK, 0 rows affected (0.41 sec)

mysql> call country_procedure('India');


+------+-------+-----------+---------------------------+-------------+----------
-+------------+----------------+-----------+-----------+--------------+---------
---------+--------------------------+---------+-------+

P a g e 17 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


| Code | Name | Continent | Region | SurfaceArea | IndepYear
| Population | LifeExpectancy | GNP | GNPOld | LocalName | Governme
ntForm | HeadOfState | Capital | Code2 |
+------+-------+-----------+---------------------------+-------------+----------
-+------------+----------------+-----------+-----------+--------------+---------
---------+--------------------------+---------+-------+
| IND | India | Asia | Southern and Central Asia | 3287263.00 | 1947
| 1013662000 | 62.5 | 447114.00 | 430572.00 | Bharat/India | Federal
Republic | Kocheril Raman Narayanan | 1109 | IN |
+------+-------+-----------+---------------------------+-------------+----------
-+------------+----------------+-----------+-----------+--------------+---------
---------+--------------------------+---------+-------+
1 row in set (0.13 sec)

Query OK, 0 rows affected (0.20 sec)

Functions:

A function is a named PL/SQL Block which is similar to a procedure. The major difference
between a procedure and a function is, a function must always return a value, but a procedure
may or may not return a value.

CREATE [OR REPLACE] FUNCTION function_name [parameters] RETURN return_datatype;


IS
Declaration_section
BEGIN
Execution_section
Return return_variable;
EXCEPTION
exception section
Return return_variable;
END;

Query2: Write a query to create a function.

DELIMITER //
CREATE FUNCTION PopulationLevel(population int) RETURNS VARCHAR(10)
BEGIN
DECLARE lvl varchar(10);
IF population > 50000 THEN
SET lvl = 'HIGH';
ELSEIF (population <= 50000 AND population >= 10000) THEN
SET lvl = 'MEDIUM';
ELSEIF population < 10000 THEN
SET lvl = 'LOW';

P a g e 18 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


END IF;
RETURN (lvl);
END //

mysql> select name, populationLevel(population) from country;


+----------------------------------------------+-----------------------------+
| name | populationLevel(population) |
+----------------------------------------------+-----------------------------+
| Aruba | HIGH |
| Afghanistan | HIGH |
| Angola | HIGH |
| Anguilla | LOW |
| Albania | HIGH |
| Andorra | HIGH |
| Netherlands Antilles | HIGH |
| United Arab Emirates | HIGH |
| Argentina | HIGH |
| Armenia | HIGH |
| American Samoa | HIGH |
| Antarctica | LOW |
| French Southern territories | LOW |
| Antigua and Barbuda | HIGH |
| Australia | HIGH |
| Austria | HIGH |
| Azerbaijan | HIGH |
| Burundi | HIGH |
| Belgium | HIGH |
| Benin | HIGH |
| Burkina Faso | HIGH |
| Bangladesh | HIGH |
| Bulgaria | HIGH |
| Bahrain | HIGH |
| Bahamas | HIGH |
| Bosnia and Herzegovina | HIGH |
| Belarus | HIGH |
| Belize | HIGH |
| Bermuda | HIGH |
| Bolivia | HIGH |
| Brazil | HIGH |
| Barbados | HIGH |
| Brunei | HIGH |
| Bhutan | HIGH |
| Bouvet Island | LOW |
| Botswana | HIGH |
| Central African Republic | HIGH |

P a g e 19 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


| Canada | HIGH |
| Cocos (Keeling) Islands | LOW |
| Switzerland | HIGH |
| Chile | HIGH |
| China | HIGH |
| Côte d’Ivoire | HIGH |
| Cameroon | HIGH |
| Congo, The Democratic Republic of the | HIGH |
| Congo | HIGH |
| Cook Islands | MEDIUM |

CONCLUSION: We have studied and executed Pl/Sql stored procedures and functions.

Viva Questions:

1) Explain the difference between stored procedures and functions.


2) What is Pl/Sql.
3) Give the difference between sql and Pl/sql.
4) Give advantages of stored procedures.

P a g e 20 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


PRACTICAL NO : 05

AIM : To study & perform structure of SQL(Select, From And Where).

THEORY:
SELECT,FROM AND WHERE CLAUSES
The basic structure of an SQL expression consists of three clauses: select, from and where.
• The select clause corresponds to the projection operation of the relational algebra.It is
used to list the attributes desired in the result of a query.
• The from clause corresponds to the Cartesian-product operation of the relational algebra.
It lists the relations to be scanned in the evaluation of the expression.
• The where clause corresponds to the selection predicate of the relational algebra.It
consists of a predicate involving attributes of the relations that appear in the from clause.

A typical SQL query has the form


select A1, A2, . . .,An
from r1, r2, . . . , rm
where P
Each represents,
Ai ->attribute
ri -> relation
P ->predicate.
The query is equivalent to the relational-algebra expression,

SQL forms the Cartesian product of the relations named in the from clause, performs a relational-
algebra selection using the where clause predicate, and then projects the result onto the
attributes of the select clause.

Programs:
1) Process to show the database.

P a g e 21 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


Mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sakila |
| test |
| world |
+--------------------+
6 rows in set (0.02 sec)

2) To select particular database.


mysql> use world;
Database changed
3) To show all the tables in database world.
mysql> show tables;
+-----------------+
| Tables_in_world |
+-----------------+
| city |
| country |
| countrylanguage |
+-----------------+
3 rows in set (0.02 sec)
4) To describe particular table
mysql> desc city;
+-------------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |

P a g e 22 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


+-------------+----------+------+-----+---------+----------------+
| ID | int(11) | NO | PRI | NULL | auto_increment |
| Name | char(35) | NO | | | |
| CountryCode | char(3) | NO | | | |
| District | char(20) | NO | | | |
| Population | int(11) | NO | |0 | |
+-------------+----------+------+-----+---------+----------------+
5 rows in set (0.00 sec)

5) Write a query to select id from city


mysql> select id from city;

| 4071 |
| 4072 |
| 4073 |
| 4074 |
| 4075 |
| 4076 |
| 4077 |
| 4078 |
| 4079 |
+------+
4079 rows in set (0.05 sec)
6) Write a query to select distinct name from city
mysql> select distinct name from city;
| Odessa |
| Carson |
| Charleston |
| Charlotte Amalie |
| Harare |

P a g e 23 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


| Bulawayo |
| Chitungwiza |
| Mount Darwin |
| Mutare |
| Gweru |
| Gaza |
| Khan Yunis |
| Hebron |
| Jabaliya |
| Nablus |
| Rafah |
+--------------------------------------+
4001 rows in set (0.03 sec)
7) Write a query to select all values from city where name in 'Odessa' ,'Gaza'
mysql> select * from city where name in ('Odessa' ,'Gaza');
+------+--------+-------------+----------+------------+
| ID | Name | CountryCode | District | Population |
+------+--------+-------------+----------+------------+
| 4064 | Odessa | USA | Texas | 89293 |
| 4074 | Gaza | PSE | Gaza | 353632 |
+------+--------+-------------+----------+------------+
2 rows in set (0.05 sec)
8) Write a query to select name and id from city where district is Texas.
mysql> select name,id from city where District ='Texas';
+----------------+------+
| name | id |
+----------------+------+
| Houston | 3796 |
| Dallas | 3800 |
| San Antonio | 3801 |

P a g e 24 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


| Austin | 3808 |
| El Paso | 3815 |
| Fort Worth | 3819 |
| Arlington | 3845 |
| Corpus Christi | 3852 |
| Plano | 3870 |
| Garland | 3874 |
| Lubbock | 3882 |
| Irving | 3892 |
| Laredo | 3907 |
| Amarillo | 3911 |
| Brownsville | 3945 |
| Pasadena | 3953 |
| Grand Prairie | 3962 |
| Mesquite | 3968 |
| Abilene | 3989 |
| Beaumont | 3992 |
| Waco | 3993 |
| Carrollton | 4002 |
| McAllen | 4013 |
| Midland | 4039 |
+----------------+------+
26 rows in set (0.03 sec)

CONCLUSION: Thus we have studied and performed select from where clause.

Viva-questions-:
1) How to avoid duplicate values from table.
2) What is the way to select all the rows from the table.
3) Explain Select,From, Where clause.
4) What is the need of where clause in query.

P a g e 25 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


PRACTICAL NO : 06

AIM : - To Execute Various SQL Aggregate Functions


THEORY:-
Aggregate functions are functions that take a collection (a set or multi-set) of values as
input and return a single value. SQL offers five built-in aggregate functions:
✓ Average: avg
✓ Minimum: min
✓ Maximum: max
✓ Total: sum
✓ Count: count

AVG FUNCTION: The avg function computes the column’s average value.The input to avg function
is a collection of number.

mysql> select * from products;


+-----+---------+------+-------+---------------+
| pid | P_name | qnt | price | P_description |
+-----+---------+------+-------+---------------+
| 1 | soap | 100 | 30.00 | bathspoap |
| 2 | biscuit | 200 | 30.00 | bathspoap |
| 3 | cake | 300 | 30.00 | bathspoap |
| 4 | soap | 100 | 30.00 | bathspoap |
| 5|A | 200 | 30.00 | aa |
+-----+---------+------+-------+---------------+
5 rows in set (0.06 sec)

mysql> select avg(qnt) from products;


+----------+
| avg(qnt) |
+----------+
| 180.0000 |
+----------+
1 row in set (0.02 sec)

MIN & MAX FUNCTION: The min & max function return the minimum and maximum values for
the specified columns.
mysql> select min(qnt) from products;
+----------+
| min(qnt) |
+----------+
| 100 |
+----------+
1 row in set (0.02 sec)

P a g e 26 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


mysql> select max(qnt) from products;
+----------+
| max(qnt) |
+----------+
| 300 |
+----------+
1 row in set (0.00 sec)

SUM FUNCTION: The sum function computes the column’s total value.input to this function must
be a collection of numbers.

mysql> select sum(qnt) from products;


+----------+
| sum(qnt) |
+----------+
| 900 |
+----------+
1 row in set (0.02 sec)

COUNT FUNCTION: The count function counts the number of rows.

mysql> select count(*) from products;


+----------+
| count(*) |
+----------+
| 5|
+----------+
1 row in set (0.00 sec)

Queries:

1)Write a query to select average quantity for each product.

mysql> select avg(qnt),p_name from products group by (p_name);


+----------+---------+
| avg(qnt) | p_name |
+----------+---------+
| 200.0000 | A |
| 200.0000 | biscuit |
| 300.0000 | cake |
| 100.0000 | soap |
+----------+---------+
4 rows in set (0.17 sec)

P a g e 27 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


2) Write a query to display maximum quatity and product name.

3) Write a query to display minimum quatity and product name.

4) Write a query to display sum of quantities for product soap use having clause.

5)Display product id,product name and sum of quantities for each product

CONCLUSION: We have executed SQL aggregate functions successfully.

Viva Questions:

1) What are different SQL aggregate functions.


2) Explain the use of group by clause.
3) What is the difference between where and having clause.
4) Explain having clause.

P a g e 28 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


PRACTICAL NO : 07

AIM : To study & perform clauses in SQL.

THEORY:
Clauses

There is following clauses use in database.

1) Between/Not Between
2) Is Null/Not Null
3) Order by
4) Group by
5) Having

1) Between/Not Between: SQL includes a between comparison operator to simplify where


clauses that specify a value be less than or equal to some value and greater than or equal to some
other value.

Query: To find products and their respective quantity whose quantity is between 100 and 300
mysql> select p_name,qnt from products where qnt between 100 and 300;
+---------+------+
| p_name | qnt |
+---------+------+
| soap | 100 |
| biscuit | 200 |
| cake | 300 |
| soap | 100 |
|A | 200 |
+---------+------+
5 rows in set (0.00 sec)

2) Is Null/Not Null: SQL allows the use of null values to indicate the absence of information about
the value of an attribute. The predicate Not Null tests for the absence of null values.

Query: To select information of those products who don’t have price.


mysql> select pid from products where price is null;
+-----+
| pid |
+-----+
| 6|
+-----+
1 row in set (0.02 sec)

P a g e 29 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


Query: select pid from products where price is not null

mysql> select pid from products where price is not null;


+-----+
| pid |
+-----+
| 1|
| 2|
| 3|
| 4|
| 5|
+-----+
5 rows in set (0.00 sec)

3) Order By: Arrange all records in the specific order called ascending or descending.
Syntax:
Select column name.. from table name ORDER By column name, column name .. [DESC];

Query: Arrange records of product table in ascending order of product name.


mysql> select * from products order by p_name
-> ;
+-----+---------+------+-------+---------------+
| pid | P_name | qnt | price | P_description |
+-----+---------+------+-------+---------------+
| 5|A | 200 | 30.00 | aa |
| 6 | abc | 400 | NULL | abc |
| 2 | biscuit | 200 | 30.00 | bathspoap |
| 3 | cake | 300 | 30.00 | bathspoap |
| 1 | soap | 100 | 30.00 | bathspoap |
| 4 | soap | 100 | 30.00 | bathspoap |
+-----+---------+------+-------+---------------+
6 rows in set (0.03 sec)
Query: Arrange records of product table in descending order of product name.

mysql> select * from products order by p_name desc;


+-----+---------+------+-------+---------------+
| pid | P_name | qnt | price | P_description |
+-----+---------+------+-------+---------------+
| 1 | soap | 100 | 30.00 | bathspoap |
| 4 | soap | 100 | 30.00 | bathspoap |
| 3 | cake | 300 | 30.00 | bathspoap |
| 2 | biscuit | 200 | 30.00 | bathspoap |
| 6 | abc | 400 | NULL | abc |
| 5|A | 200 | 30.00 | aa |
+-----+---------+------+-------+---------------+
P a g e 30 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


6 rows in set (0.00 sec)
(Using Multiple Attribute)

Query: Arrange records of product table in ascending order of quantity and product name

mysql> select * from products order by qnt,p_name;


+-----+---------+------+-------+---------------+
| pid | P_name | qnt | price | P_description |
+-----+---------+------+-------+---------------+
| 1 | soap | 100 | 30.00 | bathspoap |
| 4 | soap | 100 | 30.00 | bathspoap |
| 5|A | 200 | 30.00 | aa |
| 2 | biscuit | 200 | 30.00 | bathspoap |
| 3 | cake | 300 | 30.00 | bathspoap |
| 6 | abc | 400 | NULL | abc |
+-----+---------+------+-------+---------------+
6 rows in set (0.00 sec)

Query: Arrange records of product table in ascending order of quantity without writing column
name in query.

mysql> select * from products order by 3;


+-----+---------+------+-------+---------------+
| pid | P_name | qnt | price | P_description |
+-----+---------+------+-------+---------------+
| 1 | soap | 100 | 30.00 | bathspoap |
| 4 | soap | 100 | 30.00 | bathspoap |
| 2 | biscuit | 200 | 30.00 | bathspoap |
| 5|A | 200 | 30.00 | aa |
| 3 | cake | 300 | 30.00 | bathspoap |
| 6 | abc | 400 | NULL | abc |
+-----+---------+------+-------+---------------+
6 rows in set (0.00 sec)

Query: Arrange records of product table in descending order of quantity without writing column
name in query.

4) Group By: This class logically group the records into the single unit. Group by clause always use
with aggregate functions. Group by class collects all items in a group.
Syntax :
Select column_name, Agg function from table_name GROUP BY column name;

Query: Display sum and average of quatities for each product

mysql> select P_name,avg(qnt),sum(qnt) from products group by p_name;

P a g e 31 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


+---------+----------+----------+
| P_name | avg(qnt) | sum(qnt) |
+---------+----------+----------+
|A | 200.0000 | 200 |
| abc | 400.0000 | 400 |
| biscuit | 200.0000 | 200 |
| cake | 300.0000 | 300 |
| soap | 100.0000 | 200 |
+---------+----------+----------+
5 rows in set (0.00 sec)

5) Having: This clause always use with group by clause that provide conditions with the string.
Having clause related with the string data.
Syntax: Select column name, Agg function from table name GROUP BY column name having
[Condition];

Query: Display sum and average of quatities for product having product id =1 or 2

mysql> select pid,avg(qnt),sum(qnt) from products group by p_name having pid=1 o


r pid=2;
+-----+----------+----------+
| pid | avg(qnt) | sum(qnt) |
+-----+----------+----------+
| 2 | 200.0000 | 200 |
| 1 | 100.0000 | 200 |
+-----+----------+----------+
2 rows in set (0.02 sec)

CONCLUSION: Thus, we have studied and performed clauses in SQL.

Viva Questions:

1) How to insert null values into database.


2) Can we use order by and group by clause together? Explain with example.
3) Illustrate the use of where and group by in same query.
4) What is the use of order by 1 clause.

P a g e 32 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


PRACTICAL NO : 08

AIM : - Study & Implementation of Various Type Of Integrity Constraints.

THEORY:

SQL Integrity Constraints


Integrity Constraints are used to apply business rules for the database tables.
The constraints available in SQL are Foreign Key, Not Null, Unique, Check. Constraints can be
defined in two ways
1) The constraints can be specified immediately after the column definition. This is called
column-level definition.
2) The constraints can be specified after all the columns are defined. This is called table-level
definition.
1) SQL Primary key:
This constraint defines a column or combination of columns which uniquely identifies each
row in the table.
Syntax to define a Primary key at column level:
column name datatype [CONSTRAINT constraint_name] PRIMARY KEY
Syntax to define a Primary key at table level:

[CONSTRAINT constraint_name] PRIMARY KEY column_name1,column_name2,..)

For Example: To create an employee table with Primary Key constraint, the query would be
like.

CREATE TABLE employee( id int(5) PRIMARY KEY, name char(20), dept char(10), age int(2),
salary int(10), location char(10) );

Primary Key at column level:

CREATE TABLE employee1( id int(5), name char(20),dept char(10), age int(2),salary


int(10),location char(10),CONSTRAINT mp_id_pk PRIMARY KEY (id));

Primary Key at table level:

SQL> CREATE TABLE employee2 ( id int (5) NOT NULL, name char(20),dept char(10),age
int(2),salary int(10),location char(10));

SQL> ALTER TABLE employee2 ADD CONSTRAINT PK_EMPLOYEE_ID1 PRIMARY KEY (id);

P a g e 33 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


2) SQL Foreign key or Referential Integrity :
This constraint identifies any column referencing the PRIMARY KEY in another table. It
establishes a relationship between two columns in the same table or between different
tables. For a column to be defined as a Foreign Key, it should be a defined as a Primary Key
in the table which it is referring. One or more columns can be defined as Foreign key.
Syntax to define a Foreign key at column level:

[CONSTRAINTconstraint_name]REFERENCES eferenced_Table_name(column_name)

Syntax to define a Foreign key at table level:

[CONSTRAINT constraint_name] FOREIGN KEY(column_name) REFERENCES


referenced_table_name(column_name);
For Example:
1)Letsusethe"product"tableand"order_items".

CREATE TABLE product11 ( product_id int(5) PRIMARY KEY, product_name


char(20),supplier_name char(20),unit_price int(10));
CREATE TABLE order_items(order_id int(5) PRIMARY KEY, product_id int(5) REFERENCES
product11(product_id));

3) SQL Not Null Constraint :


This constraint ensures all rows in the table contain a definite value for the column which
is specified as not null. Which means a null value is not allowed.
Syntax to define a Not Null constraint:
[CONSTRAINT constraint name] NOT NULL

For Example: To create a employee table with Null value, the query would be like
CREATE TABLE employee33( id int(5),name char(20) NOT NULL,dept char(10),age
int(2),salary int(10),location char(10) );

P a g e 34 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


4) SQL Unique Key:
This constraint ensures that a column or a group of columns in each row have a distinct
value. A column(s) can have a null value but the values cannot be duplicated.
Syntax to define a Unique key at column level:

[CONSTRAINT constraint_name] UNIQUE

Syntax to define a Unique key at table level:

[CONSTRAINT constraint_name] UNIQUE(column_name)


For Example: To create an employee table with Unique key, the query would be like,

CREATE TABLE employee44( id int(5) PRIMARY KEY, name char(20),dept char(10), age
int(2),salary int(10), location char(10) UNIQUE );

5) SQL Check Constraint:


This constraint defines a business rule on a column. All the rows must satisfy this rule. The
constraint can be applied for a single column or a group of columns.
Syntax to define a Check constraint:

[ CONSTRAINT constraint_name] CHECK (condition)


For Example: In the employee table to select the gender of a person, the query would be
like

CREATE TABLE employee55 ( id int(5) PRIMARY KEY, name char(20), dept


Char(10), age int(2), gender char(1) CHECK (gender in ('M','F')), salary
int(10), location char(10) );

CONCLUSION: We have executed various types of Integrity Constraints.

Viva Questions:
1) List various types of integrity constraints.
2) What do you mean by referential integrity constraint.
3) What is Entity integrity constraint.
4) Give the importance of integrity constraint in sql.
5) What is unique key constraint.

P a g e 35 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


PRACTICAL NO : 09

AIM : To Study & Execute Views.

THEORY :

VIEWS
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. Views are stored queries that when invoked produce a result set. A view acts as a
virtual table.

Query1:Write a query to create view on products table having only two columns product id and
product name.
mysql> create view product_view as select pid,p_name from products;
Query OK, 0 rows affected (0.02 sec)

A view called product_view is created on products table having only 2 columns pid and pname.

mysql> select * from product_view;


+-----+---------+
| pid | p_name |
+-----+---------+
| 1 | soap |
| 2 | biscuit |
| 3 | cake |
| 4 | soap |
| 5|A |
| 6 | abc |
| 10 | aaa |
+-----+---------+
7 rows in set (0.00 sec)

Query2: Write a query to create view on product and department table which displays product
id,product name,price and department name.

Mysql>create view product_view1 as select products.pid,p_name,price,dname from


products,department where products.pid=department.pid

mysql> select * from product_view1;


+-----+--------+-------+-------+
| pid | p_name | price | dname |
+-----+--------+-------+-------+
| 1 | soap | 30.00 | A |
| 1 | soap | 30.00 | A |

P a g e 36 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


| 1 | soap | 30.00 | A |
+-----+--------+-------+-------+
3 rows in set (0.03 sec)
Drop View:

DROP VIEW removes one or more views. You must have the DROP privilege for each view. If any
of the views named in the argument list do not exist, MySQL returns an error indicating by name
which nonexisting views it was unable to drop, but it also drops all of the views in the list that do
exist.
The IF EXISTS clause prevents an error from occurring for views that don't exist

Syntax:

DROP VIEW [IF EXISTS]


view_name [, view_name] ...

Query 3: mysql> drop view pro_view;


Query OK, 0 rows affected (0.00 sec)

Update View:

You can modify the definition of a VIEW in MySQL without dropping it by using the ALTER VIEW
statement.
Syntax

The syntax for the ALTER VIEW statement in MySQL is:

ALTER VIEW view_name AS


SELECT columns
FROM table
WHERE conditions;

Query 4: Write a query to update product_view by updating column from product id to price of
product.

mysql> alter view product_view as select p_name,price from products;


Query OK, 0 rows affected (0.06 sec)

mysql> select * from product_view;


+---------+-------+
| p_name | price |
+---------+-------+
| soap | 30.00 |
| biscuit | 30.00 |

P a g e 37 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


| cake | 30.00 |
| soap | 30.00 |
|A | 30.00 |
| abc | NULL |
| aaa | 30.00 |
+---------+-------+
7 rows in set (0.00 sec)

CONCLUSION : We have executed VIEW successfully.

Viva questions:
1) What is view.
2) Explain need of view
3) Give the difference between view and materialized view.
4) Give advantages and disadvantages of view.

P a g e 38 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


PRACTICAL NO : 10

AIM : To study pl/sql block

THEORY :

PL/SQL Basics
PL/SQL is a block structured language. The programs of PL/SQL are logical blocks that can contain
any number of nested sub-blocks. Pl/SQL stands for "Procedural Language extension of SQL" that
is used in Oracle. PL/SQL is integrated with Oracle database. PL/SQL adds many procedural
constructs to SQL language to overcome some limitations of SQL. PL/SQL is not case sensitive so
you are free to use lower case letters or upper case letters except within string and character
literals.
Use of variables.
In PL/SQL, a variable is named storage location that stores a value of a particular data type. The
value of the variable changes through the program. Before using a variable, you must declare it
in the declaration section of a block or in a package as a global variable. After the declaration,
PL/SQL allocates memory for the variable's value and the storage location is identified by the
variable name.
Following is the syntax for declaring variable:

variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT initial_value]

Example:
Radius Number := 5;
Date_of_birth date;

Note-
Variables belonging to the same datatype cannot be declared in the same statement.
N1, N2, N3 Number;
It is an illegal declaration.

Datatypes in PL/SQL
PL/SQL has two kinds of data types: scalar and composite. The scalar types are types that store
single values such as number, Boolean, character, and datetime whereas the composite types are
types that store multiple values, for example, record and collection.
PL/SQL divides the scalar data types into four families:
•Number
•Boolean
•Character
•Datetime

NUMBER(p,s)
Range: p= 1 to 38 s= -84 to 127
This datatype is used to store numeric data. Here, p is precision s is scale.

P a g e 39 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


Example:
1. Age NUMBER(2); where , Age is a variable that can store 2 digits
2. percentage NUMBER(4,2); where, percentage is a variable that can store 4 (p) digits
before decimal and 2 (s) digits after decimal

CHAR(size)
Range: 1 to 2000 bytes
•This datatype is used to store alphabetical string of fixed length.
•Its value is quoted in single quotes.
•Occupies the whole declared size of memory even if the space is not utilized by the data.

Example:
1. rank CHAR(10); where, rank is a variable that can store upto 10 characters. If the length
of data(charcaters) stored in rank is 5 then it will still occupy all the 10 spaces. 5 space in
the memory will get used and the rest blank memory spaces will be wasted

VARCHAR(size)
Range: 1 to 2000 bytes
•This datatype is used to store alphanumeric string of variable length.
•Its value is quoted in single quotes.
•Occupies the whole declared size of memory even if the space is not utilized by the data.

Example:
1. address VARCHAR(10); where, address is a variable that can occupy maximum 10 bytes
of memory space and can store alphanumeric value in it. Unused spaces are wasted.

VARCHAR2(size)
Range: 1 to 4000 bytes
•This datatype is used to store alphanumeric string of variable length.
•Its value is quoted in single quotes.
•It releases the unused space in memory, hence saving the unused space.

Example:
1. name VARCHAR2(10); where, name is a variable that can occupy maximum 10 bytes of
memory to store an alphanumeric value. The unused memory space is released.

DATE
Range: 01-Jan-4712 BC to 31-DEC-9999
•It stores the data in date format DD-MON-YYYY
•The value for this datatype is written in single quotes.

Example:
1. DOB DATE; where, DOB is a variable that stores date of birth in defined format (i.e,’13-
FEB-1991’

P a g e 40 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


BOOLEAN
•This datatype is used in conditional statements.
•It stores logical values.
•It can be either TRUE or FALSE

Example:
1. isAdmin BOOLEAN; where, isAdmin is a variable whose value can be TRUE or FALSE
depending upon the condition being checked

LOB Data Type


This data type is mainly used to store and manipulate large blocks of unstructured data’s like
images, multimedia files, etc.
b. Create anonymous PL/SQL block
PL/SQL program units organize the code into blocks. A block without a name is known as an
anonymous block. The anonymous block is the simplest unit in PL/SQL. It is called anonymous
block because it is not saved in the Oracle database.
An anonymous block is an only one-time use and useful in certain situations such as creating
test units. The following illustrates anonymous block syntax:

[DECLARE]
Declaration statements;
BEGIN
Execution statements;
[EXCEPTION]
Exception handling statements;
END;
/

The anonymous block has three basic sections that are the declaration, execution, and exception
handling. Only the execution section is mandatory and the others are optional
•The declaration section allows you to define data types, structures, and variables. You
often declare variables in the declaration section by giving them names, data types, and
initial values.
•The execution section is required in a block structure and it must have at least one
statement. The execution section is the place where you put the execution code or
business logic code. You can use both procedural and SQL statements inside the
execution section.
•The exception handling section is starting with the EXCEPTION keyword. The exception
section is the place that you put the code to handle exceptions. You can either catch or
handle exceptions in the exception section.
The following example displays a message Hello PL/SQL on a screen using SQL*Plus:

SET SERVEROUTPUT ON SIZE 1000000


BEGIN
DBMS_OUTPUT.PUT_LINE('Hello PL/SQL');
P a g e 41 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


END;
/

CONCLUSION : We have studied pl/sql block successfully.

P a g e 42 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


PRACTICAL NO : 11

AIM : Write a PL/SQL block to satisfy some conditions by accepting input from the
user.

An example of a PL/SQL block that accepts user input and performs operations based on certain
conditions. In this example, the user is prompted to enter an employee ID, and the block checks
if the employee exists in a table. If the employee exists, it displays their salary. If not, it informs
the user that the employee doesn't exist.

DECLARE

emp_id NUMBER; -- Variable to hold the user input

emp_salary NUMBER; -- Variable to hold the salary

emp_exists BOOLEAN; -- Variable to check if employee exists

BEGIN

-- Prompt user for input

DBMS_OUTPUT.PUT_LINE('Enter the Employee ID:');

-- Accepting user input using substitution variable

emp_id := &emp_id;

-- Check if employee exists

SELECT COUNT(*) > 0

INTO emp_exists

FROM employees

WHERE employee_id = emp_id;

IF emp_exists THEN

-- Fetch and display the employee's salary

SELECT salary

P a g e 43 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


INTO emp_salary

FROM employees

WHERE employee_id = emp_id;

DBMS_OUTPUT.PUT_LINE('Employee found. Salary: ' || emp_salary);

ELSE

DBMS_OUTPUT.PUT_LINE('Employee not found.');

END IF;

EXCEPTION

WHEN NO_DATA_FOUND THEN

DBMS_OUTPUT.PUT_LINE('No such employee exists.');

WHEN OTHERS THEN

DBMS_OUTPUT.PUT_LINE('An unexpected error occurred: ' || SQLERRM);

END;

Explanation:

1. Variables: emp_id to store the user input, emp_salary to store the employee's salary, and
emp_exists to check if the employee exists.

2. User Input: The &emp_id allows the user to input a value when running the block. Replace
it with :emp_id if using tools that allow bind variables.

3. Logic: The block first checks if the employee exists by querying the employees table. If the
employee exists, it retrieves their salary.

4. Exception Handling: Handles errors gracefully using the EXCEPTION block.

P a g e 44 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


Notes:

• Replace employees with your actual table name.

• Use a PL/SQL-enabled client (like SQL*Plus, SQL Developer) to run this block.

• Ensure that the DBMS_OUTPUT package is enabled (SET SERVEROUTPUT ON;) to see
output messages.

CONCLUSION : We have executed conditional pl/sql block successfully.

P a g e 45 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


PRACTICAL NO : 12

AIM : To understand and Implement Describe Statement which can be used to view
the structure of the table created by the user.(Virtual Lab)

The DESCRIBE statement in SQL is a simple yet powerful tool to view the structure of a table,
including its columns, data types, and constraints. In this explanation, I'll provide a
step-by-step guide on how to understand and implement the DESCRIBE statement
in a virtual lab environment.

Understanding DESCRIBE Statement


• The DESCRIBE (or DESC) command is used to view the structure of a table or a view.
• It provides details about:
o Column names
o Data types
o Nullable constraints
o Default values (if any)

Implementation Steps in a Virtual Lab


Step 1: Create a Table
First, create a table for which you want to view the structure. For example:
CREATE TABLE students (
student_id NUMBER(5) PRIMARY KEY,
student_name VARCHAR2(50) NOT NULL,
dob DATE,
email VARCHAR2(100),
grade CHAR(2)
);
Step 2: Use the DESCRIBE Command
To view the structure of the table students, use the following command:
DESCRIBE students;
Step 3: Expected Output
After executing the DESCRIBE command, you'll see a result similar to this:
Column Name Data Type Nullable Default Comments
STUDENT_ID NUMBER(5) No
STUDENT_NAME VARCHAR2(50) No
DOB DATE Yes
EMAIL VARCHAR2(100) Yes
GRADE CHAR(2) Yes
Step 4: Virtual Lab Setup
1. Ensure you have access to a database tool:
o Tools like Oracle Live SQL, SQL*Plus, or any Oracle virtual lab environment.
2. Enable Output:
o In SQL*Plus or SQL Developer, ensure that the output is properly set up to display

P a g e 46 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


results.

Points to Note
1. The DESCRIBE command is specific to certain database systems like Oracle.
2. For MySQL, use SHOW COLUMNS FROM table_name; or SHOW CREATE TABLE
table_name; for similar functionality.
3. Ensure you have the necessary privileges to describe the table.

Virtual Lab Exercise


1. Create a table named employees with columns like employee_id, name, salary, and
department.
2. Use the DESCRIBE employees; command to view its structure.
3. Modify the table by adding or altering a column and describe it again to see the changes.
This practice will help you understand the DESCRIBE command and its practical use.

CONCLUSION : We have understood and implement Describe Statement which can be used
to view the structure of the table created by the user.(Virtual Lab)

P a g e 47 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


PRACTICAL NO : 13

AIM : Data Manipulation Language(Virtual Lab)

Theory :

Data Manipulation Language (DML) is a subset of SQL used to retrieve, insert, update, and
delete data in a database. In a virtual lab environment, you can practice and
implement DML commands on a sample database table.

Steps to Implement DML Commands in a Virtual Lab


Step 1: Create a Table
Start by creating a table for practice:
CREATE TABLE employees (
employee_id NUMBER(5) PRIMARY KEY,
first_name VARCHAR2(50) NOT NULL,
last_name VARCHAR2(50) NOT NULL,
department VARCHAR2(50),
salary NUMBER(10, 2)
);

Step 2: Insert Data (INSERT Command)


Insert records into the employees table using the INSERT command.
Single Row Insert:
INSERT INTO employees (employee_id, first_name, last_name, department, salary)
VALUES (1, 'John', 'Doe', 'IT', 75000);
Multiple Rows Insert:
INSERT INTO employees (employee_id, first_name, last_name, department, salary)
VALUES (2, 'Jane', 'Smith', 'HR', 65000),
(3, 'Sam', 'Brown', 'Finance', 80000);

Step 3: Retrieve Data (SELECT Command)


Use the SELECT command to view the data in the table.
View All Data:
SELECT * FROM employees;
Filter Data:
SELECT first_name, salary
FROM employees
WHERE department = 'IT';

Step 4: Update Data (UPDATE Command)


Modify existing data using the UPDATE command.
Update a Specific Record:
UPDATE employees
SET salary = 78000

P a g e 48 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


WHERE employee_id = 1;
Update Multiple Records:
UPDATE employees
SET department = 'Operations'
WHERE department = 'Finance';

Step 5: Delete Data (DELETE Command)


Remove records from the table using the DELETE command.
Delete a Specific Record:
DELETE FROM employees
WHERE employee_id = 2;
Delete All Records (Use with Caution):
DELETE FROM employees;

Step 6: Rollback and Commit


Use ROLLBACK and COMMIT to manage transactions.
Commit Changes:
COMMIT;
Rollback Changes:
ROLLBACK;

Virtual Lab Exercises


1. Create a table named students with columns: student_id, name, course, and marks.
2. Insert at least 5 records into the students table.
3. Write queries to:
o Update the marks of a specific student.
o Retrieve students with marks greater than 80.
o Delete a student who has not registered for a course.
4. Practice COMMIT and ROLLBACK.

Output Expectations
• SELECT should show the updated or filtered data.
• UPDATE and DELETE should affect specific rows, verified by running a SELECT after
execution.
• ROLLBACK will undo changes if not committed.
This hands-on practice in a virtual lab will help solidify your understanding of DML operations.

CONCLUSION : We have understood and implement Data Manipulation Language(Virtual


Lab)

P a g e 49 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


PRACTICAL NO : 14

AIM : Database Trigger

Theory :
A Database Trigger is a procedural code automatically executed in response to certain events on
a particular table or view in a database. Triggers can be used to enforce business
rules, audit changes, or maintain derived values in tables.

Key Features of Database Triggers


1. Event-Driven: Executed automatically when an event (e.g., INSERT, UPDATE, DELETE)
occurs.
2. Before or After: Triggers can fire before or after the specified event.
3. Row-Level or Statement-Level:
o Row-level triggers execute once for each row affected.
o Statement-level triggers execute once for the entire statement.

Steps to Create and Implement a Trigger


1. Create a Table
First, create a table to practice on:
CREATE TABLE employees (
employee_id NUMBER(5) PRIMARY KEY,
first_name VARCHAR2(50),
last_name VARCHAR2(50),
salary NUMBER(10, 2),
hire_date DATE DEFAULT SYSDATE
);

CREATE TABLE audit_log (


log_id NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
action_type VARCHAR2(50),
action_time TIMESTAMP,
employee_id NUMBER(5),
old_salary NUMBER(10, 2),
new_salary NUMBER(10, 2)
);

2. Create a Trigger
Create a trigger to log salary updates to the audit_log table.
CREATE OR REPLACE TRIGGER trg_salary_update
AFTER UPDATE OF salary ON employees
FOR EACH ROW
BEGIN
INSERT INTO audit_log (action_type, action_time, employee_id, old_salary, new_salary)
VALUES ('SALARY UPDATE', SYSTIMESTAMP, :OLD.employee_id, :OLD.salary, :NEW.salary);

P a g e 50 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


END;
/

3. Test the Trigger


Insert some data into the employees table:
INSERT INTO employees (employee_id, first_name, last_name, salary)
VALUES (1, 'John', 'Doe', 75000);

INSERT INTO employees (employee_id, first_name, last_name, salary)


VALUES (2, 'Jane', 'Smith', 65000);
Update the salary of an employee to trigger the trg_salary_update:
UPDATE employees
SET salary = 80000
WHERE employee_id = 1;

4. Verify the Trigger


Check the audit_log table for the record of the salary update:
SELECT * FROM audit_log;

Trigger Explanation
1. Trigger Type: AFTER UPDATE OF salary ensures the trigger fires after a salary update.
2. Row-Level: FOR EACH ROW makes the trigger execute for each affected row.
3. Accessing Old and New Values:
o :OLD refers to the values before the update.
o :NEW refers to the values after the update.
4. Insert Statement: Logs the action details in the audit_log table.

Types of Triggers
1. DML Triggers: Triggered by INSERT, UPDATE, or DELETE operations.
2. DDL Triggers: Triggered by CREATE, ALTER, or DROP statements.
3. Database Triggers: Triggered by system events like LOGON, LOGOFF, or STARTUP.

Exercises for Practice


1. Create a trigger to prevent the deletion of employees with a salary greater than 100,000.
2. Create a trigger to automatically update a "last_modified_date" column whenever a
record is updated.
3. Create a trigger to enforce a constraint where no two employees can have the same
email address.
Practicing these exercises will help you understand the power and versatility of triggers in a
database system.

CONCLUSION : We have understood and implement Database Trigger

P a g e 51 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


PRACTICAL NO : 15

AIM : Database Connectivity

Theory :

Database Connectivity refers to the process of establishing a connection between an application


and a database to perform operations like querying, updating, and managing data.
This is commonly implemented using APIs, libraries, or frameworks that provide
tools to interact with a database.

Components of Database Connectivity


1. Database: The backend where data is stored (e.g., Oracle, MySQL, PostgreSQL).
2. Driver: Software that enables communication between an application and the database
(e.g., JDBC, ODBC).
3. Application: The frontend or server-side program that interacts with the database.
4. Connection String: Information (host, port, username, password) required to connect to
the database.

Examples of Database Connectivity


1. Java and JDBC
Java Database Connectivity (JDBC) is a Java API for connecting to relational databases.
Steps:
1. Import the JDBC package.
2. Load the database driver.
3. Establish a connection.
4. Create and execute SQL statements.
5. Close the connection.
Code Example:
import java.sql.*;

public class DatabaseConnectionExample {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";

try {
// Load MySQL driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Establish connection
Connection connection = DriverManager.getConnection(url, username, password);

// Create a statement

P a g e 52 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


Statement statement = connection.createStatement();

// Execute a query
ResultSet resultSet = statement.executeQuery("SELECT * FROM employees");

// Process the result set


while (resultSet.next()) {
System.out.println("ID: " + resultSet.getInt("employee_id") +
", Name: " + resultSet.getString("first_name"));
}

// Close the connection


connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

2. Python and MySQL (Using mysql-connector)


Steps:
1. Install the MySQL Connector library.
2. pip install mysql-connector-python
3. Establish a connection and execute queries.
Code Example:
import mysql.connector

# Connect to the database


connection = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="mydatabase"
)

cursor = connection.cursor()

# Execute a query
cursor.execute("SELECT * FROM employees")

# Fetch and print results


for row in cursor.fetchall():
print(f"ID: {row[0]}, Name: {row[1]}")

# Close the connection

P a g e 53 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


cursor.close()
connection.close()

3. PHP and MySQL


Steps:
1. Use the mysqli or PDO extension in PHP.
2. Connect and execute queries.
Code Example:
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "mydatabase";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Execute query
$sql = "SELECT employee_id, first_name FROM employees";
$result = $conn->query($sql);

// Fetch results
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["employee_id"]. " - Name: " . $row["first_name"]. "<br>";
}
} else {
echo "0 results";
}

// Close connection
$conn->close();
?>

Important Points
• Use parameterized queries or prepared statements to prevent SQL injection.
• Use connection pooling for better performance in high-traffic applications.
• Handle exceptions to manage database connection errors gracefully.
• Secure your connection strings and credentials.

P a g e 54 | 55
NAGPUR INSTITUTE OF TECHNOLOGY
(Affiliated to RTM Nagpur University & Approved by AICTE New Delhi)
CAMPUS : 13/2, Mahurzari, Near Fetri, Katol Road, Nagpur-441501, India
Email Id : [email protected] Web : www.nit.edu.in Contact No. 09764974144

RTMNU College Code: 315 DTE Code: 4144 AICTE ID : 1-4830701

Department of Information Technology


Exercise for Practice
1. Connect to a database using your preferred programming language.
2. Create a table, insert some data, and fetch it using the connectivity methods.
3. Modify the data and handle potential errors during the update.
4. Explore connection pooling using libraries specific to your language (e.g., HikariCP for
Java).
These steps will give you hands-on experience with database connectivity in real-world
applications.

CONCLUSION : We have understood and implement Database Connectivity

P a g e 55 | 55

You might also like