Lab Manual-DBMS
Lab Manual-DBMS
For
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
---------------------------------------------------------------------------------------------------------------------------------------------
• 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.
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
--------------------------------------------------------------------------------------------------------------------------------------------
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
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
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
PEO’s
PEO-2 Capable of adapting to new technologies and constantly upgrade their skills with
an attitude towards lifelong learning.
PEO-4 Capable to understand , analyse, design and create innovative computing products
and solutions for real life problems.
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
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:
• Lines, which link attributes to entity sets and entity sets to relationship sets
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
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
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.
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
• 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.
• 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
• 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.
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
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
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:
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:
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
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.
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:
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
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.
Output :
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);
Query 7:To modify the column qnt in the products table, the query would be like
mysql>
ALTER TABLE products
MODIFY qnt int(15);
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
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
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
Example:
Output :
1 row created.
Output:
+------+--------+------+-------+---------------+
| p_id | P_name | qnt | price | P_description |
+------+--------+------+-------+---------------+
| 1 | soap | 100 | 30.00 | bathspoap |
+------+--------+------+-------+---------------+
1 row in set (0.00 sec)
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
5) SELECT COMMAND
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
Query 12: Update product table put qnt =200 having product id =1.
Output:
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
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)
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
SELECT 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
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.
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:
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
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
+-----+---------+-------+-------+
| 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:
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
Syntax:
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)
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
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.
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
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
CONCLUSION: We have studied and executed Pl/Sql stored procedures and functions.
Viva Questions:
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
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.
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
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
| 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
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
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
AVG FUNCTION: The avg function computes the column’s average value.The input to avg function
is a collection of number.
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
SUM FUNCTION: The sum function computes the column’s total value.input to this function must
be a collection of numbers.
Queries:
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
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
Viva Questions:
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
THEORY:
Clauses
1) Between/Not Between
2) Is Null/Not Null
3) Order by
4) Group by
5) Having
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.
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
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 quantity and product name
Query: Arrange records of product table in ascending order of quantity without writing column
name in query.
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;
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
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
Viva Questions:
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
THEORY:
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) );
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
[CONSTRAINTconstraint_name]REFERENCES eferenced_Table_name(column_name)
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
CREATE TABLE employee44( id int(5) PRIMARY KEY, name char(20),dept char(10), age
int(2),salary int(10), location char(10) UNIQUE );
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
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.
Query2: Write a query to create view on product and department table which displays product
id,product name,price and department name.
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
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:
Update View:
You can modify the definition of a VIEW in MySQL without dropping it by using the ALTER VIEW
statement.
Syntax
Query 4: Write a query to update product_view by updating column from product id to price of
product.
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
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
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:
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
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
Example:
1. isAdmin BOOLEAN; where, isAdmin is a variable whose value can be TRUE or FALSE
depending upon the condition being checked
[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:
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
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
BEGIN
emp_id := &emp_id;
INTO emp_exists
FROM employees
IF emp_exists THEN
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
FROM employees
ELSE
END IF;
EXCEPTION
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.
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
• 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.
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
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.
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
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.
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
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.
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
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.
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
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.
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
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.
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
Theory :
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
// Execute a query
ResultSet resultSet = statement.executeQuery("SELECT * FROM employees");
cursor = connection.cursor()
# Execute a query
cursor.execute("SELECT * FROM employees")
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
// 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
P a g e 55 | 55