Sei sulla pagina 1di 69

Nagar Yuwak Shikshan Sanstha’s

Yeshwantrao Chavan College of Engineering, Nagpur


(An Autonomous Institution affiliated to Rashtrasant Tukadoji Maharaj Nagpur University)
Hingna Road, Wanadongri, Nagpur - 441 110

Department of Information Technology

LAB MANUAL

IT1316 Database Management System


(V Semester IT)

Prepared by,
Mr. S. S. Chavhan
(Assistant Professor IT)

1|Page Database Management System Lab Manual


Sr.No. Contains Pg. No

1 General Instructions for Laboratory Classes 3

2 Hardware and software Requirements 4

3 List of Practical’s 5

4 Practical 1: 6

5 Practical 2: 14

6 Practical 3: 29

7 Practical 4: 34

8 Practical 5: 39

9 Practical 6: 44

10 Practical 7: 52

11 Practical 8: 57

12 Practical 9: 60

13 Practical 10: 63

14 Practical 11: 66

2|Page Database Management System Lab Manual


General Instructions for Laboratory Classes
DO’S

Without Prior permission do not enter into the Laboratory.

Students should sign in the LOGIN REGISTER before entering into the laboratory.

Students should maintain silence inside the laboratory.

After completing the laboratory exercise, make sure to shut down the system properly.

DONT’S

Students using the computers in an improper way.

Students scribbling on the desk and mishandling the chairs.

Students using mobile phones inside the laboratory.

Students making noise inside the laboratory.

3|Page Database Management System Lab Manual


Hardware and Software Requirement

Minimum Hardware Requirements:

Processor : Dual Core and above

RAM : 2 GB

HDD Space : 16 GB

Minimum Software Requirements:

Operating System : Windows / Linux operating system

Language : JDK 1.6 (or above)

4|Page Database Management System Lab Manual


List of Practical’s
Nagar Yuwak Shikshan Sanstha’s
YESHWANTRAO CHAVAN COLLEGE OF ENGINEERING
(An Autonomous Institution affiliated Rashtrasanth Tukadoji Maharaj Nagpur University, Nagpur)
HINGNA ROAD, WANADONGRI, NAGPUR
DEPARTMENT OF INFORMATION TECHNOLOGY

Academic Year: 2017-18

Course: Database Management System Lab Sem.:5th


Course Code: IT-1317 Teaching Scheme: 2 Hrs/Week
CA: 40 marks (4 MSPAs – 10 Marks each) Name of Faculty: Mrs. R. A. Fadanvis
Mrs. P. G. Jaiswal
Mr. S. S. Chavhan
Mr. G. K. Yenurkar
LIST OF PRACTICALS
Sr. Name of Practical CO PO
No Mapped Mapped
1 Database design using E-R Model for: 1 1
Payroll processing system,
Banking system
Library Information System
Student Information System, etc.
2 Mapping of E-R model to relational Schema and creation of 2 1,3,5
Tables using DDL (Data Definition Language).
3 Modification of Database objects using DDL and DML (Data 2 1,3,5
Manipulation Language).
4 Querying the Database based on various inbuilt functions 2 1,3,5
(Date Function, Numeric Function, Character Function,
Conversion Function, Miscellaneous Function).
5 Querying the Database based on Set, Arithmetic and Logical 2 1,3,5
operator.
6 Querying the Database based nesting and applying various 3 1,5
Clauses
7 Querying the Database based on Join operation 4 1
a) Simple Join and Self Join
b) Outer Join and Inner Join
8 Querying the Database based on various data language 5 1,3
commands (DCL, TCL) and implements them on the database.
9 Querying the Database based on to create triggers for various 6 1,5
events such as insertion, updation, etc.,
10 To create and manipulate various database objects of the Table 6 1,5
using views
11 To create PL/SQL programs to implement various types of 6 1
control structure.(Topic Beyond the Syllabus)

1. Mrs. R. A. Fadanvis
2. Mrs. P. G. Jaiswal
Mr. S. S. Chavhan 3. Mr. Ganesh Yenurkar Mrs. R. A. Fadanvis Dr. U. H.Gawande
Subject Teacher Co- Teacher(s) Thrust Area Group HOD, IT
Leader
5|Page Database Management System Lab Manual
Practical Number: 1
Title of the Exercise : Database design using E-R Model
Date of the Exercise :
OBJECTIVE (AIM) OF THE EXPERIMENT
This lab session introduced the key concepts of entity relationship modeling. After this lab session
student should be able to:
1. Define entity relationship models and describe its benefits
2. Recognize and understand the basic concepts and constructs of an entity relationship diagram
(ERD)
3. Distinguish between unary, binary, and ternary relationships, and give an example of each
4. Learn how to identify entities from a simple description.
5. Learn how to identify entity relationships using an Entity Relationship collection.
6. Draw ERD diagrams

ENTITY RELATIONSHIP DIAGRAM (ERD)

ERD complements Data Flow Diagram (DFD). While DFD focuses on processes and data flow between
them, ERD focuses on data and the relationships between them. It helps to organize data used by a system
in a disciplined way. It helps to ensure completeness, adaptability and stability of data. It is an effective
tool to communicate with senior management (what is the data needed to run the business), data
administrators (how to manage and control data), database designers (how to organize data efficiently and
remove redundancies). It consists of three components.

Entity: It represents a collection of objects or things in the real world whose individual members or
instances have the following characteristics:

 Each can be identified uniquely in some fashion.


 Each plays a necessary role in the system we are building.
 Each can be described by one or more data elements (attributes).

Entities generally correspond to persons, objects, locations, events, etc. Examples are employee, vendor,
supplier, materials, warehouse, delivery, etc.
There are five types of entities.

 Fundamental entity: It does not depend on any other entity for its existence. For e.g. materials
 Subordinate entity: It depends on another entity for its existance. For example, in an inventory
management system, purchase order can be an entity and it will depend on materials being
procured. Similarly invoices will depend on purchase orders.
 Associative entity: It depends on two or more entities for its existence. For example, student
grades will depend on the student and the course.
 Generalisation entity: It encapsulates common characteristics of many subordinate entities. For
example, a four wheeler is a type of vehicle. A truck is a type of four wheeler .
 Aggregation entity: It consists of or an aggregation of other entities. For example, a car consists
of engine, chasis, gear box, etc. A vehicle can also be regarded as an aggregation entity, because
a vehicle can be regarded as an aggregation of many parts.

ATTRIBUTES : They express the properties of the entities.

Every entity will have many attributes, but only a subset, which are relevant for the system under study,
will be chosen. For example, an employee entity will have professional attributes like name, designation,
salary, etc. and also physical attributes like height, weight, etc. But only one set will be chosen depending
on the context.
6|Page Database Management System Lab Manual
Attributes are classified as entity keys and entity
descriptors.
(a) CUSTOMER entity type
Entity keys are used to uniquely identify instances with simple attributes
of entities. Attributes having unique values are
called candidate keys and one of them is designated
as primary key. The domains of the attributes should
be pre-defined. If 'name' is an attribute of an entity,
(b) CUSTOMER relation
then its domain is the set of strings of alphabets of
predefined length.

ATTRIBUTE TYPES

 Atomic / Simple Attribute


 Composite Attributes (a) CUSTOMER
 Single-Valued entity type with
composite
 Multi Valued attribute
 Stored Attribute
 Derived Attribute

 Simple (or atomic) attribute can't be broken down (b) CUSTOMER relation with address detail
into smaller components.
 Composite attributes, can be broken down into
component parts.
 Single-valued attribute (represented by a single
line ellipse) is an attribute which has only
one value in a table.
 Multi-valued attribute has multiple values per instance, such as: all courses taken by a student, shown
above. It is represented by double line ellipse
 Stored attribute - a regular attribute
 Derived attribute which is calculated from a stored attribute, and thus should not be shown on the ERD.

Relationships: They describe the association Example


between entities.
Attribute
Attribute M ulti_v alued
attribu te
They are characterized by optionality and
Age
Age Degree
Degree
cardinality.
A
A :: 24
24 A
A :: B.Sc
B.Sc,, M.Sc.
M.Sc.
Optionality is of two types, namely, mandatory B
B :: 27
27 B
B :: B.Sc,
B.Sc, M.Sc.,
M.Sc., Dr.
Dr. Eng.
Eng.
and optional.
Single _Val ued
attribute
Attribute values
1. Mandatory relationship means associated
with every instance of the first entity there
will be at least one instance of the second entity.
2. Optional relationship means that there may be instances of the first entity, which are not
associated with any instance of the second entity. For example, employee-spouse relationship has
to be optional because there could be unmarried employees. It is not correct to make the
relationship mandatory.

7|Page Database Management System Lab Manual


Cardinality is of three types: one-to-one, one-to-many, many-to-many.

1. One-to-one relationship means an instance of Example


the first entity is associated with only one
instance of the second entity. Similarly, each Attribute
instance of the second entity is related to one
instance of the first entity.
Age Birth Day Stored
Stored Attribute
Attribute
2. One-to-many relationship means that one
instance of the first entity is related to many
instances of the second entity, while an A : 24 Years A : 13 July 1980
B : 40 Years B : 23 Dec 1964
instance of the second entity is associated with
only one instance of the first entity.
Derived
Derived Attribute
Attribute
3. In many-to-many relationship an instance of Attribute Value
the first entity is related to many instances of
the second entity and the same is true in the
reverse direction also.

Other types of relationships are multiple relationships between entities, relationships leading to associative
entities, relationship of entity with itself, EXCLUSIVE-OR and AND relationships

ERD NOTATION : PETER CHEN NOTATION

COMPONENT REPRESENTATION
ENTITY OR OBJECT
PURCHASE ORDER
TYPE

RELATIONSHIP

CARDINALITY

OPTIONALITY

Example

8|Page Database Management System Lab Manual


Creating Entity Relationship Diagrams
Components of an Entity Relationship Diagram
An entity relationship diagram (ERD) typically consists of four different graphical components:
1. Entity. An entity in ERD stands for some physical or abstract object in reality. Entity can represent:
 persons (e.g., customer, student)
 things (e.g., a tangible product such as car)
 organizations (e.g., store, university department)
 events (e.g., purchase, course enrollment)
 concepts (e.g., order, GPA).

Specific examples of an entity are called instances (e.g., the customer John Jones).
2. Relationship. A relationship represents a connection that exists between entities (e.g., a customer
places an order). Relationships in ERD usually reflect relationships between objects in reality.
3. Cardinality. Cardinality defines how many instances of related entities can participate in the
relationship (e.g., a customer may place many purchase orders, and each purchase order is placed by
one particular customer). In an ERD, cardinality is specified by those funny looking crow feet, bars
and circles (or sometimes simply by numbers).
4. Attribute. An attribute is a piece of data, a characteristic common to all or most instances of a
particular entity (e.g., customer number, name, address, and telephone number are all attributes of the
entity customer). Attributes are also referred to as fields or columns.
An attribute or a combination of attributes that uniquely identify one and only one instance of an entity
is called primary key or just key (e.g., customer ID is the primary key for the entity customer).
The figure below is an ERD containing all the four components discussed above. Primary keys are
underlined.

9|Page Database Management System Lab Manual


Primary Keys

CustomerID OrderID
Entities

places
Customer Order

Relationship
CustFirstName
CustMiddleName
CustLastName Cardinalities OrderDate
CustAddrLine1
CustAddrLine2
CustCity
CustProvince
CustPostalCode
CustPhone
CustEmail Attributes

Figure 1. Components of Entity Relationship Diagram

Procedure for Developing Entity Relationship Diagram


Typically, you will start with a case study or perhaps some business documents belonging to the company
in case. The following procedure will demonstrate how to convert that information into an ERD.
1. Identify Entities. Identify the persons, organizations, things, events, and concepts that you want
to present as entities in your ERD.
2. Identify Relationships. Figure out relationships between pairs of entities.
3. Draw a Rough Diagram. Draw rectangles for entities and lines with diamond shapes inserted for
relationships connecting the entities.
4. Define Primary Keys. Identify the data attribute(s) that can be used for identifying each instance
of an entity.
5. Identify Attributes. List other data attribute(s) for your entities.
6. Map Attributes into Entities. For each attribute, match it with that specific entity it belongs to.
7. Draw a Fully Attributed Diagram. Adjust the diagram to account for attributes, entities, or
relationships discovered in step 6.
8. Check Results. Ask yourself, does the final entity relationship diagram accurately depict the case
or document data?

Example
The above procedure will be illustrated by working out the following example.

A store has customers. A customer places orders with the store. An order contains products. The important
data fields are customer first name, customer middle name, customer last name, street address, city,
province, postal code, phone number, product name, product unit price, quantity in stock, order date, and
the quantity of the product ordered. Each of the following sections corresponds to a specific step above.

1. Identify Entities

In this stage, you analyze the information you have in order to identify the people roles, events,
organizations, things, and concepts. One approach is to highlight those words which you think correspond
to entities, as follows:

10 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
a. A store has customers.
b. A customer places orders with the store.
c. An order contains products.

The important data attributes are customer first name, customer middle name, customer last name, street
address, city, province, postal code, phone number, product name, product unit price, quantity in stock,
order date, and the quantity of the product ordered.

This example is quite simple because entities are labeled and the text explicitly specifies attributes.

2. Identify Relationships

In this step, the aim is to identify relationships, that is, the connections between pairs of entities. There
are minimally two relationships in example.
a. A customer places an order
b. An order contains products.

3. Draw a Rough Data Diagram and place all the entities in rectangles
4. Use diamonds and lines to represent the relationships between entities.

Arrange the entities so there is no overlap of the relationships. The figure below is an example of a
rough diagram that represents information from Step 2.

places
Customer Order

contains

Product

Figure 2. A Rough ERD

5. Define Primary Keys


A primary key is an attribute, or a group of attributes, that can be used to uniquely identify a specific
instance of an entity. The name "Bob Smith" is not a primary key as there are many people with that name.
We usually use whole numbers for primary keys because each number is unique and thus can uniquely
identify each instance of an entity. So, a customer number is the key in this case, and we usually use the
term “ID” (identifier) for naming this key as well as other keys.

You can identify primary keys by examining and evaluating the information about the business that you
want to represent in your ERD. In this example, the following are specified as unique identifiers:
CustomerID, ProductID, OrderID. The diagram below includes the keys. Cardinality is also specified to
make the diagram complete.

11 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
CustomerID OrderID

places
Customer Order

contains

Product ProductID

Figure 3. Rough ERD with Primary Keys


7. Identify Attributes
A data attribute is a characteristic common to all or most instances of a particular entity. In this step, you
try to identify and name all the attributes essential to the business you are studying without trying to match
them to particular entities. The best way to do this is by studying forms, files, and reports currently
available and taking a note of each potential attribute. Cross out extraneous items such as signatures and
information that is same for all instances of the form (e.g., your company name and address). If so
indicated, cross out any attributes which are no longer used or which are not to be used in the future.

The remaining items should represent the attributes you need. You should always verify these with the
people in the actual business. (Sometimes forms or reports are out of date.)

The only attributes indicated in our example case are the customer first name, customer middle name,
customer last name, street address, city, province, postal code, product name, product unit price, quantity
in stock, order date, and quantity of product ordered.

6. Map Attributes

For each attribute, we need to match it with exactly one entity. Often it seems like an attribute should go
with more than one entity (e.g., name). In this case, you need to add a modifier to the attribute name to
make it unique (e.g., Customer Name, Employee Name, etc.) or determine which entity an attribute “best”
describes. It is a convention to use a single word to name a field, such as using CustName instead of
Customer Name).

If you have attributes leftovers without corresponding entities, you may have missed an entity and its
corresponding relationships. Identify these missed entities, and add them to your list. In our example, there
is just one such “odd” attribute, the quantity of products being ordered – QuantityOrdered. This attribute
does not belong to either Product or Order but to something that is a bridge between these two. This is a
“bridge” entity (called weak entity or association entity). In the table below, the association entity is
OrderDetail. It contains the attribute QuantityOrdered as well as the ProductID (to track which product is
ordered in a particular quantity) and OrderID (to track on which orders the particular products in specific
quantities occur).

Attribute-Entity Mapping Table


Customer ( CustomerID, CustFirstName, Order ( OrderID, OrderDate )
CustMiddleName, CustLastName,
CustAddrLine1, CustAddrLine2 Product ( ProductID, ProductName,
CustCity, CustProvince, CustPostalCode UnitPrice
CustPhone, CustEmail ) QuantityInStock)

OrderDetail -- New Entity


(OrderID, ProductID, QuantityOrdered)

Another way of thinking about this new entity OrderDetail is that it allows for one order to contain many
products (e.g., Order #1 can contain apples and oranges, which are represented by their ProductIDs).
Notice that the key for entity OrderDetail is a combination of OrderID and ProductID. This key makes it
12 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
possible to match the same OrderID – 1 in our example – with different ProductIDs – those for apples and
oranges in our example.

Another useful property of this new entity OrderDetail is that it allows for apples to be ordered many
times (the same goes for oranges). So, you can have apples on orders #1, #2, and so on. Therefore, different
OrderIDs are matched with the same ProductID.

7. Draw a Fully Attributed ERD

To show all the attributes belonging to the entities and the new association entity, you need to redraw your
ERD, as depicted in the figure below.

Figure 5. Completed ERD


8. Check Your Results

Look at your diagram from the point of view of a person who is familiar with the situation, form, or
process being modeled. Is everything clear? Also, look over the list of attributes associated with each
entity to see if anything has been omitted.

Hints:
 Begin labeling relationships using single words or simple phrases that describe how two items
relate to each other, but be consistent in your use of words or phrases. Avoid using different labels
such as ‘uses’ and ‘makes use of’ if ‘uses’ could accurately apply for both situations.
 Always look for relationships between the items in the diagram, and add these when they become
apparent. The strength of an ERD is in showing the relationships, dependencies, and complexity
in an organization.

PRACTICE ASSIGNMENTS
Create ERDs for the examples below.
1. Payroll processing system,
2. Banking system
3. Library Information System
4. Student Information System,

Conclusion: We studied ER Modeling and draw one ER diagram based on above problem
Statement.

13 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
Practical Number: 2
Title of the Exercise : Mapping of E-R model to relational Schema and creation of Tables
using DDL (Data Definition Language).
Date of the Exercise :
OBJECTIVE (AIM) OF THE EXPERIMENT
To practice and implement data definition language commands and constraints.
PROCEDURE
o Procedure for doing the experiment:
Step
Details of the step
no.
DDL COMMAND
It is used to communicate with database. DDL is used to:
1 o Create an object
o Alter the structure of an object
o To drop the object created.
2 The commands used are: Create, Alter, Drop, Truncate
INTEGRITY CONSTRAINT
An integrity constraint is a mechanism used by oracle to prevent invalid data entry
3 into the table. It has enforcing the rules for the columns in a table. The types of the
integrity constraints are:
a) Domain Integrity b) Entity Integrity c) Referential Integrity
a) Domain Integrity
This constraint sets a range and any violations that take place will prevent the user
from performing the manipulation that caused the breach. It includes:
Not Null constraint:
While creating tables, by default the rows can have null value .the enforcement of
not null constraint in a table ensure that the table contains values.
Principle of null values:
4 3. Setting null value is appropriate when the actual value is
unknown, or when a value would not be meaningful.
4.A null value is not equivalent to a value of zero.
5.A null value will always evaluate to null in any expression.
6. When a column name is defined as not null, that column becomes
a mandatory i.e., the user has to enter data into it.
7. Not null Integrity constraint cannot be defined using the alter
table command when the table contain rows.
Check Constraint:
Check constraint can be defined to allow only a particular range of values .when the
5
manipulation violates this constraint, the record will be rejected. Check condition
cannot contain sub queries.

14 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
b) Entity Integrity
Maintains uniqueness in a record. An entity represents a table and each row of a
table represents an instance of that entity. To identify each row in a table uniquely
we need to use this constraint. There are 2 entity constraints:
Unique key constraint
It is used to ensure that information in the column for each record is unique, as with
telephone or drivers license numbers. It prevents the duplication of value with rows
of a specified column in a set of column. A column defined with the constraint can
allow null value.
6 If unique key constraint is defined in more than one column i.e., combination of
column cannot be specified. Maximum combination of columns that a composite
unique key can contain is 16.
Primary Key Constraint
A primary key avoids duplication of rows and does not allow null values. It can be
defined on one or more columns in a table and is used to uniquely identify each row
in a table. These values should never be changed and should never be null.
A table should have only one primary key. If a primary key constraint is assigned to
more than one column or combination of column is said to be composite primary
key, which can contain 16 columns.
c) Referential Integrity
It enforces relationship between tables. To establish parent-child relationship
between 2 tables having a common column definition, we make use of this
constraint. To implement this, we should define the column in the parent table as
primary key and same column in the child table as foreign key referring to the
7 corresponding parent entry.
Foreign key
A column or combination of column included in the definition of referential
integrity, which would refer to a referenced key.
Referenced key
It is a unique or primary key upon which is defined on a column belonging to the
parent table.

o SQL Commands:

QUERY: 01

Q1. Write a query to create a table employee with empno, ename, designation, and salary.

Syntax for creating a table:

SQL: CREATE <OBJ.TYPE> <OBJ.NAME> (COLUMN NAME.1<DATATYPE> (SIZE),


COLUMN NAME.1 <DATATYPE> (SIZE)……………………………);

QUERY: 01

SQL>CREATE TABLE EMP (EMPNO NUMBER (4), ENAME VARCHAR2 (10),


DESIGNATIN VARCHAR2 (10), SALARY NUMBER (8,2));
Table created.

15 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
QUERY: 02

Q2. Write a query to display the column name and datatype of the table employee.

Syntax for describe the table:

SQL: DESC <TABLE NAME>; SQL>


DESC EMP;

Name Null? Type


----------------------------------------- -------- -------------
EMPNO NUMBER(4)
ENAME VARCHAR2(10)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2)
QUERY: 03

Q3. Write a query for create a from an existing table with all the fields

Syntax For Create A from An Existing Table With All Fields

SQL> CREATE TABLE <TRAGET TABLE NAME> SELECT * FROM <SOURCE TABLE
NAME>;

QUERY: 03
SQL> CREATE TABLE EMP1 AS SELECT * FROM EMP;
Table created.

SQL> DESC EMP1


Name Null? Type
----------------------------------------- -------- -------------
EMPNO NUMBER(4)
ENAME VARCHAR2(10)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2)

QUERY: 04

Q4. Write a query for create a from an existing table with selected fields

Syntax For Create A from An Existing Table With Selected Fields

SQL> CREATE TABLE <TRAGET TABLE NAME> SELECT EMPNO, ENAME FROM
<SOURCE TABLE NAME>;

QUERY: 04

SQL> CREATE TABLE EMP2 AS SELECT EMPNO, ENAME FROM EMP;


Table created.

16 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
SQL> DESC EMP2
Name Null? Type
----------------------------------------- -------- ----------------------
EMPNO NUMBER (4)
ENAME VARCHAR2 (10)
QUERY: 05

Q5. Write a query for create a new table from an existing table without any record:

Syntax for create a new table from an existing table without any record:

SQL> CREATE TABLE <TRAGET TABLE NAME> AS SELECT * FROM


<SOURCE TABLE NAME> WHERE <FALSE CONDITION>;

QUERY: 05
SQL> CREATE TABLE EMP3 AS SELECT * FROM EMP WHERE1>2;

Table created. SQL>

DESC EMP3;
Name Null? Type
----------------------------------------- -------- ------------------------
EMPNO NUMBER(4)
ENAME VARCHAR2(10)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2);

ALTER & MODIFICATION ON TABLE

QUERY: 06
Q6. Write a Query to Alter the column EMPNO NUMBER (4) TO EMPNO NUMBER
(6).

Syntax for Alter & Modify on a Single Column:

SQL > ALTER <TABLE NAME> MODIFY <COLUMN NAME> <DATATYPE>


(SIZE);

QUERY: 06
SQL>ALTER TABLE EMP MODIFY EMPNO NUMBER (6);

Table altered.
SQL> DESC EMP;
Name Null? Type
----------------------------------------- -------- ----------------------------
EMPNO NUMBER(6)
ENAME VARCHAR2(10)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2)
17 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
QUERY: 07
Q7. Write a Query to Alter the table employee with multiple columns (EMPNO,
ENAME.)

Syntax for alter table with multiple column:

SQL > ALTER <TABLE NAME> MODIFY <COLUMN NAME1> <DATATYPE> (SIZE),
MODIFY <COLUMN NAME2> <DATATYPE> (SIZE)
………………………………………….; QUERY: 07

SQL>ALTER TABLE EMP MODIFY (EMPNO NUMBER (7), ENAME


VARCHAR2(12));
Table altered.

SQL> DESC EMP;


Name Null? Type
----------------------------------------- -------- ----------------------------
EMPNO NUMBER(7)
ENAME VARCHAR2(12)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2);

QUERY: 08
Q8. Write a query to add a new column in to employee
Syntax for add a new column:
SQL> ALTER TABLE <TABLE NAME> ADD (<COLUMN NAME> <DATA TYPE>
<SIZE>);

QUERY: 08
SQL> ALTER TABLE EMP ADD QUALIFICATION VARCHAR2(6);
Table altered.

SQL> DESC EMP;


Name Null? Type
----------------------------------------- -------- ----------------------------
EMPNO NUMBER(7)
ENAME VARCHAR2(12)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2)
QUALIFICATION VARCHAR2(6)

QUERY: 09
Q9. Write a query to add multiple columns in to employee
Syntax for add a new column:
SQL> ALTER TABLE <TABLE NAME> ADD (<COLUMN NAME1> <DATA TYPE>
<SIZE>,(<COLUMN NAME2> <DATA TYPE> <SIZE>,
18 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
………………………………………………………………);

QUERY: 09

SQL>ALTER TABLE EMP ADD (DOB DATE, DOJ DATE);


Table altered. SQL>
DESC EMP;
Name Null? Type
----------------------------------------- -------- ----------------------------
EMPNO NUMBER(7)
ENAME VARCHAR2(12)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2)
QUALIFICATION VARCHAR2(6) DOB
DATE
DOJ DATE

REMOVE / DROP

QUERY: 10
Q10. Write a query to drop a column from an existing table employee
Syntax for add a new column:
SQL> ALTER TABLE <TABLE NAME> DROP COLUMN <COLUMN NAME>;

QUERY: 10

SQL> ALTER TABLE EMP DROP COLUMN DOJ;

Table altered. SQL>


DESC EMP;
Name Null? Type
----------------------------------------- -------- ------------- EMPNO
NUMBER(7)
ENAME VARCHAR2(12)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2)
QUALIFICATION VARCHAR2(6) DOB
DATE

QUERY: 11
Q10. Write a query to drop multiple columns from employee
Syntax for add a new column:
SQL> ALTER TABLE <TABLE NAME> DROP <COLUMN
NAME1>,<COLUMN NAME2>,…………………………….. ;

QUERY: 11

SQL> ALTER TABLE EMP DROP (DOB, QUALIFICATION);


19 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
Table altered.

SQL> DESC EMP;


Name Null? Type
----------------------------------------- -------- --------------
EMPNO NUMBER(7)
ENAME VARCHAR2(12)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2)

REMOVE

QUERY: 12
Q10. Write a query to rename table emp to employee
Syntax for add a new column:
SQL> ALTER TABLE RENAME <OLD NAME> TO <NEW NAME>

QUERY: 12

SQL> ALTER TABLE EMP RENAME EMP TO EMPLOYEE; SQL>


DESC EMPLOYEE;
Name Null? Type
----------------------------------------- -------- --------------
EMPNO NUMBER(7)
ENAME VARCHAR2(12)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2)

CONSTRAINTS
Constraints are part of the table definition that limits and restriction on the value
entered into its columns.

TYPES OF CONSTRAINTS:

1) Primary key
2) Foreign key/references
3) Check
4) Unique
5) Not null
6) Null
7) Default

CONSTRAINTS CAN BE CREATED IN THREE WAYS:

1) Column level constraints


2) Table level constraints
3) Using DDL statements-alter table command

20 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
OPERATION ON CONSTRAINT:
i) ENABLE
ii) DISABLE
iii) DROP

Column level constraints Using Primary key

Q13. Write a query to create primary constraints with column level

Primary key
Syntax for Column level constraints Using Primary key:
SQL:>CREATE <OBJ.TYPE> <OBJ.NAME> (COLUMN NAME.1 <DATATYPE>
(SIZE)<TYPE OF CONSTRAINTS> , COLUMN NAME.1 <DATATYPE> (SIZE)
……………………………);
QUERY:13

SQL>CREATE TABLE EMPLOYEE(EMPNO NUMBER(4) PRIMARYKEY,ENAME


VARCHAR2(10), JOB VARCHAR2(6), SAL NUMBER(5), DEPTNO NUMBER(7));

Column level constraints Using Primary key with naming convention

Q14. Write a query to create primary constraints with column level with naming convention

Syntax for Column level constraints Using Primary key:


SQL: >CREATE <OBJ.TYPE> <OBJ.NAME> (COLUMN NAME.1 <DATATYPE>
(SIZE)CONSTRAINTS <NAME OF THE CONSTRAINTS> <TYPE OF THE
CONSTRAINTS> , COLUMN NAME.1 <DATATYPE> (SIZE)
……………………………);

QUERY:14

SQL>CREATE TABLE EMPLOYEE(EMPNO NUMBER(4) CONSTRAINT


EMP_EMPNO_PK PRIMARY KEY,ENAME VARCHAR2(10), JOB VARCHAR2(6), SAL
NUMBER(5), DEPTNO NUMBER(7));

Table Level Primary Key Constraints


Q15. Write a query to create primary constraints with table level with naming convention

Syntax for Table level constraints Using Primary key:


SQL: >CREATE <OBJ.TYPE> <OBJ.NAME> (COLUMN NAME.1 <DATATYPE> (SIZE)
, COLUMN NAME.1 <DATATYPE> (SIZE), CONSTRAINTS <NAME OF THE
CONSTRAINTS> <TYPE OF THE CONSTRAINTS>);

21 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
QUERY: 15
SQL>CREATE TABLE EMPLOYEE (EMPNO NUMBER (6), ENAME VARCHAR2(20), JOB
VARCHAR2(6), SAL NUMBER(7), DEPTNO NUMBER(5),CONSTRAINT
EMP_EMPNO_PK PRIMARY KEY(EMPNO));

Table level constraint with alter command (primary key):

Q16. Write a query to create primary constraints with alter command

Syntax for Column level constraints Using Primary key:


SQL:>CREATE <OBJ.TYPE> <OBJ.NAME> (COLUMN NAME.1 <DATATYPE> (SIZE),
COLUMN NAME.1 <DATATYPE> (SIZE) );
SQL> ALTER TABLE <TABLE NAME> ADD CONSTRAINTS <NAME OF THE
CONSTRAINTS> <TYPE OF THE CONSTRAINTS> <COLUMN NAME>);

QUERY: 16
SQL>CREATE TABLE EMPLOYEE(EMPNO NUMBER(5),
ENAME VARCHAR2(6), JOB
VARCHAR2(6), SAL
NUMBER(6),
DEPTNO NUMBER(6));
SQL>ALTER TABLE EMP3 ADD CONSTRAINT EMP3_EMPNO_PK PRIMARY KEY
(EMPNO);

Reference /foreign key constraint


Column level foreign key constraint:

Q.17. Write a query to create foreign key constraints with column level
Parent Table:
Syntax for Column level constraints Using Primary key:
SQL:>CREATE <OBJ.TYPE> <OBJ.NAME> (COLUMN NAME.1 <DATATYPE>
(SIZE)<TYPE OF CONSTRAINTS> , COLUMN NAME.1 <DATATYPE> (SIZE)
……………………………);
Child Table:
Syntax for Column level constraints Using foreign key:
SQL:>CREATE <OBJ.TYPE> <OBJ.NAME> (COLUMN NAME.1 <DATATYPE> (SIZE),

22 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
COLUMN NAME2 <DATATYPE> (SIZE) REFERENCES <TABLE NAME>
(COLUMN NAME> ……………………………);

QUERY: 17
SQL>CREATE TABLE DEPT(DEPTNO NUMBER(2) PRIMARY KEY,
DNAME VARCHAR2(20),
LOCATION VARCHAR2(15));

SQL>CREATE TABLE EMP4 (EMPNO


NUMBER(3),
DEPTNO NUMBER(2) REFERENCES DEPT(DEPTNO),
DESIGN VARCHAR2(10));

Column level foreign key constraint with naming conversions:

Parent Table:
Syntax for Column level constraints Using Primary key:
Q.18. Write a query to create foreign key constraints with column level

SQL:>CREATE <OBJ.TYPE> <OBJ.NAME> (COLUMN NAME.1 <DATATYPE>


(SIZE)<TYPE OF CONSTRAINTS> , COLUMN NAME.1 <DATATYPE> (SIZE)
……………………………);
Child Table:
Syntax for Column level constraints using foreign key:
SQL:>CREATE <OBJ.TYPE> <OBJ.NAME> (COLUMN NAME.1 <DATATYPE> (SIZE) ,
COLUMN NAME2 <DATATYPE> (SIZE) CONSTRAINT <CONST. NAME>
REFERENCES <TABLE NAME> (COLUMN NAME>
……………………………);

QUERY:18

SQL>CREATE TABLE DEPT(DEPTNO NUMBER(2) PRIMARYKEY,DNAME


VARCHAR2(20), LOCATION VARCHAR2(15));

SQL>CREATE TABLE EMP4A (EMPNO NUMBER(3),


DEPTNO NUMBER(2)CONSTRAINT EMP4A_DEPTNO_FK REFERENCES
DEPT(DEPTNO),DESIGN VARCHAR2(10));

Table Level Foreign Key Constraints


Q.19. Write a query to create foreign key constraints with Table level
Parent Table:
SQL:>CREATE <OBJ.TYPE> <OBJ.NAME> (COLUMN NAME.1 <DATATYPE>
(SIZE)<TYPE OF CONSTRAINTS> , COLUMN NAME.1 <DATATYPE> (SIZE)

23 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
……………………………);
Child Table:
Syntax for Table level constraints using foreign key:
SQL:>CREATE <OBJ.TYPE> <OBJ.NAME> (COLUMN NAME.1 <DATATYPE> (SIZE),
COLUMN NAME2 <DATATYPE> (SIZE), CONSTRAINT <CONST. NAME>
REFERENCES <TABLE NAME> (COLUMN NAME> );

QUERY: 19
SQL>CREATE TABLE DEPT(DEPTNO NUMBER(2) PRIMARY KEY, DNAME
VARCHAR2(20),LOCATION VARCHAR2(15));

SQL>CREATE TABLE EMP5 (EMPNO NUMBER(3),DEPTNO NUMBER(2),DESIGN


VARCHAR2(10)CONSTRAINT ENP2_DEPTNO_FK FOREIGN KEY(DEPT
NO)REFERENCESDEPT(DEPTNO));

Table Level Foreign Key Constraints with Alter command


Q.20. Write a query to create foreign key constraints with Table level with alter
command.
Parent Table:
SQL:>CREATE <OBJ.TYPE> <OBJ.NAME> (COLUMN NAME.1 <DATATYPE>
(SIZE)<TYPE OF CONSTRAINTS> , COLUMN NAME.1 <DATATYPE> (SIZE)
……………………………);

Child Table:
Syntax for Table level constraints using foreign key:
SQL:>CREATE <OBJ.TYPE> <OBJ.NAME> (COLUMN NAME.1 <DATATYPE> (SIZE) ,
COLUMN NAME2 <DATATYPE> (SIZE));

SQL> ALTER TABLE <TABLE NAME> ADD CONSTRAINT <CONST. NAME>


REFERENCES <TABLE NAME> (COLUMN NAME>);
QUERY:20

SQL>CREATE TABLE DEPT (DEPTNO NUMBER(2) PRIMARY KEY, DNAME


VARCHAR2(20),LOCATION VARCHAR2(15));

SQL>CREATE TABLE EMP5 (EMPNO NUMBER(3), DEPTNO NUMBER(2), DESIGN


VARCHAR2(10));

SQL>ALTER TABLE EMP6 ADD CONSTRAINT EMP6_DEPTNO_FK FOREIGN


KEY(DEPTNO)REFERENCES DEPT(DEPTNO);
24 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
Check constraint
Column Level Check Constraint
Q.21. Write a query to create Check constraints with column level
Syntax for clumn level constraints using Check:
SQL:>CREATE <OBJ.TYPE> <OBJ.NAME> (COLUMN NAME.1 <DATATYPE> (SIZE)
CONSTRAINT <CONSTRAINTS NAME> <TYPE OF CONSTRAINTS> (CONSTRAITNS
CRITERIA) , COLUMN NAME2 <DATATYPE> (SIZE));

QUERY:21

SQL>CREATE TABLE EMP7(EMPNO NUMBER(3), ENAME VARCHAR2(20),


DESIGN VARCHAR2(15),SAL NUMBER(5)CONSTRAINT EMP7_SAL_CK
CHECK(SAL>500 AND SAL<10001),DEPTNO NUMBER(2));

Table Level Check Constraint:


Q.22. Write a query to create Check constraints with table level
Syntax for Table level constraints using Check:
SQL:>CREATE <OBJ.TYPE> <OBJ.NAME> (COLUMN NAME.1 <DATATYPE> (SIZE),
(COLUMN NAME2 <DATATYPE> (SIZE), CONSTRAINT
<CONSTRAINTS NAME> <TYPE OF CONSTRAINTS> (CONSTRAITNS CRITERIA)) ;

QUERY:22

SQL>CREATE TABLE EMP8(EMPNO NUMBER(3), ENAME VARCHAR2(20),


DESIGN VARCHAR2(15),SAL NUMBER(5),DEPTNO NUMBER(2), CONSTRAINTS
EMP8_SAL_CK CHECK(SAL>500 AND SAL<10001));

Check Constraint with Alter Command


Q.23. Write a query to create Check constraints with table level using alter command.
Syntax for Table level constraints using Check:
SQL:>CREATE <OBJ.TYPE> <OBJ.NAME> (COLUMN NAME.1 <DATATYPE> (SIZE),
(COLUMN NAME2 <DATATYPE> (SIZE), CONSTRAINT
<CONSTRAINTS NAME> <TYPE OF CONSTRAINTS> (CONSTRAITNS CRITERIA)) ;

QUERY:23
SQL>CREATE TABLE EMP9(EMPNO NUMBER, ENAME VARCHAR2(20),DESIGN

25 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
VARCHAR2(15), SAL NUMBER(5));

SQL>ALTER TABLE EMP9 ADD CONSTRAINTS EMP9_SAL_CK CHECK (SAL>500 AND


SAL<10001);

Unique Constraint
Column Level Constraint
Q.24. Write a query to create unique constraints with column level

Syntax for Column level constraints with Unique:


SQL :> CREATE <OBJ.TYPE> <OBJ.NAME> (<COLUMN NAME.1>
<DATATYPE> (SIZE) CONSTRAINT <NAME OF CONSTRAINTS>
<CONSTRAINT TYPE>, (COLUMN NAME2 <DATATYPE> (SIZE)) ;

QUERY:24

SQL>CREATE TABLE EMP10(EMPNO NUMBER(3), ENAME


VARCHAR2(20),
DESGIN VARCHAR2(15)CONSTRAINT EMP10_DESIGN_UK UNIQUE, SAL
NUMBER(5));

Table Level Constraint


Q.25. Write a query to create unique constraints with table level
Syntax for Table level constraints with Unique:
SQL :> CREATE <OBJ.TYPE> <OBJ.NAME> (<COLUMN NAME.1>
<DATATYPE> (SIZE), (COLUMN NAME2 <DATATYPE> (SIZE), CONSTRAINT
<NAME OF CONSTRAINTS> <CONSTRAINT TYPE>(COLUMN NAME);) ;

QUERY:25

SQL>CREATE TABLE EMP11(EMPNO NUMBER(3), ENAME


VARCHAR2(20),
DESIGN VARCHAR2(15),
SAL NUMBER(5),CONSTRAINT EMP11_DESIGN_UK UNIGUE(DESIGN));

Table Level Constraint Alter Command


Q.26. Write a query to create unique constraints with table level
Syntax for Table level constraints with Check Using Alter
SQL :> CREATE <OBJ.TYPE> <OBJ.NAME> (<COLUMN NAME.1>
<DATATYPE> (SIZE), (COLUMN NAME2 <DATATYPE> (SIZE)) ;

SQL> ALTER TABLE ADD <CONSTRAINTS> <CONSTRAINTS NAME>


<CONSTRAINTS TYPE>(COLUMN NAME);
26 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
QUERY:26

SQL>CREATE TABLE EMP12 (EMPNO NUMBER(3), ENAME VARCHAR2(20), DESIGN


VARCHAR2(15), SAL NUMBER(5));

SQL>ALTER TABLE EMP12 ADD CONSTRAINT EMP12_DESIGN_UK


UNIQUE(DESING);

Not Null

Column Level Constraint


Q.27. Write a query to create Not Null constraints with column level
Syntax for Column level constraints with Not Null:
SQL :> CREATE <OBJ.TYPE> <OBJ.NAME> (<COLUMN NAME.1><DATATYPE> (SIZE)
CONSTRAINT <NAME OF CONSTRAINTS><CONSTRAINT TYPE>, (COLUMN NAME2
<DATATYPE> (SIZE)) ;

QUERY: 27
SQL>CREATE TABLE EMP13 (EMPNO NUMBER(4),ENAME VARCHAR2(20)
CONSTRAINT EMP13_ENAME_NN NOT NULL, DESIGN VARCHAR2(20), SAL
NUMBER(3));

Null

Column Level Constraint


Q.28. write a query to create Null constraints with column level
Syntax for Column level constraints with Null:
SQL :> CREATE <OBJ.TYPE> <OBJ.NAME> (<COLUMN NAME.1><DATATYPE> (SIZE)
CONSTRAINT <NAME OF CONSTRAINTS><CONSTRAINT TYPE>, (COLUMN NAME2
<DATATYPE> (SIZE)) ;

QUERY:28
SQL>CREATE TABLE EMP13 (EMPNO NUMBER(4),ENAME VARCHAR2(20)
CONSTRAINT EMP13_ENAME_NN NULL, DESIGN VARCHAR2(20), SAL NUMBER(3));

Constraint Disable \ Enable


Constraint Disable
Q.29. write a query to disable the constraints
Syntax for disabling a single constraint in a table:
27 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
SQL>ALTER TABLE <TABLE-NAME> DISABLE CONSTRAINT <CONSTRAINT- NAME>

Constraint Enable
QUERY:29
SQL>ALTER TABLE EMP13 DISABLE CONSTRAINT EMP13_ENAME_NN NULL;

Q.30. Write a query to enable the constraints


Syntax for disabling a single constraint in a table:
SQL>ALTER TABLE <TABLE-NAME> DISABLE CONSTRAINT <CONSTRAINT- NAME>

QUERY:30
SQL>ALTER TABLE EMP13 ENABLE CONSTRAINT EMP13_ENAME_NN NULL;

Result: Thus we have executed all DDL queries.

28 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
Practical Number 3
Title of the Exercise : DATA MANIPULATION LANGUAGE (DML) COMMANDS
Date of the Exercise :
AIM OF THE EXPERIMENT
To study the various DML commands and implement them on the database.

PROCEDURE
a) Procedure for doing the experiment:
Step
Details of the step
no.
DML COMMAND
1 DML commands are the most frequently used SQL commands and is used to query
and manipulate the existing database objects. Some of the commands are Insert,
Select, Update, Delete
Insert Command
This is used to add one or more rows to a table. The values are separated by commas
2
and the data types char and date are enclosed in apostrophes. The values must be
entered in the same order as they are defined.
Select Commands
It is used to retrieve information from the table. it is generally referred to as querying
3
the table. We can either display all columns in a table or only specify column
from the table.
Update Command
4 It is used to alter the column values in a table. A single column may be updated or
more than one column could be updated.
Delete command
5 After inserting row in a table we can also delete them if required. The delete
command consists of a from clause followed by an optional where clause.

a) SQL
Commands:
INSERT
COMMAND
Inserting a single row into a table:
Syntax: insert into <table name> values (value list)
Example: insert into s values(„s3‟,‟sup3‟,‟blore‟,10)

Inserting more than one record using a single insert commands:


Syntax: insert into <table name> values (&col1, &col2, ….)
Example: Insert into stud values(&reg, „&name‟,
&percentage);

Skipping the fields while inserting:


Insert into <tablename(coln names to which datas to b inserted)> values (list of values); Other way
is to give null while passing the values.

29 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
SELECT COMMANDS
Selects all rows from the table
Syntax: Select * from tablename;
Example; Select * from IT;

The retrieval of specific columns from a table:


It retrieves the specified columns from the table
Syntax: Select column_name1, …..,column_namen from table name;
Example: Select empno, empname from emp;

Elimination of duplicates from the select clause:


It prevents retriving the duplicated values .Distinct keyword is to be used.
Syntax: Select DISTINCT col1, col2 from table name;
Example: Select DISTINCT job from emp;

Select command with where clause:


To select specific rows from a table we include „where‟ clause in the select command. It
can appear only after the „from‟ clause.
Syntax: Select column_name1, …..,column_namen from table name where condition;
Example: Select empno, empname from emp where sal>4000;

Select command with order by clause:


Syntax: Select column_name1, …..,column_namen from table name where condition
order by colmnname;
Example: Select empno, empname from emp order by empno;

Select command to create a table:


Syntax: create table tablename as select * from existing_tablename;
Example: create table emp1 as select * from emp;

Select command to insert records:


Syntax: insert into tablename ( select columns from existing_tablename);
Example: insert into emp1 ( select * from emp);

UPDATE COMMAND
Syntax: update tablename set field=values where condition;
Example: Update emp set sal = 10000 where empno=135;

DELETE COMMAND
Syntax: Delete from table where conditions;
Example: delete from emp where empno=135;

30 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
Q1: Insert a single record into dept table.
Solution:
1.Decide the data to add in dept.
2.Add to dept one row at a time using the insert into syntax.

Ans:
SQL> insert into dept values (1,'IT','Tholudur'); 1 row created.

Q2: Insert more than a record into emp table using a single insert command. Ans:
SQL> insert into emp values(&empno,'&ename','&job',&deptno,&sal);
Enter value for empno: 1
Enter value for ename: Mathi
Enter value for job: AP
Enter value for deptno: 1
Enter value for sal: 10000
old 1: insert into emp values(&empno,'&ename','&job',&deptno,&sal)
new 1: insert into emp values(1,'Mathi','AP',1,10000)
1 row created.
SQL> /
Enter value for empno: 2
Enter value for ename: Arjun
Enter value for job: ASP
Enter value for deptno: 2
Enter value for sal: 12000
old 1: insert into emp values(&empno,'&ename','&job',&deptno,&sal)
new 1: insert into emp values(2,'Arjun','ASP',2,12000)
1 row created.
SQL> /
Enter value for empno: 3
Enter value for ename:
Gugan Enter value for job:
ASP Enter value for deptno:
1 Enter value for sal: 12000
old 1: insert into emp values(&empno,'&ename','&job',&deptno,&sal)
new 1: insert into emp values(3,'Gugan','ASP',1,12000)
1 row created.

Q3. Update the emp table to set the salary of all employees to Rs15000/- who are working as
ASP
Ans:
SQL> select * from emp;
EMPNO ENAME JOB DEPTNO SAL
---------- -------------------- ------------- ---------- ----------

1 Mathi AP 1 10000
2 Arjun ASP 2 12000
3 Gugan ASP 1 12000
SQL> update emp set sal=15000 where job='ASP'; 2 rows updated.

31 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
SQL> select * from emp;
EMPNO ENAME JOB DEPTNO SAL
---------- -------------------- ------------- ---------- ----------

1 Mathi AP 1 10000
2 Arjun ASP 2 15000
3 Gu gan ASP 1 15000
Q4: Create a pseudo table employee with the same structure as the table emp and insert rows
into the table using select clauses.
Ans:
SQL> create table employee as select * from emp; Table created.
SQL> desc employee;
Name Null? Type
----------------------------------------- -------- ----------------------------
EMPNO NUMBER(6)
ENAME NOT NULL VARCHAR2(20)
JOB NOT NULL VARCHAR2(13)
DEPTNO NUMBER(3)
SAL NUMBER(7,2)

Q5: select employee name, job from the emp table Ans:
SQL> select ename, job from emp; ENAME JOB
-------------------- -------------
Mathi AP
Arjun ASP
Gugan ASP
Karthik Prof
Akalya AP
suresh lect 6 rows selected.
Q6: Delete only those who are working as lecturer
Ans:
SQL> select * from emp;
EMPNO ENAME JOB DEPTNO SAL
---------- -------------------- ------------- ---------- ----------

1 Mathi AP 1 10000
2 Arjun ASP 2 15000
3 Gugan ASP 1 15000
4 Karthik Prof 2 30000
5 Akalya AP 1 10000
6 suresh Lect 1 8000
6 rows selected.
SQL> delete from emp where job='lect'; 1 row deleted.
SQL> select * from emp;
EMPNO ENAME JOB DEPTNO SAL
---------- -------------------- ------------- ---------- ----------

32 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
1 Mathi AP 1 10000
2 Arjun ASP 2 15000
3 Gugan ASP 1 15000
4 Karthik Prof 2 30000
5 Akalya AP 1 10000
Q7: List the records in the emp table orderby salary in ascending order. Ans:
SQL> select * from emp order by sal;
EMPNO ENAME JOB DEPTNO SAL
---------- -------------------- ------------- ---------- ----------

1 Mathi AP 1 10000
5 Akalya AP 1 10000
2 Arjun ASP 2 15000
3 Gugan ASP 1 15000
4 Karthik Prof 2 30000
Q8: List the records in the emp table orderby salary in descending order. Ans:
SQL> select * from emp order by sal desc;
EMPNO ENAME JOB DEPTNO SAL
---------- -------------------- ------------- ---------- ----------

4 Karthik Prof 2 30000


2 Arjun ASP 2 15000
3 Gugan ASP 1 15000
1 Mathi AP 1 10000
5 Akalya AP 1 10000
Q9: Display only those employees whose deptno is 30.
Solution:
1. Use SELECT FROM WHERE syntax.
Ans:
SQL> select * from emp where deptno=1;

EMPNO ENAME JOB DEPTNO SAL


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

1 Mathi AP 1 10000
3 Gugan ASP 1 15000
5 Akalya AP 1 10000

Q10: Display deptno from the table employee avoiding the duplicated values.
Solution:
1. Use SELECT FROM syntax.
2. Select should include distinct clause for the deptno.
Ans:
SQL> select distinct deptno from emp;
DEPTNO
----------
1
2

Result: Thus we have executed all DML queries.


33 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
Practical Number: 4

Title of the Exercise : IN BUILT FUNCTIONS


Date of the Exercise :

OBJECTIVE (AIM) OF THE EXPERIMENT


To perform queries using various inbuilt function.

PROCEDURE
a) Procedure for doing the experiment:
Step Details of the step
no.
Function is a group of code that accepts zero or more arguments and both return one
or more results. Both are used to manipulate individual data items. Operators differ
1 from functional in that they follow the format of function name (arg..). An argument
is a user defined variables or constants. Most operators accept at most 2 arguments
while the structure of functions permit to accept 3 or more arguments. Function can
be classifies into single row function and group functions.
Single Row functions
A single row function or scalar function returns only one value for every row queries
in table. Single row function can appear in a select command and can also be
included in a where clause. The single row function can be broadly classified as, o
2 Date Function
o Numeric Function
o Character Function
o Conversion Function
o Miscellaneous Function
The example that follows mostly uses the symbol table “dual”. It is a table, which is
automatically created by oracle along with the data dictionary.
Date Function
3 They operate on date values and produce outputs, which also belong to date data type
except for months, between, date function returns a number.
4 Group Functions
A group function returns a result based on group of rows

b) SQL Commands: DATE FUNCTION

1. Sysdate
This function is used to retrieve the current database system time in Oracle and MySQL. A
common use of SYSDATE is to get today's date.
Syntax: sysdate
Example: Select sysdate from dual;

2. Add_month
This function returns a date after adding a specified date with specified number of months.
Syntax: Add_months(d,n); where d-date n-number of months
Example: Select add_months(sysdate,2) from dual;

3. last_day
It displays the last date of that month.
Syntax: last_day (d); where d-date
Example: Select last_day (‘1-jun-2009’) from dual;
34 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
4. Months_between
It gives the difference in number of months between d1 & d2.
Syntax: month_between (d1,d2); where d1 & d2 -dates
Example: Select months_between (‘1-jun-2009’,’1-aug-2009’) from dual;

5. next_day
It returns a day followed the specified date.
Syntax: next_day (d,day);
Example: Select next_day (sysdate,‟wednesday‟) from dual

6. round
This function returns the date, which is rounded to the unit specified by the format model.
Syntax : round (d,[fmt]);

where d- date, [fmt] – optional.By default date will be rounded to the nearest day

Example:
Select round (to_date(„1-jun-2009‟,‟dd-mm-yy‟),‟year‟) from dual;
Select round (‘1-jun-2009’,‟year‟) from dual;

NUMERICAL FUNCTIONS
Command Query Output

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


Ceil(n) Select ceil(55.67) from dual; 56
Exp(n) Select exp(4) from dual; 54.59
Floor(n) Select floor(100.2) from dual; 100
Power(m,n) Select power(4,2) from dual; 16
Mod(m,n) Select mod(10,3) from dual; 1
Round(m,n) Select round(100.256,2) from dual; 100.26
Trunc(m,n) Select trunc(100.256,2) from dual; 100.23
Sqrt(m,n) Select sqrt(16) from dual; 4

CHARACTER FUNCTIONS

Command Query Output

initcap(char); select initcap(‘hello’) from dual; Hello


lower (char); select lower (‘HELLO’) from dual; hello
upper (char); select upper (‘hello’) from dual; HELLO
trim(char); select trim(‘ hello ‘ );
ltrim (char,[set]); select ltrim (‘cseit’, ‘cse’) from dual; it
rtrim (char,[set]); select rtrim (‘cseit, ‘it’) from dual; cse
replace (char,search select replace(‘jack and jue’,’j’,’bl’) from dual; black and
string, replace string); blue
substr (char,m,n); select substr (‘information’, 3, 4) from dual; Form

CONVERSION FUNCTION
1. to_char()
Syntax: to_char(d,[format]);
This function converts date to a value of varchar type in a form specified by date format. If format
is negelected then it converts date to varchar2 in the default date format.
35 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
Example: select to_char (sysdate, ‘dd-mm-yy’) from dual;

2. to_date()
Syntax: to_date(d,[format]);
This function converts character to date data format specified in the form character.
Example: select to_date(‘aug 15 2009’,’mm-dd-yy’) from dual;

Miscellaneous Functions
1. uid – This function returns the integer value (id) corresponding to the user currently logged in.
Example: select uid from dual;
2. user – This function returns the logins user name.
Example: select user from dual;
3. nvl – The null value function is mainly used in the case where we want to consider null values as
zero.

Syntax; nvl(exp1, exp2)


If exp1 is null, return exp2. If exp1 is not null, return exp1.
Example: select custid, shipdate, nvl(total,0) from order;

4. vsize: It returns the number of bytes in expression.


Example: select vsize(‘tech’) from dual;

GROUP FUNCTIONS
A group function returns a result based on group of rows.
1. avg - Example: select avg (total) from student;
2. max - Example: select max (percentagel) from student;
3. min - Example: select min (marksl) from student;
4. sum - Example: select sum(price) from product;

COUNT FUNCTION
In order to count the number of rows, count function is used.
1. count(*) – It counts all, inclusive of duplicates and nulls.
Example: select count(*) from student;
2. count(col_name)– It avoids null value.
Example: select count(total) from order;
2. count(distinct col_name) – It avoids the repeated and null values.
Example: select count(distinct ordid) from order;

GROUP BY CLAUSE
This allows us to use simultaneous column name and group functions.
Example: Select max(percentage), deptname from student group by deptname;

HAVING CLAUSE
This is used to specify conditions on rows retrieved by using group by clause. Example: Select
max(percentage), deptname from student group by deptname having count(*)>=50;

SPECIAL OPERATORS:
In / not in – used to select a equi from a specific set of values
Any - used to compare with a specific set of values Between / not between – used to find between
the ranges Like / not like – used to do the pattern matching

36 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
a) Queries:
Q1: Display all the details of the records whose employee name starts with ‗A‘.
Solution:
1. Use SELECT FROM WHERE syntax.
2. Select should include all in the given format.
3. from should include employee
4. where should include condition on empname like „A%‟.

Ans:
SQL> select * from emp where ename like 'A%';
EMPNO ENAME JOB DEPTNO SAL
---------- -------------------- ------------- ---------- ----------

2 Arjun ASP 2 15000


5 Akalya AP 1 10000

Q2: Display all the details of the records whose employee name does not starts with ‗A‘.
Ans:
SQL> select * from emp where ename not like 'A%';

EMPNO ENAME JOB DEPTNO SAL


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

1 Mathi AP 1 10000
3 Gugan ASP 1 15000
4 Karthik Prof 2 30000

Q3: Display the rows whose salary ranges from 15000 to 30000.
Ans:
SQL> select * from emp where sal between 15000 and 30000;

EMPNO ENAME JOB DEPTNO SAL


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

2 Arjun ASP 2 15000


3 Gugan ASP 1 15000
4 Karthik Prof 2 30000

Q4: Calculate the total and average salary amount of the emp table.
Ans:
SQL> select sum(sal),avg(sal) from emp;
SUM(SAL) AVG(SAL)
---------- ----------
80000 16000

Q5: Count the total records in the emp table.


Ans:
SQL>select * from emp;
EMPNO ENAME JOB DEPTNO SAL
------ -------------------- ------------- ---------- ----------

1 Mathi AP 1 10000
2 Arjun ASP 2 15000

37 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
3 Gugan ASP 1 15000
4 Karthik Prof 2 30000
5 Akalya AP 1 10000
SQL> select count(*) from emp;
COUNT(*)
---------
5

Q6: Determine the max and min salary and rename the column as max_salary and
min_salary.
Solution:
1. Use the MIN & MAX aggregate function in select clause.
2. Rename the column as min_sal & max_sal.
Ans:
SQL> select max(sal) as max_salary, min(sal) as min_salary from emp;
MAX_SALARY MIN_SALARY
---------- ----------
30000 10000
Q7: Display the month between ―1-jun-10‖and 1-aug-10 in full.
Ans:
SQL>Select month_between („1-jun-2010‟,‟1-aug-2010‟) from dual;

Q8: Display the last day of that month in ―05-Oct-09‖.


Ans:
SQL> Select last_day ('1-jun-2009') from dual;

LAST_DAY(
---------
30-JUN-09

Q9: Find how many job titles are available in employee table.
Solution:
1. Use select from clause.
2. Use count function to get the result.
Ans:
SQL> select count(job) from emp; COUNT(JOB)
----------
4
SQL> select count(distinct job) from emp; COUNT(DISTINCTJOB)
------------------
2
Q10: What is the difference between maximum and minimum salaries of employees in the
organization?
Solution:
1. Use select from clause.
2. Use function max(),min() and find the difference between them to get the result.
Ans:
SQL> select max(sal), min(sal) from emp;
MAX(SAL) MIN(SAL)
---------- ----------
20000 10000

Result: Thus we have studied various SQL function and execute different queries.
38 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
Practical Number: 5
Title of the Exercise : SET OPERATORS
Date of the Exercise :

OBJECTIVE (AIM) OF THE EXPERIMENT


To perform set operations using DML Commands.

PROCEDURE
a) Procedure for doing the experiment:

Step Details of the step


no.
Set Operators:
The Set operator combines the result of 2 queries into a single result. The following
1 are the operators:
 Union
 Union all
 Intersect
 Minus
The rules to which the set operators are strictly adhere to :
· The queries which are related by the set operators should have a same number of
2 column and column definition.
· Such query should not contain a type of long.
· Labels under which the result is displayed are those from the first select statement.

b) SQL commands:
Union: Returns all distinct rows selected by both the queries
Syntax:
Query1 Union Query2;

Union all: Returns all rows selected by either query including the duplicates.
Syntax:
Query1 Union all Query2;

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


Syntax:
Query1 Intersect Query2;

Minus: Returns all distinct rows selected by the first query and are not by the second
Syntax:
Query1 minus Query2;

EXCEPT
EXCEPT clause in SQL Server is working as like MINUS operation in Oracle. EXCEPT query
returns all rows which are in the first query but those are not returned in the second query.

39 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
c) Queries:

UNION:
Q1: Display all the dept numbers available with the dept and emp tables avoiding duplicates.
Solution:
1. Use select from clause.
2. Use union select clause to get the result.
Ans:
SQL> select deptno from emp union select deptno from dept;

DEPTNO
----------
1
2
12
30
40

1. Get the names of employees who are married or earn over 30,000.

SQL> SELECT EMP_NAME FROM EMP WHERE MARITAL_STATUS = 'M'


UNION
SELECT EMP_NAME FROM EMP WHERE SALARY > 30000;

EMP_NAME
----------
Brown
Green
Jarvis
Jones

2.Get the names of departments with budgets in excess of 140,000 or that are managed by
employee E8.

SQL> SELECT DEPT_NAME FROM DEPT WHERE BUDGET > 140000


UNION
SELECT DEPT_NAME FROM DEPT WHERE MANAGER_NO = 'E8';

DEPT_NAME
----------
Accounts
Sales
Transport

3. Find the Project Numbers of projects which have a deadline before 01-Jan-2008 or have
employee E3 working on them.

SQL> SELECT PROJ_NO FROM PROJ WHERE DEADLINE < '01-JAN-2008'


UNION
SELECT PROJ_NO FROM ALLOC WHERE EMP_NO = 'E3';

PR
--

40 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
P2

4. List the Employee Numbers of employees who either manage the Sales Department or
work on project P4.

SQL> SELECT MANAGER_NO FROM DEPT WHERE DEPT_NAME = 'Sales'


UNION
SELECT EMP_NO FROM ALLOC WHERE PROJ_NO = 'P4';

MA
--
E4
E5
E6
E9

5. Get the names of employees with their salaries and of departments with their budgets.

SQL> SELECT EMP_NAME, SALARY FROM EMP


UNION
SELECT DEPT_NAME, BUDGET FROM DEPT;

EMP_NAME SALARY
---------- ----------
Accounts 95000
Brown 38500
Evans 11000
Fletcher 12000
Green 38500
Jarvis 21000
Jones 12000
Production 100000
Roberts 20000
Sales 250000
Transport 150000
11 rows selected.

Q6: Display all the dept numbers available with the dept and emp tables.
Solution:
1. Use select from clause. 2. Use union all in select clause to get the result.
Ans:
SQL> select deptno from emp union all select deptno from dept;

DEPTNO
----------
1
2
2
1
12
1
2
30
40
9 rows selected.

41 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
INTERSECT:
1. Get the names of employees who are married and earn more than £15,000.
SQL> SELECT EMP_NAME FROM EMP WHERE MARITAL_STATUS = 'M'
INTERSECT
SELECT EMP_NAME FROM EMP WHERE SALARY > 15000;
EMP_NAME
----------
Jarvis

2. Get the names of departments not managed by employee E5 that have budgets of more
than£96,000.
SQL> SELECT DEPT_NAME FROM DEPT WHERE MANAGER_NO <> 'E5'
INTERSECT
SELECT DEPT_NAME FROM DEPT WHERE BUDGET > 96000;

DEPT_NAME
----------
Production
Transport

3. List the EmployeeNumbers of department managers who are paid less than £12,500.
SQL> SELECT MANAGER_NO FROM DEPT
INTERSECT
SELECT EMP_NO FROM EMP WHERE SALARY < 12500;

MA
--
E2

4. Get the Project Numbers of projects that started after 10-Jun-2005 and have employee E4
working on them.
SQL> SELECT PROJ_NO FROM PROJ WHERE START_DATE > '10-Jun-2005'
INTERSECT
SELECT PROJ_NO FROM ALLOC WHERE EMP_NO = 'E4';
PR
--
P4

5. Get the Employee Numbersof managers who are also working on projects.
SQL> SELECT MANAGER_NO FROM DEPT
INTERSECT
SELECT EMP_NO FROM ALLOC;

MA
--
E2
E5

MINUS:
1. Get the names of employees known to be single who do not earn more than £13,000.
SQL> SELECT EMP_NAME FROM EMP WHERE MARITAL_STATUS = 'S'
MINUS
SELECT EMP_NAME FROM EMP WHERE SALARY > 13000;

EMP_NAME
----------
Evans
Fletcher

2. Get the salaries of every employee apart from those working for department D2.
SQL> SELECT SALARY FROM EMP
MINUS

42 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
SELECT SALARY FROM EMP WHERE DEPT_NO = 'D2';

SALARY
----------
11000
12000
20000
21000
3. Find the EmployeeNumbers of employees who do not manage a department.
SQL> SELECT EMP_NO FROM EMP
MINUS
SELECT MANAGER_NO FROM DEPT;

EM
--
E4
E6
E9

4. Get the Employee Numbers of those employees who are not working on any projects.
SQL> SELECT EMP_NO FROM EMP
2 MINUS
3 SELECT EMP_NO FROM ALLOC;

EM
--
E3
E8

5. Get the Employee Numbers of employees paid more than £15,000apart from those who
manage departments with a budget of £100,000 or less

SQL> SELECT EMP_NO FROM EMP WHERE SALARY > 15000


2 MINUS
3 SELECT MANAGER_NO FROM DEPT WHERE BUDGET <= 100000;
EM
--
E5
E6

Q6: Display all the dept numbers available in emp and not in dept tables and vice versa.
Solution:
1. Use select from clause.
2. Use minus in select clause to get the result.
Ans:
SQL> select deptno from emp minus select deptno from dept;

DEPTNO
----------
12
SQL> select deptno from dept minus select deptno from emp; DEPTNO
----------
30
40

d) Result:
Thus the set operations using DML Commands was successfully performed and executed.

43 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
Practical Number: 6
Title of the Exercise : NESTED QUERIES AND JOIN QUERIES
Date of the Exercise :

OBJECTIVE (AIM) OF THE EXPERIMENT


To perform nested Queries and joining Queries using DML command.

a) Procedure:
Step
Details of the step
no.
Nested Queries: Nesting of queries one within another is known as a nested
queries.
1 Sub queries The query within another is known as a sub query. A statement
containing sub query is called parent statement. The rows returned by sub query are
used by the parent statement.
Types
1. Sub queries that return several values
Sub queries can also return more than one value. Such results should be made use
along with the operators in and any.
2. Multiple queries
2
Here more than one sub query is used. These multiple sub queries are combined by
means of „and‟ & „or‟ keywords
3. Correlated sub query
A sub query is evaluated once for the entire parent statement whereas a correlated
Sub query is evaluated once per row processed by the parent statement.

b) SQL Commands:

Nested Queries:
A subquery is a SELECT statement written within parentheses and nested inside another statement.
Here’s an example that looks up the IDs for grade event rows that correspond to tests ('T') and
uses them to select scores for those tests
SELECT * FROM score
WHERE event_id IN (SELECT event_id FROM grade_event WHERE category = 'T');

Subqueries can return different types of information:

 A scalar subquery returns a single value.


 A column subquery returns a single column of one or more values.
 A row subquery returns a single row of one or more values.
 A table subquery returns a table of one or more rows of one or more columns.

Subquery results can be tested in different ways:

 Scalar subquery results can be evaluated using relative comparison operators such as = or <.
 IN and NOT IN test whether a value is present in a set of values returned by a subquery.
 ALL, ANY, and SOME compare a value to the set of values returned by a subquery.
 EXISTS and NOT EXISTS test whether a subquery result is empty.

44 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
A scalar subquery is the most restrictive because it produces only a single value. But as a
consequence, scalar subqueries can be used in the widest variety of contexts. They are applicable
essentially anywhere that you can use a scalar operand, such as a term of an expression, as a
function argument, or in the output column list. Column, row, and table subqueries that return
more information cannot be used in contexts that require a single value.

Subqueries can be correlated or uncorrelated. This is a function of whether a subquery refers to and
is dependent on values in the outer query.

You can use subqueries with statements other than SELECT. However, for statements that modify
tables (DELETE, INSERT, REPLACE, UPDATE, LOAD DATA), MySQL enforces the restriction that the
subquery cannot select from the table being modified.

In some cases, subqueries can be rewritten as joins. You might find subquery rewriting techniques
useful to see whether the MySQL optimizer does a better job with a join than the equivalent
subquery.

The following sections discuss the kinds of operations you can use to test subquery results, how to
write correlated subqueries, and how to rewrite subqueries as joins

1) Subqueries with Relative Comparison Operators

The =, <>, >, >=, <, and <= operators perform relative-value comparisons. When used with a
scalar subquery, they find all rows in the outer query that stand in particular relationship to the
value returned by the subquery. For example, to identify the scores for the quiz that took place on
'2012-09-23', use a scalar subquery to determine the quiz event ID and then match score table rows
against that ID in the outer SELECT:

Example:
SELECT * FROM score
WHERE event_id =
(SELECT event_id FROM grade_event
WHERE date = '2012-09-23' AND category = 'Q');

Use of scalar subqueries with relative comparison operators is handy for solving problems for
which you’d be tempted to use an aggregate function in a WHERE clause. For example, to determine
which of the presidents in the president table was born first, you might try this statement:
Example:
1. SELECT * FROM president WHERE birth = MIN(birth);

2. SELECT * FROM president


WHERE birth = (SELECT MIN(birth) FROM president);
3. SELECT * FROM score WHERE event_id = 5
AND score > (SELECT AVG(score) FROM score WHERE event_id = 5);

If a subquery returns a single row, you can use a row constructor to compare a set of values (that is,
a tuple) to the subquery result. This statement returns rows for presidents who were born in the same
city and state as John Adams
Example:

mysql> SELECT last_name, first_name, city, state FROM president


-> WHERE (city, state) =
45 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
-> (SELECT city, state FROM president
-> WHERE last_name = 'Adams' AND first_name = 'John');

+-----------+-------------+-----------+-------+
| last_name | first_name | city | state |
+-----------+-------------+-----------+-------+
| Adams | John | Braintree | MA |
| Adams | John Quincy | Braintree | MA |
+-----------+-------------+-----------+-------+

You can also use ROW(city, state) notation, which is equivalent to (city, state).
Both act as row constructors.

2) IN and NOT IN Subqueries


The IN and NOT IN operators can be used when a subquery returns multiple rows to be evaluated
in comparison to the outer query. They test whether a comparison value is present in a set of
values. IN is true for rows in the outer query that match any row returned by the subquery. NOT IN
is true for rows in the outer query that match no rows returned by the subquery. The following
statements use IN and NOT IN to find those students who have absences listed in the absence
table, and those who have perfect attendance (no absences):
mysql> SELECT * FROM student
-> WHERE student_id IN (SELECT student_id FROM absence);
+-------+-----+------------+
| name | sex | student_id |
+-------+-----+------------+
| Kyle | M | 3 |
| Abby | F | 5 |

| Peter | M | 10 |
| Will | M | 17 |
| Avery | F | 20 |
+-------+-----+------------+
mysql> SELECT * FROM student
-> WHERE student_id NOT IN (SELECT student_id FROM absence);
+-----------+-----+------------+
| name | sex | student_id |
+-----------+-----+------------+
| Megan | F | 1 |
| Joseph | M | 2 |
| Katie | F | 4 |
| Nathan | M | 6 |
| Liesl | F | 7 |
+-----------+-------------+----+

IN and NOT IN also work for subqueries that return multiple columns. In other words, you can use
them with table subqueries. In this case, use a row constructor to specify the comparison values to
test against each column:

mysql> SELECT last_name, first_name, city, state FROM president


-> WHERE (city, state) IN
-> (SELECT city, state FROM president
-> WHERE last_name = 'Roosevelt');
+-----------+-------------+-----------+-------+
| last_name | first_name | city | state |
+-----------+-------------+-----------+-------+
| Roosevelt | Theodore | New York | NY |
| Roosevelt | Franklin D. | Hyde Park | NY |
+-----------+-------------+-----------+-------+

46 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
IN and NOT IN actually are synonyms for = ANY and <> ALL, which are covered in the next
section.

3) ALL, ANY, and SOME Subqueries


The ALL and ANY operators are used in conjunction with a relative comparison operator to test
the result of a column subquery. They test whether the comparison value stands in particular
relationship to all or some of the values returned by the subquery. For example, <= ALL is true if
the comparison value is less than or equal to every value that the subquery returns, whereas <=
ANY is true if the comparison value is less than or equal to any value that the subquery returns.
SOME is a synonym for ANY.

This statement determines which president was born first by selecting the row with a birth date less
than or equal to all the birth dates in the president table (only the earliest date satisfies this
condition):
mysql> SELECT last_name, first_name, birth FROM president
-> WHERE birth <= ALL (SELECT birth FROM president);
+------------+------------+------------+
| last_name | first_name | birth |
+------------+------------+------------+
| Washington | George | 1732-02-22 |
+------------+------------+------------+

Less usefully, the following statement returns all rows because every date is less than or equal to at
least one other date (itself):
mysql> SELECT last_name, first_name, birth FROM president
-> WHERE birth <= ANY (SELECT birth FROM president);
+------------+---------------+------------+
| last_name | first_name | birth |
+------------+---------------+------------+
| Washington | George | 1732-02-22 |
| Adams | John | 1735-10-30 |
| Jefferson | Thomas | 1743-04-13 |
| Madison | James | 1751-03-16 |
| Monroe | James | 1758-04-28 |

When ALL, ANY, or SOME are used with the = comparison operator, the subquery can be a table
subquery. In this case, you test return rows using a row constructor to provide the comparison
values.

mysql> SELECT last_name, first_name, city, state FROM president


-> WHERE (city, state) = ANY
-> (SELECT city, state FROM president
-> WHERE last_name = 'Roosevelt');
+-----------+-------------+-----------+-------+
| last_name | first_name | city | state |
+-----------+-------------+-----------+-------+
| Roosevelt | Theodore | New York | NY |
| Roosevelt | Franklin D. | Hyde Park | NY |
+-----------+-------------+-----------+-------+

As mentioned in the previous section, IN and NOT IN are shorthand for = ANY and <> ALL. That is,
IN means “equal to any of the rows returned by the subquery” and NOT IN means “unequal to all
rows returned by the subquery.”

47 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
4) EXISTS and NOT EXISTS Subqueries

The EXISTS and NOT EXISTS operators merely test whether a subquery returns any rows. If it does,
EXISTS is true and NOT EXISTS is false. The following statements show some trivial examples of
these subqueries. The first returns 0 if the absence table is empty, the second returns 1:

SELECT EXISTS (SELECT * FROM absence);


SELECT NOT EXISTS (SELECT * FROM absence);

EXISTS and NOT EXISTS actually are much more commonly used in correlated subqueries.

With EXISTS and NOT EXISTS, the subquery uses * as the output column list. There’s no need to
name columns explicitly, because the subquery is assessed as true or false based on whether it
returns any rows, not based on the particular values that the rows might contain. You can actually
write pretty much anything for the subquery column selection list, but if you want to make it
explicit that you’re returning a true value when the subquery succeeds, you might write it as
SELECT 1 rather than SELECT *.

5) Correlated Subqueries

Subqueries can be uncorrelated or correlated:

 An uncorrelated subquery contains no references to values from the outer query, so it could
be executed by itself as a separate statement. For example, the subquery in the following
statement is uncorrelated because it refers only to the table t1 and not to t2:

SELECT j FROM t2 WHERE j IN (SELECT i FROM t1);

 A correlated subquery does contain references to values from the outer query, and thus is
dependent on it. Due to this linkage, a correlated subquery cannot be executed by itself as a
separate statement. For example, the subquery in the following statement is true for each
value of column j in t2 that matches a column i value in t1:

SELECT j FROM t2 WHERE (SELECT i FROM t1 WHERE i = j);

The following EXISTS subquery identifies matches between the tables—that is, values that are
present in both. The statement selects students who have at least one absence listed in the absence
table:

SELECT student_id, name FROM student WHERE EXISTS


(SELECT * FROM absence WHERE absence.student_id = student.student_id);

NOT EXISTS identifies nonmatches—values in one table that are not present in the other. This
statement selects students who have no absences:

SELECT student_id, name FROM student WHERE NOT EXISTS


(SELECT * FROM absence WHERE absence.student_id = student.student_id);

6) Subqueries in the FROM Clause

Subqueries can be used in the FROM clause to generate values. In this case, the result of the subquery
acts like a table. A subquery in the FROM clause can participate in joins, its values can be tested in the

48 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
WHERE clause, and so forth. With this type of subquery, you must provide a table alias to give the
subquery result a name:

mysql> SELECT * FROM (SELECT 1, 2) AS t1 INNER JOIN (SELECT 3, 4) AS t2;


+---+---+---+---+
| 1 | 2 | 3 | 4 |
+---+---+---+---+
| 1 | 2 | 3 | 4 |
+---+---+---+---+

c) Queries:

1. Get the names of employees who have a below average salary?


SQL> SELECT EMP_NAME
2 FROM EMP
3 WHERE SALARY <
4 ( SELECT AVG( SALARY ) FROM EMP );

EMP_NAME
----------
Jones
Roberts
Jarvis
Fletcher
Evans

2. Get the names of employees who have a greater than average salary?
SQL> SELECT EMP_NAME
2 FROM EMP
3 WHERE SALARY >
4 ( SELECT AVG( SALARY ) FROM EMP );

EMP_NAME
----------
Brown
Green
3. Get the names of employees who are paid exactly the avarage salary ?
SQL> SELECT EMP_NAME
2 FROM EMP
3 WHERE SALARY =
4 ( SELECT AVG( SALARY ) FROM EMP );

no rows selected

4. Get the names of Employee is the most highly paid ?


SQL> SELECT EMP_NAME
2 FROM EMP
3 WHERE SALARY =
4 ( SELECT MAX( SALARY ) FROM EMP );

EMP_NAME
----------
Brown
Green

5. Get the names of Employee is the least paid?


SQL> SELECT EMP_NAME
2 FROM EMP
3 WHERE SALARY =
49 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
4 ( SELECT MIN( SALARY ) FROM EMP );

EMP_NAME
----------
Evans

6. Get the names of Employee whose salary exceeds the lowest salary by more than
4,000 ?

SQL> SELECT EMP_NAME


2 FROM EMP
3 WHERE SALARY >
4 ( SELECT (4000 + MIN( SALARY ) ) AS BOUNDARY
5 FROM EMP );

EMP_NAME
----------
Roberts
Jarvis
Brown
Green

7. Get the names of employees for the departments that have only one employee

SQL> SELECT DEPT_NAME FROM DEPT


2 WHERE 1 =
3 ( SELECT COUNT(*) FROM EMP
4 WHERE EMP.DEPT_NO = DEPT.DEPT_NO );

DEPT_NAME
----------
Transport

8. Get the deadlines of projects that have more than 3 employees working on them
SQL> SELECT DEADLINE FROM PROJ
2 WHERE 3 <
3 ( SELECT COUNT(*) FROM ALLOC
4 WHERE ALLOC.PROJ_NO = PROJ.PROJ_NO );

DEADLINE
---------
01-JAN-09

9. Get the names of employees who work in departments such that their salary is less
than 10% of their department’s budget
SQL> SELECT EMP_NAME FROM EMP
2 WHERE SALARY <
3 ( SELECT BUDGET/10 FROM DEPT
4 WHERE EMP.DEPT_NO = DEPT.DEPT_NO );

EMP_NAME
----------
Evans

10. Get the details of the projects not worked on by employee E2.
SQL> SELECT * FROM PROJ
2 WHERE PROJ_NO IN
3 (SELECT PROJ_NO FROM ALLOC
4 WHERE EMP_NO = 'E2');

50 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
PR START_DAT DEADLINE
-- --------- ---------
P2 21-JAN-05 30-SEP-07

11. Get the names of employees not allocated to projects.


SQL> SELECT EMP_NAME FROM EMP
2 WHERE EMP_NO NOT IN
3 ( SELECT EMP_NO FROM ALLOC );

EMP_NAME
----------
Roberts
Jarvis

12. Get the details of all employees who are not departmental managers.
SQL> SELECT * FROM EMP
2 WHERE EMP_NO NOT IN
3 ( SELECT MANAGER_NO FROM DEPT );

EM EMP_NAME SALARY M DE
-- ---------- ---------- - --
E9 Fletcher 12000 S D1
E4 Evans 11000 S D5
E6 Green 38500 ? D2

13. Get the details of employees whose salary is less than that of all those employees who
work on project P2.
SQL> SELECT * FROM EMP
2 WHERE SALARY <ALL
3 ( SELECT SALARY
4 FROM EMP NATURAL JOIN ALLOC
5 WHERE PROJ_NO = 'P2' );

EM EMP_NAME SALARY M DE
-- ---------- ---------- - --
E4 Evans 11000 S D5

14. Get details of the department with the largest budget;

SQL> SELECT * FROM DEPT


2 WHERE BUDGET >=ALL
3 ( SELECT BUDGET FROM DEPT );

DE DEPT_NAME MA BUDGET
-- ---------- -- ----------
D2 Sales E5 250000

d) Result:
Thus the nested quarries operations using DML Commands was successfully performed and
executed.

51 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
Practical Number: 7
Title of the Exercise : NESTED QUERIES AND JOIN QUERIES
Date of the Exercise :
OBJECTIVE (AIM) OF THE EXPERIMENT
To perform nested Queries and joining Queries using DML command.

b) Procedure for doing the experiment:


Step
Details of the step
no.
Relating Data through Join Concept
The purpose of a join concept is to combine data spread across tables. A join is
1 actually performed by the „where‟ clause which combines specified rows of tables.
Syntax; select columns from table1, table2 where logical expression;
Types of Joins 1. Simple Join 2. Self Join 3. Outer Join 4. Inner Join
1. Simple Join
a) Equi-join: A join, which is based on equalities, is called equi-join.
b) Non Equi-join: It specifies the relationship between
Table Aliases
Table aliases are used to make multiple table queries shorted and more readable. We
2
give an alias name to the table in the „from‟ clause and use it instead of the name
throughout the query.
Self join: Joining of a table to itself is known as self-join. It joins one row in a table
3 to another. It can compare each row of the table to itself and also with other rows of
the same table.
Outer Join: It extends the result of a simple join. An outer join returns all the rows
returned by simple join as well as those rows from one table that do not match any
row from the table. The symbol (+) represents outer join.
Inner join: Inner join returns the matching rows from the tables that are being
joined

c) Simple Join
a) Equi-join
Example: select * from item, cust where item.id=cust.id;
b) Non Equi-join
Example: select * from item, cust where item.id<cust.id;

Self join
Example: select * from emp x ,emp y where x.salary >= (select avg(salary) from x.emp where x.
deptno =y.deptno);

Outer Join
Example: select ename, job, dname from emp, dept where emp.deptno (+) = dept.deptno;

d) Queries:
Q1: Display all employee names and salary whose salary is greater than minimum salary of
the company and job title starts with ‗M‘.
Solution:
52 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
1. Use select from clause.
2. Use like operator to match job and in select clause to get the result.
Ans:
SQL> select ename,sal from emp where sal>(select min(sal) from emp where job like 'A%');
ENAME SAL
-------------------- ----------
Arjun 12000
Gugan 20000
Karthik 15000

Q2: Issue a query to find all the employees who work in the same job as Arjun.
Ans:
SQL> select * from emp;
EMPNO ENAME JOB DEPTNO SAL
---------- -------------------- ---------- ---------- ----------
1 Mathi AP 1 10000
2 Arjun ASP 2 12000
3 Gugan ASP 2 20000
4 Karthik AP 1 15000
SQL> select ename from emp where job=(select job from emp where ename='Arjun');
ENAME
--------------
Arjun
Gugan

Q3: Issue a query to display information about employees who earn more than any
employee in dept 1.
Ans:
SQL> select * from emp where sal>(select max(sal) from emp where empno=1);

EMPNO ENAME JOB DEPTNO SAL


---------- -------------------- ---------- ---------- ----------
2 Arjun ASP 2 12000
3 Gugan ASP 2 20000
4 Karthik AP 1 15000
JOINS
Tables used
SQL> select * from emp;

EMPNO ENAME JOB DEPTNO SAL


---------- -------------------- ---------- ---------- ----------
1 Mathi AP 1 10000
2 Arjun ASP 2 12000
3 Gugan ASP 2 20000
4 Karthik AP 1 15000

SQL> select * from dept;

DEPTNO DNAME LOC


---------- -------------- -------------
1 ACCOUNTING NEW YORK
53 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
2 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

EQUI-JOIN
Q4: Display the employee details, departments that the departments are same in both the
emp and dept.
Solution:
1. Use select from clause. 2. Use equi join in select clause to get the result.
Ans:
SQL> select * from emp,dept where emp.deptno=dept.deptno;
EMPNO ENAME JOB DEPTNO SAL DEPTNO DNAME LOC
---------- ------------------ ---------- ---------- ---------- ---------- -------------- -------------
1 Mathi AP 1 10000 1 ACCOUNTING NEW YORK
2 Arjun ASP 2 12000 2 RESEARCH DALLAS
3 Gugan ASP 2 20000 2 RESEARCH DALLAS
4 Karthik AP 1 15000 1 ACCOUNTING NEW YORK
NON-EQUIJOIN
Q5: Display the employee details, departments that the departments are not same in both
the emp and dept.
Solution:
1.Use select from clause. 2. Use non equi join in select clause to get the result.
Ans:
SQL> select * from emp,dept where emp.deptno!=dept.deptno;
EMPNO ENAME JOB DEPTNO SAL DEPTNO DNAME LOC
---------- -------------------- ---------- ---------- ---------- ------------------------ -------------
2 Arjun ASP 2 12000 1 ACCOUNTING NEW YORK
3 Gugan ASP 2 20000 1 ACCOUNTING NEW YORK
1 Mathi AP 1 10000 2 RESEARCH DALLAS

EMPNO ENAME JOB DEPTNO SAL DEPTNO DNAME LOC


---------- -------------------- ---------- ---------- ---------- ---------- -------------- -------------
4 Karthik AP 1 15000 2 RESEARCH DALLAS
1 Mathi AP 1 10000 30 SALES CHICAGO
2 Arjun ASP 2 12000 30 SALES CHICAGO
EMPNO ENAME JOB DEPTNO SAL DEPTNO DNAME LOC
---------- -------------------- ---------- ---------- ---------- ---------- -------------- -------------
3 Gugan ASP 2 20000 30 SALES CHICAGO
4 Karthik AP 1 15000 30 SALES CHICAGO
1 Mathi AP 1 10000 40 OPERATIONS BOSTON
EMPNO ENAME JOB DEPTNO SAL DEPTNO DNAME LOC
---------- -------------------- ---------- ---------- ---------- ---------- -------------- -------------
2 Arjun ASP 2 12000 40 OPERATIONS BOSTON
3 Gugan ASP 2 20000 40 OPERATIONS BOSTON
4 Karthik AP 1 15000 40 OPERATIONS BOSTON
12 rows selected.

LEFTOUT-JOIN
Tables used
54 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
SQL> select * from stud1;
Regno Name Mark2 Mark3 Result
---------- ----------- ---------- ---------- ---------------------------------------
101 john 89 80 pass
102 Raja 70 80 pass
103 Sharin 70 90 pass
104 sam 90 95
pass SQL> select * from stud2;
NAME GRA
----------- ----------
john s
raj s
sam a
sharin a

Q6: Display the Student name and grade by implementing a left outer join.
Ans: SQL> select stud1.name,grade from stud1 left outer join stud2 on stud1.name=stud2.name;
Name Gra
----------- ----------
john s
raj s
sam a
sharin a
smith null

RIGHTOUTER-JOIN
Q7: Display the Student name, register no, and result by implementing a right outer join.
Ans:
SQL> select stud1.name, regno, result from stud1 right outer join stud2 on stud1.name =
stud2.name;
Name Regno Result
----------- ---------- --------------------------
john 101 pass
raj 102 pass
sam 103 pass
sharin 104 pass
Rollno Name Mark1 Mark2 Total
---------- ---------- ---------- ---------- ----------
1 sindu 90 95 185
2 arul 90 90 180

FULLOUTER-JOIN
Q8: Display the Student name register no by implementing a full outer join.
Ans:
SQL> select stud1.name, regno from stud1 full outer join stud2 on (stud1.name= stud2.name);
Name Regno
----------- ----------
john 101
raj 102
sam 103
sharin 104

55 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
SELFJOIN
Q9: Write a query to display their employee names
Ans:
SQL> select distinct ename from emp x, dept y where x.deptno=y.deptno;
ENAME
--------------------
Arjun
Gugan
Karthik
Mathi

Q10: Display the details of those who draw the salary greater than the average salary.
Ans:
SQL> select distinct * from emp x where x.sal >= (select avg(sal) from emp);
EMPNO ENAME JOB DEPTNO SAL
---------- -------------------- ---------- ---------- ----------
3 Gugan ASP 2 20000
4 Karthik AP 1 15000
11 kavitha designer 12 17000
e) Result:
Thus the nested Queries and join Queries was performed successfully and executed.

56 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
Practical Number: 8
Title of the Exercise : DATA CONTROL LANGUAGE (DCL),
TRANSACTION CONTROL LANGUAGE (TCL)
COMMANDS
Date of the Exercise :
OBJECTIVE (AIM) OF THE EXPERIMENT
To study the various data language commands (DCL, TCL) and implements them
on the database.

PROCEDURE
b) Procedure for doing the experiment:
Step
Details of the step
no.
DCL COMMAND
1 The DCL language is used for controlling the access to the table and hence securing
the database. DCL is used to provide certain privileges to a particular user.
Privileges are rights to be allocated.
2 The privilege commands are namely, Grant and Revoke
The various privileges that can be granted or revoked are,
3
Select Insert Delete Update References Execute All
GRANT COMMAND: It is used to create users and grant access to the database. It
4 requires database administrator (DBA) privilege, except that a user can change their
password. A user can grant access to their database objects to other users.
REVOKE COMMAND: Using this command , the DBA can revoke the granted
5
database privileges from the user.
TCL COMMAND
COMMIT: command is used to save the Records.
6
ROLL BACK: command is used to undo the Records.
SAVE POINT command is used to undo the Records in a particular transaction.

c)SQL Commands DCL Commands GRANT COMMAND


Grant < database_priv [database_priv…..] > to <user_name> identified by <password>
[,<password…..];
Grant <object_priv> | All on <object> to <user | public> [ With Grant Option ];

REVOKE COMMAND
Revoke <database_priv> from <user [, user ] >;
Revoke <object_priv> on <object> from < user | public >;

<database_priv> -- Specifies the system level priveleges to be granted to the users or roles.
This includes create / alter / delete any object of the system.
<object_priv> -- Specifies the actions such as alter / delete / insert / references / execute /
select / update for tables.
<all> -- Indicates all the priveleges.

[ With Grant Option ] – Allows the recipient user to give further grants on the objects.
The priveleges can be granted to different users by specifying their names or to all users by
using the “Public” option.

57 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
TCL COMMANDS:
Syntax:
SAVEPOINT: SAVEPOINT <SAVE POINT NAME>;
ROLLBACK: ROLL BACK <SAVE POINT NAME>;
COMMIT: Commit;

d) Queries:
Tables Used:
Consider the following tables namely “DEPARTMENTS” and “EMPLOYEES”
Their schemas are as follows ,
Departments ( dept _no , dept_ name , dept_location );
Employees ( emp_id , emp_name , emp_salary );

Q1: Develop a query to grant all privileges of employees table into departments table
Ans:
SQL> Grant all on employees to departments; Grant succeeded.

Q2: Develop a query to grant some privileges of employees table into departments table
Ans:
SQL> Grant select, update , insert on departments to departments with grant option; Grant
succeeded.

Q3: Develop a query to revoke all privileges of employees table from departments table
Ans:
SQL> Revoke all on employees from departments; Revoke succeeded.

Q4: Develop a query to revoke some privileges of employees table from departments table
Ans:
SQL> Revoke select, update , insert on departments from departments; Revoke succeeded.

Q5: Write a query to implement the save point


Ans:
SQL> SAVEPOINT S1;
Savepoint created.

SQL> select * from emp;


EMPNO ENAME JOB DEPTNO SAL
---------- -------------------- ------------- ---------- ----------

1 Mathi AP 1 10000
2 Arjun ASP 2 15000
3 Gugan ASP 1 15000
4 Karthik Prof 2 30000

SQL> INSERT INTO EMP VALUES(5,'Akalya','AP',1,10000);


1 row created.

SQL> select * from emp;


EMPNO ENAME JOB DEPTNO SAL
---------- -------------------- ------------- ---------- ----------
1 Mathi AP 1 10000
2 Arjun ASP 2 15000
58 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
3 Gugan ASP 1 15000
4 Karthik Prof 2 30000
5 Akalya AP 1 10000

Q6: Write a query to implement the rollback


Ans:
SQL> rollback s1;
SQL> select * from emp;
EMPNO ENAME JOB DEPTNO SAL
---------- -------------------- ------------- ---------- ----------
1 Mathi AP 1 10000
2 Arjun ASP 2 15000
3 Gugan ASP 1 15000
4 Karthik Prof 2 30000

Q6: Write a query to implement the commit


Ans:
SQL> COMMIT;
Commit complete.
e)Result
The DCL,TCL commands was performed successfully and executed.

59 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
Practical Number: 09
Title of the Exercise : TRIGGER
Date of the Exercise :
OBJECTIVE (AIM) OF THE EXPERIMENT
To create triggers for various events such as insertion, updation, etc.,

PROCEDURE
a) PL/SQL Syntax:
TRIGGER
A Trigger is a stored procedure that defines an action that the database
automatically take when some database-related event such as Insert, Update or Delete
occur.

TRIGGER VS. PROCEDURE VS CURSOR

TRIGGER PROCEDURES CURSORS


These are named These are named These are named PL/SQL
PL/SQL blocks. PL/SQL blocks. blocks.
These are invoked User as per need invokes These can be created both
automatically. these. explicitly and implicitly.
These can‟t take These can take These can take parameters.
parameters. parameters.
These are stored in These are stored in These are not stored in
database. database. database.

TYPES OF TRIGGERS
The various types of triggers are as follows,
Before: It fires the trigger before executing the trigger statement.
After: It fires the trigger after executing the trigger statement.
For each row: It specifies that the trigger fires once per row.
 For each statement: This is the default trigger that is invoked. It specifies that
the trigger fires once per statement.
VARIABLES USED IN TRIGGERS
:new
:old
These two variables retain the new and old values of the column updated in the database.
The values in these variables can be used in the database triggers for data manipulation

Row Level Trigger vs. Statement Level Trigger:


Row Level Trigger Statement Level Trigger
These are fired for each row affected by These are fired once for the statement
the DML statement. instead of the no of rows modified by it.
These are used for generating/checking These are used for generated the
the values begin inserted or updated. summary information.

60 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
Before trigger vs. after trigger

Before Triggers After Triggers


Before triggers are fired before the After triggers are fired after the
DML statement is actually executed. DML statement has finished
execution.

Sytax:

Create or replace trigger <trg_name> Before /After Insert/Update/Delete


[of column_name, column_name….]
on
<table_name>
[for each row]
[when
condition] begin
---statement
end;
Q1: Create a trigger that insert current user into a username column of an existing table
b) Procedure for doing the experiment:
Step
Details of the step
no.
1 Create a table itstudent4 with name and username as arguments
2 Create a trigger for each row that insert the current user as user name into a table
3 Execute the trigger by inserting value into the table

d)Program:
SQL> create table itstudent4(name varchar2(15),username varchar2(15));
Table created.
SQL> create or replace trigger itstudent4 before insert on itstudent4 for each
row 2 declare
3 name varchar2(20);
4 begin
5 select user into name from
dual; 6 :new.username:=name;
7 end;
8 /
Trigger created.
e)Output:
SQL> insert into itstudent4 values('&name','&username');
Enter value for name: akbar
Enter value for username: ranjani
old 1: insert into itstudent4 values('&name','&username')
new 1: insert into itstudent4 values('akbar','ranjani')
1 row
created.
SQL> /
Enter value for name: suji

61 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
Enter value for username:
priya
old 1: insert into itstudent4 values('&name','&username')
new 1: insert into itstudent4 values('suji','priya')
1 row created.
SQL> select * from itstudent4;

NAME USERNAME
--------------- ---------------
akbar SCOTT
suji SCOTT
Q2: Create a Simple Trigger that does not allow Insert Update and Delete Operations on
the Table

d)Program:
Table used:
SQL> select * from itempls;
ENAME EID
SALARY
---------- --------- ---------
xxx 11 10000
yyy 12 10500
zzz 13 15500
Trigger:
SQL> create trigger ittrigg before insert or update or delete on itempls for each row
2 begin
3 raise_application_error(-20010,'You cannot do manipulation');
4 end;
5
6 /
Trigger created.

e)Output:
SQL> insert into itempls values('aaa',14,34000);
insert into itempls values('aaa',14,34000)
*
ERROR at line
1:
ORA-20010: You cannot do manipulation
ORA-06512: at "STUDENT.ITTRIGG", line
2
ORA-04088: error during execution of trigger 'STUDENT.ITTRIGG'

SQL> delete from itempls where ename='xxx';


delete from itempls where ename='xxx'
*
ERROR at line
1:
ORA-20010: You cannot do manipulation
ORA-06512: at "STUDENT.ITTRIGG", line
2
ORA-04088: error during execution of trigger 'STUDENT.ITTRIGG'

62 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
SQL> update itempls set eid=15 where ename='yyy';
update itempls set eid=15 where ename='yyy'
*
ERROR at line 1:
ORA-20010: You cannot do manipulation
ORA-06512: at "STUDENT.ITTRIGG", line
2
ORA-04088: error during execution of trigger 'STUDENT.ITTRIGG'

Q3: Create a Trigger that raises an User Defined Error Message and does not allow
updating and Insertion

d)Program:
Table used:
SQL> select * from itempls;
ENAME EID
SALARY
---------- --------- ---------
xxx 11 10000
yyy 12 10500
zzz 13 15500
Trigger:
SQL> create trigger ittriggs before insert or update of salary on itempls for each row
2 declare
3 triggsal itempls.salary%type;
4 begin
5 select salary into triggsal from itempls where eid=12;
6 if(:new.salary>triggsal or :new.salary<triggsal) then
7 raise_application_error(-20100,'Salary has not been changed');
8 end if;
9 end;
10 /
Trigger created.
e)Output:
SQL> insert into itempls values ('bbb',16,45000);
insert into itempls values ('bbb',16,45000)
*
ERROR at line 1:
ORA-04098: trigger 'STUDENT.ITTRIGGS' is invalid and failed re-validation
SQL> update itempls set eid=18 where ename='zzz';
update itempls set eid=18 where ename='zzz'
*
ERROR at line 1:
ORA-04298: trigger 'STUDENT.ITTRIGGS' is invalid and failed re-validation

Q4: develop a query to Drop the Created Trigger


Ans:
SQL> drop trigger ittrigg;
Trigger dropped.

f)Result:
Thus the creation of triggers for various events such as insertion, updating, etc., was performed
and executed successfully.

63 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
Practical Number: 10
Title of the Exercise : VIEWS
Date of the Exercise :

OBJECTIVE (AIM) OF THE EXPERIMENT


To create and manipulate various database objects of the Table using views

PROCEDURE
a) Procedure for doing the experiment:

Step Details of the step


no.
Views:
A view is the tailored presentation of data contained in one or more table and can also be
1 said as restricted view to the data‟s in the tables. A view is a “virtual table” or a “stored
query” which takes the output of a query and treats it as a table. The table upon which a
view is created is called as base table.
A view is a logical table based on a table or another view. A view contains no data of its
2 own but is like a window through which data from tables can be viewed or changed. The
tables on which a view is based are called base tables. The view is stored as a SELECT
statement in the data dictionary
Advantages of a view:
a. Additional level of table security.
3 b. Hides data complexity.
c. Simplifies the usage by combining multiple tables into a single table.
d. Provides data‟s in different perspective.
Types of view:
4 Horizontal -> enforced by where cause
Vertical -> enforced by selecting the required columns

a) SQL Commands
Creating and dropping view:
Syntax:
Create [or replace] view <view name> [column alias names] as <query> [with
<options> conditions];
Drop view <view name>;
Example:
Create or replace view empview as select * from emp;
Drop view empview;
b) Queries: Tables used:
SQL> select * from emp;
EMPNO ENAME JOB DEPTNO SAL
---------- -------------------- ---------- ---------- ----------
1 Mathi AP 1 10000
2 Arjun ASP 2 12000
3 Gugan ASP 2 20000
4 Karthik AP 1 15000

64 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
Q1: The organization wants to display only the details of the employees those who are ASP.
(Horizontal portioning)
Solution:
1. Create a view on emp table named managers
2. Use select from clause to do horizontal partioning
Ans:
SQL> create view empview as select * from emp where job='ASP';
View created.
SQL> select * from empview;
EMPNO ENAME JOB DEPTNO SAL
---------- -------------------- ---------- ---------- ----------
2 Arjun ASP 2 12000
3 Gugan ASP 2 20000
Q2: The organization wants to display only the details like empno, empname, deptno,
deptname of the employees. (Vertical portioning)
Solution:
1. Create a view on emp table named general 2. Use select from clause to do vertical partioning
Ans:
SQL> create view empview1 as select ename,sal from emp;
View created.
Q3: Display all the views generated.
Ans:
SQL> select * from tab;
TNAME TABTYPE CLUSTERID
------------------------------ ------- ----------
DEPT TABLE
EMP TABLE
EMPVIEW VIEW
EMPVIEW1 VIEW
Q4: Execute the DML commands on the view created.
Ans:
SQL> select * from empview;
EMPNO ENAME JOB DEPTNO SAL
---------- -------------------- ---------- ---------- ----------
2 Arjun ASP 2 12000
3 Gugan ASP 2 20000
Q5: Drop a view.
Ans: SQL> drop view empview1;
View dropped.
c) Result:
Thus the creation and manipulate various database objects of the Table using views
was successfully executed.

65 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
Practical Number: 11
Title of the Exercise : CONTROL STRUCTURE
Date of the Exercise :
OBJECTIVE (AIM) OF THE EXPERIMENT
To create PL/SQL programs to implement various types of control structure.

PROCEDURE
a) Facilities required to do the experiment:
Sl.No. Facilities required Quantity
1 System 1
2 Operating System Windows XP
3 Front end VB/VC ++/JAVA
4 Back end Oracle11g,my SQL, DB2

b) PL/SQL Syntax:
PL/SQL can also process data using flow of statements. The flow of control statements are
classified into the following categories.
 Conditional control –Branching
 Iterative control – looping
 Sequential control – Selection

BRANCHING in PL/SQL:
Sequence of statements can be executed on satisfying certain condition. If statements are being
used and different forms of if are:
1. Simple IF 2. If then else 3. Else if 4. Nested if

SELECTION IN PL/SQL (Sequential Controls)


1. Simple case 2. Searched case

ITERATIONS IN PL/SQL
Sequence of statements can be executed any number of times using loop construct. It is broadly
classified into:
1.Simple Loop 2. For Loop 3. While Loop

SIMPLE IF:
Syntax:
IF condition
THEN
statement1;
statement2;
END IF;
IF-THEN-ELSE STATEMENT:
Syntax:
IF condition
THEN
statement1;
ELSE
statem
ent2;
66 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
END
IF;

ELSIF STATEMENTS:
Syntax:
IF condition1 THEN
statement1;
ELSIF condition2 THEN
statement2;
ELSIF condition3 THEN
statement3;
ELSE
statement;
END IF;

NESTED IF:
Syntax:
IF condition THEN
statement1;
ELSE
IF condition THEN
statement2;
ELSE
statement3;
END IF;
END IF;
ELSE
statement3;
END IF;
SELECTION IN PL/SQL (Sequential Controls)
SIMPLE CASE
Syntax:
CASE SELECTOR
WHEN Expr1 THEN statement1;
WHEN Expr2 THEN statement2;
:
ELSE
Statement n;
END CASE

ITERATIONS IN PL/SQL
SIMPLE LOOP
Syntax:
LOOP
statement1;
EXIT [ WHEN Condition];
END LOOP;
Example:
Declare
A number:=10;
Begin
Loop
a := a+25;
67 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
exit when a=250;
end loop;
dbms_output.put_line(to_char(a));
end;

WHILE LOOP
Syntax
WHILE condition LOOP
statement1;
statement2;
END
LOOP;
Example:
Declare
i
number:=0
; j
number:=0
; begin
while i<=100
Loop j := j+i;
i := i+2;
end loop;
dbms_output.put_line(„the value of j is‟ ||j);
end;

FOR LOOP
Syntax:
FOR counter IN
[REVERSE]
LowerBound..UpperBound
LOOP
statement1;
statement2;
END
LOOP;
Example:
Begin
For I in
1..2 Loop
Update emp set field = value where
condition; End loop;
End;
/
Q1: write a pl/sql program to swap two numbers
c) Procedure for doing the experiment:

Step
Details of the step
no.
1 Declare three variables and read variables through a and b
2 Swap the values of a and b using temporary variables
3 Display the swapped results

68 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l
a) Program:
SQL>edit swapping.sql
declare
a
number(10);
b
number(10);
c
number(10);
begin
dbms_output.put_line('THE PREV VALUES OF A AND B WERE');
dbms_output.put_line(a);
dbms_output.put_line(b);
a:=&a;
b:=&b;
c:=a;
a:=b;
b:=c;
dbms_output.put_line('THE VALUES OF A AND B
ARE'); dbms_output.put_line(a);
dbms_output.put_line(b
); end;
e)output:
SQL> @
swapping.sql 19 /
Enter value for a:
5 old 6: a:=&a;
new 6: a:=5;
Enter value for b:
3 old 7: b:=&b;
new 7: b:=3;
THE PREV VALUES OF A AND B WERE
53
THE VALUES OF A AND B ARE
35

Result: PL/SQL procedure successfully completed.

69 | P a g e D a t a b a s e M a n a g e m e n t S y s t e m L a b M a n u a l

Potrebbero piacerti anche