0% found this document useful (0 votes)
3 views130 pages

SQL_LAB

The document outlines the design and understanding of Entity-Relationship (ER) and Extended Entity-Relationship (EER) models, emphasizing their importance in creating well-structured databases. It details the components, symbols, and procedures for creating ER diagrams, including entities, attributes, relationships, and cardinality. Additionally, it discusses best practices for developing effective ER diagrams and introduces concepts related to EER, such as subclasses, specialization, and aggregation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views130 pages

SQL_LAB

The document outlines the design and understanding of Entity-Relationship (ER) and Extended Entity-Relationship (EER) models, emphasizing their importance in creating well-structured databases. It details the components, symbols, and procedures for creating ER diagrams, including entities, attributes, relationships, and cardinality. Additionally, it discusses best practices for developing effective ER diagrams and introduces concepts related to EER, such as subclasses, specialization, and aggregation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 130

Ex.

1 DESIGNING AN ENTITY-RELATIONSHIP (ER) / EXTENDED ENTITY-


RELATIONSHIP (EER) MODEL

LAB OBJECTIVES:

To understand for designing an entity-relationship (er) / extended entity-relationship (eer) model

in the real world application.

LAB OUTCOMES:

On Successful Completion, the Student will be able to understand about designing an entity-
relationship (er) / extended entity-relationship (eer) modelin the real world application.

PROCEDURE:

ER Diagram stands for Entity Relationship Diagram, also known as ERD is a diagram that
displays the relationship of entity sets stored in a database. In other words, ER diagrams help to
explain the logical structure of databases. ER diagrams are created based on three basic concepts:
entities, attributes and relationships.

ER Diagrams contain different symbols that use rectangles to represent entities, ovals to define
attributes and diamond shapes to represent relationships.

At first look, an ER diagram looks very similar to the flowchart. However, ER Diagram includes
many specialized symbols, and its meanings make this model unique. The purpose of ER
Diagram is to represent the entity framework infrastructure.
Entity Relationship Diagram Example

What is ER Model?
ER Model stands for Entity Relationship Model is a high-level conceptual data model diagram.
ER model helps to systematically analyze data requirements to produce a well-designed
database. The ER Model represents real-world entities and the relationships between them.
Creating an ER Model in DBMS is considered as a best practice before implementing your
database.
ER Modeling helps you to analyze data requirements systematically to produce a well-designed
database. So, it is considered a best practice to complete ER modeling before implementing your
database.
History of ER models
ER diagrams are visual tools that are helpful to represent the ER model. Peter Chen proposed ER
Diagram in 1971 to create a uniform convention that can be used for relational databases and
networks. He aimed to use an ER model as a conceptual modeling approach.

Why use ER Diagrams?


Here, are prime reasons for using the ER Diagram

● Helps you to define terms related to entity relationship modeling


● Provide a preview of how all your tables should connect, what fields are going to be on
each table
● Helps to describe entities, attributes, relationships
● ER diagrams are translatable into relational tables which allows you to build databases
quickly
● ER diagrams can be used by database designers as a blueprint for implementing data in
specific software applications
● The database designer gains a better understanding of the information to be contained in
the database with the help of ERP diagram
● ERD Diagram allows you to communicate with the logical structure of the database to
users

Facts about ER Diagram Model


Now in this ERD Diagram Tutorial, let’s check out some interesting facts about ER
Diagram Model:

● ER model allows you to draw Database Design


● It is an easy to use graphical tool for modeling data
● Widely used in Database Design
● It is a GUI representation of the logical structure of a Database
● It helps you to identifies the entities which exist in a system and the relationships
between those entities

ER Diagrams Symbols & Notations


Entity Relationship Diagram Symbols & Notations mainly contains three basic symbols
which are rectangle, oval and diamond to represent relationships between elements, entities and
attributes. There are some sub-elements which are based on main elements in ERD Diagram. ER
Diagram is a visual representation of data that describes how data is related to each other using
different ERD Symbols and Notations.

Following are the main components and its symbols in ER Diagrams:


● Rectangles: This Entity Relationship Diagram symbol represents entity types
● Ellipses : Symbol represent attributes
● Diamonds: This symbol represents relationship types
● Lines: It links attributes to entity types and entity types with other relationship types
● Primary key: attributes are underlined
● Double Ellipses: Represent multi-valued attributes

ER Diagram Symbols

Components of the ER Diagram


This model is based on three basic concepts:

● Entities
● Attributes
● Relationships

ER Diagram Examples

For example, in a University database, we might have entities for Students, Courses, and
Lecturers. Students entity can have attributes like Rollno, Name, and DeptID. They might have
relationships with Courses and Lecturers.
Components of the ER Diagram

WHAT IS ENTITY?
A real-world thing either living or non-living that is easily recognizable and nonrecognizable. It
is anything in the enterprise that is to be represented in our database. It may be a physical thing
or simply a fact about the enterprise or an event that happens in the real world.

An entity can be place, person, object, event or a concept, which stores data in the database. The
characteristics of entities are must have an attribute, and a unique key. Every entity is made up of
some ‘attributes’ which represent that entity.

Examples of entities:

● Person: Employee, Student, Patient


● Place: Store, Building
● Object: Machine, product, and Car
● Event: Sale, Registration, Renewal
● Concept: Account, Course
Notation of an Entity

Entity set:
Student

An entity set is a group of similar kind of entities. It may contain entities with attribute sharing
similar values. Entities are represented by their properties, which also called attributes. All
attributes have their separate values. For example, a student entity may have a name, age, class,
as attributes.

Example of Entities:

A university may have some departments. All these departments employ various lecturers and
offer several programs.

Some courses make up each program. Students register in a particular program and enroll in
various courses. A lecturer from the specific department takes each course, and each lecturer
teaches a various group of students.

Relationship
Relationship is nothing but an association among two or more entities. E.g., Tom works in the
Chemistry department.
Entities take part in relationships. We can often identify relationships with verbs or verb phrases.

For example:

● You are attending this lecture


● I am giving the lecture
● Just loke entities, we can classify relationships according to relationship-types:
● A student attends a lecture
● A lecturer is giving a lecture.

Weak Entities
A weak entity is a type of entity which doesn’t have its key attribute. It can be identified
uniquely by considering the primary key of another entity. For that, weak entity sets need to have
participation.

In above ER Diagram examples, “Trans No” is a discriminator within a group of transactions in


an ATM.

Strong Entity Set Weak Entity Set


It does not have enough attributes to build a primary
Strong entity set always has a primary key.
key.
It is represented by a rectangle symbol. It is represented by a double rectangle symbol.
It contains a Primary key represented by the underline It contains a Partial Key which is represented by a
symbol. dashed underline symbol.
The member of a strong entity set is called as The member of a weak entity set called as a
dominant entity set. subordinate entity set.
Primary Key is one of its attributes which helps to In a weak entity set, it is a combination of primary
identify its member. key and partial key of the strong entity set.
The relationship between one strong and a weak
In the ER diagram the relationship between two
entity set shown by using the double diamond
strong entity set shown by using a diamond symbol.
symbol.
The connecting line of the strong entity set with the The line connecting the weak entity set for identifying
relationship is single. relationship is double.
Let’s learn more about a weak entity by comparing it with a Strong Entity

Attributes
It is a single-valued property of either an entity-type or a relationship-type.

For example, a lecture might have attributes: time, date, duration, place, etc.

An attribute in ER Diagram examples, is represented by an Ellipse

Types of Attributes Description


Simple attributes can’t be divided any further. For
Simple attribute example, a student’s contact number. It is also
called an atomic value.
It is possible to break down composite attribute.
For example, a student’s full name may be further
Composite attribute
divided into first name, second name, and last
name.
This type of attribute does not include in the
physical database. However, their values are
derived from other attributes present in the
Derived attribute
database. For example, age should not be stored
directly. Instead, it should be derived from the
DOB of that employee.
Multivalued attributes can have more than one
Multivalued attribute values. For example, a student can have more than
one mobile number, email address, etc.

Cardinality
Defines the numerical attributes of the relationship between two entities or entity sets.

Different types of cardinal relationships are:

● One-to-One Relationships
● One-to-Many Relationships
● May to One Relationships
● Many-to-Many Relationships

1.One-to-one:
One entity from entity set X can be associated with at most one entity of entity set Y and vice
versa.

Example: One student can register for numerous courses. However, all those courses have a
single line back to that one student.

2.One-to-many:

One entity from entity set X can be associated with multiple entities of entity set Y, but an entity
from entity set Y can be associated with at least one entity.

For example, one class is consisting of multiple students.

3. Many to One

More than one entity from entity set X can be associated with at most one entity of entity set Y.
However, an entity from entity set Y may or may not be associated with more than one entity
from entity set X.
For example, many students belong to the same class.

4. Many to Many:

One entity from X can be associated with more than one entity from Y and vice versa.

For example, Students as a group are associated with multiple faculty members, and faculty
members can be associated with multiple students.

How to Create an Entity Relationship Diagram (ERD)


Now in this ERD Diagram Tutorial, we will learn how to create an ER Diagram. Following are
the steps to create an ER Diagram:

Steps to Create an ER Diagram


Let’s study them with an Entity Relationship Diagram Example:

In a university, a Student enrolls in Courses. A student must be assigned to at least one or more
Courses. Each course is taught by a single Professor. To maintain instruction quality, a Professor
can deliver only one course
Step 1) Entity Identification
We have three entities

● Student
● Course
● Professor

Step 2) Relationship Identification


We have the following two relationships

● The student is assigned a course


● Professor delivers a course

Step 3) Cardinality Identification


For them problem statement we know that,

● A student can be assigned multiple courses


● A Professor can deliver only one course
Step 4) Identify Attributes
You need to study the files, forms, reports, data currently maintained by the organization to
identify attributes. You can also conduct interviews with various stakeholders to identify entities.
Initially, it’s important to identify the attributes without mapping them to a particular entity.

Once, you have a list of Attributes, you need to map them to the identified entities. Ensure an
attribute is to be paired with exactly one entity. If you think an attribute should belong to more
than one entity, use a modifier to make it unique.

Once the mapping is done, identify the primary Keys. If a unique key is not readily available,
create one.

Entity Primary Key Attribute

Student Student_ID StudentName

Professor Employee_ID ProfessorName

Course Course_ID CourseName


For Course Entity, attributes could be Duration, Credits, Assignments, etc. For the sake of ease
we have considered just one attribute.

Step 5) Create the ERD Diagram


A more modern representation of Entity Relationship Diagram Example

Best Practices for Developing Effective ER Diagrams


Here are some best practice or example for Developing Effective ER Diagrams.

● Eliminate any redundant entities or relationships


● You need to make sure that all your entities and relationships are properly labeled
● There may be various valid approaches to an ER diagram. You need to make sure that the
ER diagram supports all the data you need to store
● You should assure that each entity only appears a single time in the ER diagram
● Name every relationship, entity, and attribute are represented on your diagram
● Never connect relationships to each other
● You should use colors to highlight important portions of the ER diagram
EER is a high-level data model that incorporates the extensions to the original ER model.
Enhanced ERD are high level models that represent the requirements and complexities of complex
database.
In addition to ER model concepts EE-R includes −
● Subclasses and Super classes.
● Specialization and Generalization.
● Category or union type.
● Aggregation.
These concepts are used to create EE-R diagrams.
Subclasses and Super class
Super class is an entity that can be divided into further subtype.
For example − consider Shape super class.

Super class shape has sub groups: Triangle, Square and Circle.
Sub classes are the group of entities with some unique attributes.Sub class inherits the properties
and attributes from super class.
Specialization and Generalization
Generalization is a process of generalizing an entity which contains generalized attributes or
properties of generalized entities.
It is a Bottom up process i.e. consider we have 3 sub entities Car, Truck and Motorcycle. Now
these three entities can be generalized into one super class named as Vehicle.
Specialization is a process of identifying subsets of an entity that share some different
characteristic. It is a top down approach in which one entity is broken down into low level entity.
In above example Vehicle entity can be a Car, Truck or Motorcycle.
Category or Union
Relationship of one super or sub class with more than one super class.
Owner is the subset of two super class: Vehicle and House.
Aggregation
Represents relationship between a whole object and its component.

Consider a ternary relationship Works_On between Employee, Branch and Manager. Now the
best way to model this situation is to use aggregation, So, the relationship-set, Works_On is a
higher level entity-set. Such an entity-set is treated in the same manner as any other entity-set. We
can create a binary relationship, Manager, between Works_On and Manager to represent who
manages what tasks.

Conclusion:

Thus for designing an entity-relationship (er) / extended entity-relationship (eer) model is studied
and verified for the application.
EX.2 MAPPING ER/EER TO RELATIONAL SCHEMA MODEL

LAB OBJECTIVES:

To understand about Mapping ER/EER to relational Schema Model on real world applications.

LAB OUTCOMES:

On Successful Completion, the Student will be able to understand about Mapping ER/EER to
relational Schema Model on real world applications.

PROCEDURE:

Drawing ER and EER Diagrams & Relational Mapping

What are the ER diagrams?


ER diagram is a visual representation of data based on the ER model, and it describes how entities
are related to each other in the database.
What are EER diagrams?
EER diagram is a visual representation of data, based on the EER model that is an extension of the
original entity-relationship (ER) model.

Entity
An entity is any singular, identifiable and separate object. It refers to individuals, organizations,
systems, bits of data or even distinct system components that are considered significant in and of
themselves. For example, People, Property, Organizations, Agreements and, etc. In the ER
diagram, the entity is represented by a rectangle.
Weak Entity
A weak entity is an entity that depends on the existence of another entity. In more technical terms it can
be defined as an entity that cannot be identified by its own attributes.
Attributes
Attributes are the properties that define the entity type. For example, Roll_No, Name, DOB, Age,
Address, Mobile_No are the attributes that define entity type Student. In the ER diagram,
the attribute is represented by an oval.
Multi-valued Attribute
If an attribute can have more than one value it is called a multi-valued attribute.
Derived Attribute
An attribute-based on another attribute.
Relationships
A relationship is an association that describes the interaction between entities.
Recursive Relationship
If the same entity participates more than once in a relationship it is known as a recursive relationship.
The following are the types of entities, attributes, and relationships.
Cardinality
Cardinality refers to the maximum number of times an instance in one entity can relate to instances of
another entity. There are three types of cardinalities.
one to one (1 to 1)
one to many(1 to N)
many to many (M to N)
Participation
Participation constraint specifies the existence of an entity when it is related to another entity in
a relationship type. There are two types. Partial and Total participation.
Total Participation − Each entity is involved in the relationship. Total participation is represented by
double lines.
Partial participation − Not all entities are involved in the relationship. Partial participation is
represented by single lines.
There are three steps in database development.
Requirements Analysis- Understand the data problem through user interviews, forms, reports,
observation and etc.
Component design stage- Create a data model that is a graphical representation of what will be
finally will be implemented.
Implementation stage- Actual development of the database which leads to database actually being
used in the real environment.
In the above stages after the first stage(Requirements analysis) you have to follow the database design
stages.

1. Conceptual design

2. Logical design

3. Physical design
In the Conceptual design, we identify all entities, we define attributes and their properties and we
define relationships between entities.
In the Logical design, we transform the conceptual design into relational, transform entities as tables,
transform entity attributes into table column, and normalization.
In the Physical design, we specify internal storage structure and paths, assign one or more indexes
and tune indexes.

At the conceptual design stage, we design the ER or EER diagrams.

Here are some rules for drawing ER and EER diagrams

● Write all entities in the singular form

● Write all relationships in a singular form.

● Write all attributes in the singular form.

● If you want to separate words use underscore mark.

Now, let’s see how to draw ER diagrams and EER diagrams.

Drawing ER and EER diagrams

Below points show how to go about creating an ER diagram.

1. Identify all the entities in the system. An entity should appear only once in a particular
diagram. Create rectangles for all entities and name them properly.

2. Identify relationships between entities. Connect them using a line and add a diamond in
the middle describing the relationship.

3. Add attributes for entities. Give meaningful attribute names so they can be understood
easily.

4. Mark the cardinalities and participation between the entities.


Here is an example of ER diagrams.

Looks easy? Try more to draw complex diagrams.


Now let’s see how to draw EER diagrams.
Here we just need to add a few things to above.

1. As in drawing ER diagrams first, we have to identify all entities.


After we found entities from the scenario you should check whether those entities have sub-entities. If
so you have to mark sub-entities in your diagram.
Dividing entities into sub-entities we called as specialization. And combining sub-entities to one entity is
called a generalization.
2. Then you have to identify relationships between entities and mark them.
3. Add attributes for entities. Give meaningful attribute names so they can be understood easily.
4.Mark the cardinalities and participation
If it is an EER diagram you have to add a few to your diagram.
Here also we have to check whether sub-entities totally depend on the main entity or not. And you
should mark it.
If all members in the superclass(main entity) participate in either one subclass it is known as total
participation. It marks by double lines.
Total Participation
If at least one member in the superclass does not participate in subclass it is known as partial
participation. It is denoted by one single line.
Partial Participation
If all the members in the superclass participate for only one subclass it is known as disjoint and
denoted by “d”. If all the members in the superclass participate in more than one subclass it is known
as overlap and denoted by “o”.
Now it ends, after following all the above steps you can come up with your ER and EER diagrams.😍
Benefits of ER and EER diagrams.
Easy to understand and does not require a person to undergo extensive recently training to be able to
work with it and accurately.
Readily translatable to relational tables which can be used to quickly build databases
Can directly be used by database developers as the blueprint for implementing databases in specific
software application
It can be applied in other contexts such as describing the different relationships and operations within
an organization.
Now let’s move on. Our next topic is map ER and EER diagrams into relational schemas.
Mapping ER and EER diagrams into relational schemas
First I’ll tell you how to map the ER diagram into a relational schema.

Mapping ER diagrams into relational schemas

Follow the steps one by one to get it done.🤞

1. Mapping strong entities.

2. Mapping weak entities.

3. Map binary one-to-one relations.

4. Map binary one-to-many relations

5. Map binary many-to-many relations.

6. Map multivalued attributes.

7. Map N-ary relations

Let’s go deep with the examples.


1. Mapping strong entities.

2. Mapping weak entities.

Above it shows an ER diagram with its relationships. You can see there are two strong entities
with relationships and a weak entity with a weak relationship.

When you going to make a relational schema first you have to identify all entities with their
attributes. You have to write attributes in brackets as shown below. Definitely you have to
underline the primary keys. In the above DEPENDENT is a weak entity. To make it strong go
through the weak relationship and identify the entity which connects with this. Then you have
written that entity’s primary key inside the weak entity bracket.
Then you have to map the primary key to where you took from as shown below.

3. Map binary one to one relations.

Let’s assume that the relationship between CUSTOMER and CARD is one to one.

There are three occasions where one to one relations take place according to the participation
constraints.

I. Both sides have partial participation.


When both sides have partial participation you can send any of the entity’s primary key to others.
At the same time, if there are attributes in the relationship between those two entities, it is also
sent to other entity as shown above.

So, now let us see how we write the relational schema.

Here you can see I have written CUSTID and STARTDATE inside the CARD table. Now you
have to map CUSTID from where it comes. That’s it.🤩

II. One side has partial participation.


You can see between the relationship and CARD entity it has total participation.

When there is total participation definitely the primary of others comes to this. And also if there
are attributes in the relationship it also comes to total participation side.

Then you have to map them as below.

III. Both sides have total participation


If both sides have total participation you need to make a new relationship with a suitable name
and merge entities and the relationship.

Following it shows how we should write the relation.

Now let us see how to map one to many relations.


4. Map binary one-to-many relations

If it is one-to-many, always to the many side other entities' primary keys and the attributes in the
relationship go to the many side. No matter about participation. And then you have to map the
primary key.
5. Map binary many to many relations.

If it is many to many relations you should always make a new relationship with the name of the
relationship between the entities.

And there you should write both primary keys of the entities and attributes in the relationship and
map them to the initials as shown below.
6. Map multivalued attributes.

If there are multivalued attributes you have to make a new relationship with a suitable name and
write the primary key of the entity which belongs to the multivalued attribute and also the name
of the multivalued attribute as shown below.

7. Map N-ary relations.

First, let us consider unary relationships.

We categorized them into two.


I. one-to-one and one to many relations.

If it is unary and one to one or one to many relations you do not need to make a new relationship
you just want to add a new primary key to the current entity as shown below and map it to the
initial. For example, in the above diagram, the employee is supervised by the supervisor.
Therefore we need to make a new primary key as SID and map it to EMPID. Because
of SID also an EMPID.
II. many-to-many relations.

If it is unary and many to many relations you need to make a new relationship with a suitable
name. Then you have to give it a proper primary key and it should map to where it comes as
shown below.
Now let us see how to map relations with more than two entities.
If there are more than three entities for a relationship you have to make a new relation
table and put all primary keys of connected entities and all attributes in the relationship.
And in the end, you have to map them as shown below.

👍 That’s how we map ER diagrams into relational schemas.

Now let us see how to map EER diagrams.

Mapping EER diagrams into relational schemas.

Let us go through the following diagram.


There are four ways to draw relational schema for an EER. You have to choose the most suitable
one. In the end, I'll give you the guidelines on how to choose the best and most suitable way.

First method
Here we write separate relations to all superclass entities and subclass entities. And here we have
to write the superclass entities' primary key to all subclass entities and then map them as shown
above. Note that we write only the attributes belongs to each entity.

Second method

Here we do not write the superclass entity but in each subclass entity, we write all attributes that
are in superclass entity.

Third method

Here we write only the superclass entity and write all the attributes which belong to subclass
entities. Specialty in here is that to identify that PERSON is an EMPLOYEE or STUDENT we
add a column as PERSONTYPE. After the table creates we can mark as
a STUDENT or EMPLOYEE.

Fourth method

Here instead of PERSONTYPE, we write STUDENT and EMPLOYEE both.

The reason for that is sometime PERSON will belong to both categories.

Somewhat confusing right? Don't worry read the following guidelines to clear out them.

Now let us see how to select the best and most suitable method to write the relational schema.

Guidelines

1.If sub-entities have more attributes (local or foreign attributes)

Select the first or second method.

From this two,

If EER is totally specialized -> select the second method.

If EER is partially specialized -> select first method.

2. If sub-entities have fewer attributes (local or foreign attributes)

Select the third or fourth method.


From this two,

If EER is disjoint-> select the third method.

If EER is overlap -> select forth method.

👍 That’s how we map EER diagrams into relational schemas.

CONCLUSION:

Thus the Mapping ER/EER to Relational schema model is done and the relevant application is
verified.
EX.3 CREATING A DATABASE USING DDL AND APPLY INTEGRITY
CONSTRAINTS.

LAB Objectives:

To create a database using DDL and apply integrity constraints for a real world application.

LAB OUTCOMES:

On Successful Completion, the Student will be able to understand about to create a database
using DDL and apply integrity constraints for a real world application.

PROCEDURE:

One of the most important features that a DBMS must provide is a way of maintaining the
integrity of data. The constraints, which are used to check the modification or insertion of data,
are called integrity constraints. The task of maintaining integrity constraints can be handled by
the user in application programs or by the DBMS.

The most important benefits of handling integrity constraints by the DBMS are the following:

● Increased reliability of data

● Reduced programming time

● Simple maintenance

Using the DBMS to define integrity constraints increases the reliability of data because there is
no possibility that the integrity constraints can be forgotten by a programmer. (If an integrity
constraint is handled by application programs, all programs concerning the constraint must
include the corresponding code. If the code is omitted in one application program, the
consistency of data is compromised.)

An integrity constraint not handled by the DBMS must be defined in every application program
that uses the data involved in the constraint. In contrast, the same integrity constraint must be
defined only once if it is to be handled by the DBMS. Additionally, application-enforced
constraints are usually more complex to code than are database enforced constraints.

If an integrity constraint is handled by the DBMS, the modification of the structure of the
constraint must be handled only once, in the DBMS. The modification of a structure in
application programs requires the modification of every program that involves the corresponding
code.

There are two groups of integrity constraints handled by a DBMS:

● Declarative integrity constraints

● Procedural integrity constraints that are handled by triggers (for the definition of triggers, see

Chapter “Concurrency Controls”)

The declarative constraints are defined using the DDL statements CREATE TABLE and ALTER
TABLE. They can be column-level constraints or table-level constraints. Column-level
constraints, together with the data type and other column properties, are placed within the
declaration of the column, while table-level constraints are always defined at the end of the
CREATE TABLE or ALTER TABLE statement, after the definition of all columns.

Note – There is only one difference between column-level constraints and table-level constraints:
a column-level constraint can be applied only upon one column, while a table-level constraint
can cover one or more columns of a table.
Each declarative constraint has a name. The name of the constraint can be explicitly assigned
using the CONSTRAINT option in the CREATE TABLE statement or the ALTER TABLE
statement. If the CONSTRAINT option is omitted, the Database Engine assigns an implicit name
for the constraint.

Note – Using explicit constraint names is strongly recommended. The search for an integrity
constraint can be greatly enhanced if an explicit name for a constraint is used.
All declarative constraints can be categorized into several groups:

● DEFAULT clause

● UNIQUE clause

● PRIMARY KEY clause

● CHECK clause

● FOREIGN KEY clause and referential integrity


The definition of the default value using the DEFAULT clause was shown earlier in this chapter
(see also Example 5.6). All other constraints are described in detail in the following sections.

The UNIQUE Clause

Sometimes more than one column or group of columns of the table have unique values and
therefore can be used as the primary key. All columns or groups of columns that qualify to be
primary keys are called candidate keys. Each candidate key is defined using the UNIQUE clause
in the CREATE TABLE or the ALTER TABLE statement.

The UNIQUE clause has the following form:

[CONSTRAINT c_name]

UNIQUE [CLUSTERED | NONCLUSTERED] ({ col_name1} ,...)

The CONSTRAINT option in the UNIQUE clause assigns an explicit name to the candidate key.
The option CLUSTERED or NONCLUSTERED relates to the fact that the Database Engine
always generates an index for each candidate key of a table. The index can be clustered—that is,
the physical order of rows is specified using the indexed order of the column values. If the order
is not specified, the index is nonclustered (see also Chapter on Indices). The default value is
NONCLUSTERED. col_name1 is a column name that builds the candidate key. (The maximum
number of columns per candidate key is 16.)

Example 5.6 shows the use of the UNIQUE clause. (You have to drop the projects table, via
DROP TABLE projects, before you execute the following example.)

USEsample;3
CREATE TABLE projects (project_no CHAR(4) DEFAULT'p1',
project_name CHAR(15) NOT NULL,
budget FLOAT NULL
CONSTRAINT unique_no UNIQUE (project_no));
Each value of the project_no column of the projects table is unique, including the NULL value.
(Just as with any other value with a UNIQUE constraint, if NULL values are allowed on a
corresponding column, there can be at most one row with the NULL value for that particular
column.) If an existing value should be inserted into the column project_no, the system rejects it.
The explicit name of the constraint that is defined in Example 5.6 is unique_no.
The PRIMARY KEY Clause

The primary key of a table is a column or group of columns whose value is different in every
row. Each primary key is defined using the PRIMARY KEY clause in the CREATE TABLE or
the ALTER TABLE statement.

The PRIMARY KEY clause has the following form:

[CONSTRAINT c_name]

PRIMARY KEY [CLUSTERED | NONCLUSTERED] ({col_name1} ,...)

All options of the PRIMARY KEY clause have the same meaning as the corresponding options
with the same name in the UNIQUE clause. In contrast to UNIQUE, the PRIMARY KEY
column must be NOT NULL, and its default value is CLUSTERED.

Example 5.7 shows the specification of the primary key for the employee table of the sample
database.

Note – You have to drop the employee table (DROP TABLE employee) before you execute the
following example.
Example 5.7
USEsample;
CREATE TABLE employee (emp_no INTEGER NOT NULL,
emp_fname CHAR(20) NOT NULL,
emp_lname CHAR(20) NOT NULL,
dept_no CHAR(4) NULL,
CONSTRAINT prim_empl PRIMARY KEY (emp_no));
The employee table is re-created and its primary key is defined in Example 5.7. The primary key
of the table is specified using the declarative integrity constraint named prim_empl. This
integrity constraint is a table-level constraint, because it is specified after the definition of all
columns of the employee table.

Example 5.8 is equivalent to Example 5.7, except for the specification of the primary key of the
employee table as a column-level constraint.

Note – Again, you have to drop the employee table (DROP TABLE employee) before you
execute the following example.
Example 5.8
USEsample;
CREATE TABLE employee
(emp_no INTEGER NOT NULL CONSTRAINT prim_empl PRIMARY KEY,
emp_fname CHAR(20) NOT NULL,
emp_lname CHAR(20) NOT NULL,
dept_no CHAR(4) NULL);
In Example 5.8, the PRIMARY KEY clause belongs to the declaration of the corresponding
column, together with its data type and nullability. For this reason, it is called a column-level
constraint.

The CHECK Clause

The check constraint specifies conditions for the data inserted into a column. Each row inserted
into a table or each value updating the value of the column must meet these conditions. The
CHECK clause is used to specify check constraints. This clause can be defined in the CREATE
TABLE or ALTER TABLE statement. The syntax of the CHECK clause is

[CONSTRAINT c_name]
CHECK[NOT FOR REPLICATION]expression
Code language:CSS(css)
expression must evaluate to a Boolean value (true or false) and can reference any columns in the
current table (or just the current column if specified as a column level constraint), but no other
tables. The CHECK clause is not enforced during a replication of the data if the option NOT
FOR REPLICATION exists. (A database, or a part of it, is said to be replicated if it is stored at
more than one site. Replication can be used to enhance the availability of data. Chapter “Query
Optimizer” describes data replication.)

Example 5.9 shows how the CHECK clause can be used.

Example 5.9

USEsample;
CREATE TABLE customer
(cust_no INTEGER NOT NULL,
cust_group CHAR(3) NULL,
CHECK (cust_group IN ('c1', 'c2', 'c10')));
Code language:PHP(php)
The customer table that is created in Example 5.9 contains the cust_group column with the
corresponding check constraint. The database system returns an error if the cust_group column,
after a modification of its existing values or after the insertion of a new row, would contain a
value different from the values in the set (‘c1’, ‘c2’, ‘c10’).

The FOREIGN KEY Clause

A foreign key is a column or group of columns in one table that contains values that match the
primary key values in the same or another table. Each foreign key is defined using the FOREIGN
KEY clause combined with the REFERENCES clause.

The FOREIGN KEY clause has the following form:

[CONSTRAINT c_name]
[[FOREIGN KEY] ({col_name1} ,...)]
REFERENCES table_name ({col_name2},...)
[ON DELETE {NO ACTION| CASCADE | SET NULL | SET DEFAULT}]
[ON UPDATE {NO ACTION | CASCADE | SET NULL | SET
DEFAULT}]
Code language:PHP(php)
The FOREIGN KEY clause defines all columns explicitly that belong to the foreign key. The
REFERENCES clause specifies the table name with all columns that build the corresponding
primary key. The number and the data types of the columns in the FOREIGN KEY clause must
match the number and the corresponding data types of columns in the REFERENCES clause
(and, of course, both of these must match the number and data types of the columns in the
primary key of the referenced table).

The table that contains the foreign key is called the referencing table, and the table that contains
the corresponding primary key is called the parent table or referenced table. Example 5.10 shows
the specification of the foreign key in the works_on table of the sample database.

Note – You have to drop the works_on table before you execute the following example.
Example 5.10
USEsample;
CREATE TABLE works_on
(emp_no INTEGER NOT NULL,
project_no CHAR(4) NOT NULL,
job CHAR (15) NULL,
enter_date DATE NULL,
CONSTRAINT prim_works PRIMARY KEY(emp_no, project_no),
CONSTRAINT foreign_works FOREIGN KEY(emp_no)
REFERENCES employee (emp_no));
Code language:PHP(php)
The works_on table in Example 5.10 is specified with two declarative integrity constraints:
prim_works and foreign_works. Both constraints are table-level constraints, where the former
specifies the primary key and the latter the foreign key of the works_on table. Further, the
constraint foreign_works specifies the employee table as the parent table and its emp_no column
as the corresponding primary key of the column with the same name in the works_on table.

The FOREIGN KEY clause can be omitted if the foreign key is defined as a column-level
constraint, because the column being constrained is the implicit column “list” of the foreign key,
and the keyword REFERENCES is sufficient to indicate what kind of constraint this is. The
maximum number of FOREIGN KEY constraints in a table is 63.

A definition of the foreign keys in tables of a database imposes the specification of another
important integrity constraint: the referential integrity, described next.

CONCLUSION:

Thus Create a database using DDL and apply integrity constraints is done and verified.
EX.4 PERFORMING DATA MANIPULATIONS OPERATIONS ON POPULATED
DATABASE

LAB OBJECTIVES:

To understand about the to perform data manipulations operations on populated database on real
world application.

LAB OUTCOMES:

On Successful Completion, the Student will be able to understand about data manipulations
operations on populated database on real world application.

PROCEDURE:

Oracle provide Data Manipulation Language commands to exercise data operations in the
database.Data operations can be populating the database tables with the application or business
data,modifying the data and removing the data from the database,whenever required. Besides the
data operations,there are set of commands which are used to control these operations.These
commands are grouped as Transaction Control Language.
There are three types of DML statements involved in a logical SQL transaction namely, Insert,
Update, Delete and Merge.A transaction is the logical collection of DML actions within a database
session.
INSERT statement
The INSERT command is used to store data in tables. The INSERT command is often used in
higher-level programming languages such as Visual Basic.NET or C++ as an embedded SQL
command; however,this command can also be executed at the SQL*PLUS prompt in command
mode.There are two different forms of the INSERT command. The first form is used if a new row
will have a value inserted into each column of the row. The second form of the INSERT command
is used to insert rows where some of the column data is unknown or defaulted from another
business logic.This form of the INSERT command requires that you specify column names for
which data are being stored.
Syntax:
The below syntax can be followed if the values for all the columns in the table is definite and
known.
INSERT INTO table
VALUES (column1 value, column2 value,
...);
The below syntax can be used if only few columns from the table have to be populated with a
value. Rest of the columns can deduce their values either as NULL or from a different business
logic.
INSERT INTO table (column1 name, column2 name,...)
VALUES (column1 value, column2 value,...);
The INSERT statement below creates a new employee record in the EMPLOYEES table. Note
that it inserts the values for the primary columns EMPLOYEE_ID, FIRST_NAME, SALARY and
DEPARTMENT_ID.
INSERT INTO employees (EMPLOYEE_ID, FIRST_NAME, SALARY, DEPARTMENT_ID)
VALUES (130,'KEMP',3800,10);
Otherwise, complete employee data can be inserted in the EMPLOYEES table without specifying
the column list using the below INSERT statement - provided the values are known beforehand
and must be in compliance with the data type and position of columns in the table.
INSERT INTO employees
VALUES (130,'KEMP','GARNER','[email protected]','48309290',TO_DATE ('01-JAN-
2012'),'SALES',3800,0,110,10);
Values to be inserted must be compatible with the data type of the column. Literals, fixed values
and special values like functions, SYSDATE, CURRENT_DATE, SEQ.CURRVAL
(NEXTVAL), or USER can be used as column values. Values specified must follow the generic
rules. String literals and date values must be enclosed within quotes. Date value can be supplied
in DD-MON-RR or D-MON-YYYY format, but YYYY is preferred since it clearly specifies the
century and does not depend on internal RR century calculation logic.
INSERT-AS-SELECT (IAS) statement
Data can be populated into the target table from the source table using INSERT..AS..SELECT
(IAS) operation. Its a direct path read operation.Its a simple way of creating copy of the data from
one table to another or creating a backup copy of the table which the source table operations are
online.
For example, data can be copied from EMPLOYEES table to EMP_HISTORY table.
INSERT INTO EMP_HISTORY
SELECT EMPLOYEE_ID, EMPLOYEE_NAME, SALARY, DEPARTMENT_ID
FROM employees;

UPDATE statement
The UPDATE command modifies the data stored in a column.It can update single or multiple rows
at a time depending on the result set filtered by conditions specified in WHERE clause. Note that
Updating columns is different from altering columns. Earlier in this chapter, you studied the
ALTER command.The ALTER command changes the table structure, but leaves the table data
unaffected.The UPDATE command changes data in the table, not the table structure.
Syntax:
UPDATE table
SET column =value[, column =value...]
[WHERE condition]
From the syntax,
The SET column = expression can be any combination of characters, formulas, or functions that
will update data in the specified column name.The WHERE clause is optional, but if it is included,
it specifies which rows will be updated.Only one table can be updated at a time with an UPDATE
command.
The UPDATE statement below updates the salary of employee JOHN to 5000.
UPDATE employees
SET salary =5000
WHERE UPPER (first_name)='JOHN';
Though WHERE predicates are optional, but must be logically appended so as to modify only the
required row in the table. The UPDATE statement below updates the salaries of all the employees
in the table.
UPDATE employees
SET salary =5000;
Multiple columns can also be updated by specifying multiple columns in SET clause separated by
a comma. For example, if both salary and job role has to be changed to 5000 and SALES
respectively for JOHN, the UPDATE statement looks like,
UPDATE employees
SET SALARY =5000,
JOB_ID ='SALES'
WHERE UPPER (first_name)='JOHN';

1 row updated.
Another way of updating multiple columns of the same row shows the usage of subquery.
UPDATE employees
SET (SALARY, JOB_ID)=(SELECT 5000,'SALES' FROM DUAL)
WHERE UPPER (ENAME)='JOHN'
DELETE statement
The DELETE command is one of the simplest of the SQL statements. It removes one or more rows
from a table. Multiple table delete operations are not allowed in SQL.The syntax of the DELETE
command is as below.
DELETE FROM table_name
[WHERE condition];
The DELETE command deletes all rows in the table that satisfy the condition in the optional
WHERE clause. Since the WHERE clause is optional, one can easily delete all rows from a table
by omitting a WHERE clause since the WHERE clause limits the scope of the DELETE operation.
The below DELETE statement would remove EDWIN's details from EMP table.
DELETE employees
WHERE UPPER (ENAME)='EDWIN'

1 row deleted.
Note: DELETE [TABLE NAME] and DELETE FROM [TABLE NAME] hold the same meaning.
The WHERE condition in the conditional delete statements can make use of subquery as shown
below.
DELETE FROM employees
WHERE DEPARTMENT_ID IN (SELECT DEPARTMENT_ID
FROM LOCATIONS
WHERE LOCATION_CODE ='SFO')

TRUNCATE
Truncate is a DDL command which is used to flush out all records from a table but retaining the
table structure. It does not supports WHERE condition to remove the selected records.
Syntax:
TRUNCATE [table name]
It is Auto Commit i.e. it commits the current active transaction in the session. Truncating the table
does not drops dependent indexes, triggers or table constraints. If a table A is parent of a reference
constraint of a table B in the database, the table A could not be truncated.
Transaction
A transaction is a logical unit of work done in database. It can either contain -
● Multiple DML commands ending with a TCL command i.e. COMMIT or ROLLBACK
● One DDL command
● One DCL command
Beginning of a transaction is marked with the first DML command. It ends with a TCL, DDL or
DCL command. A TCL command i.e. COMMIT or ROLLBACK is issues explicitly to end an
active transaction. By virtue of their basic behavior, if any of DDL or DCL commands get executed
in a database session, commit the ongoing active transaction in the session. If the database instance
crashes abnormally, the transaction is stopped.
COMMIT, ROLLBACK and SAVEPOINT are the transaction control language. COMMIT
applies the data changes permanently into the database while ROLLBACK does anti-commit
operation. SAVEPOINT controls the series of a transaction by setting markers at different
transaction stages. User can roll back the current transaction to the desired save point, which was
set earlier.
COMMIT - Commit ends the current active transaction by applying the data changes permanently
into the database tables. COMMIT is a TCL command which explicitly ends the transaction.
However, the DDL and DCL command implicitly commit the transaction.
SAVEPOINT - Savepoint is used to mark a specific point in the current transaction in the session.
Since it is logical marker in the transaction, savepoints cannot be queried in the data dictionaries.
ROLLBACK - The ROLLBACK command is used to end the entire transaction by discarding the
data changes. If the transaction contains marked savepoints, ROLLBACK TO SAVEPOINT
[name] can be used to rollback the transaction upto the specified savepoint only. As a result, all
the data changes upto the specified savepoint will be discarded.
Demonstration
Consider the EMPLOYEES table which gets populated with newly hired employee details during
first quarter of every year. The clerical staff appends each employee detail with a savepoint, so as
to rollback any faulty data at any moment during the data feeding activity. Note that he keeps the
savepoint names same as the employee names.
INSERT INTO employees (employee_id,first_name,hire_date,job_id, salary,department_id)
VALUES (105,'Allen',TO_DATE('15-JAN-2013','SALES',10000,10);

SAVEPOINT Allen;

INSERT INTO employees (employee_id,first_name,hire_date,job_id, salary,department_id)


VALUES (106,'Kate',TO_DATE('15-JAN-2013','PROD',10000,20);

SAVEPOINT Kate;

INSERT INTO employees (employee_id,first_name,hire_date,job_id, salary,department_id)


VALUES (107,'McMan',TO_DATE ('15-JAN-2013','ADMIN',12000,30);

SAVEPOINT McMan;
Suppose, the data feeding operator realises that he has wrongly entered the salary of 'Kate' and
'McMan'. He rolls back the active transaction to the savepoint Kate and re-enters the employee
details for Kate and McMan.
ROLLBACK TO SAVEPOINT Kate;

INSERT INTO employees (employee_id,first_name,hire_date,job_id, salary,department_id)


VALUES (106,'Kate',TO_DATE('15-JAN-2013','PROD',12500,20);

SAVEPOINT Kate;

INSERT INTO employees (employee_id,first_name,hire_date,job_id, salary,department_id)


VALUES (107,'McMan',TO_DATE ('15-JAN-2013','ADMIN',13200,30);

SAVEPOINT McMan;
Once he is done with the data entry, he can commit the entire transaction by issuing COMMIT in
the current session.
Read Consistency
Oracle maintains consistency among the users in each session in terms of data access and
read/write actions.
When a DML occurs on a table, the original data values changed by the action are recorded in the
database undo records. As long as transaction is not committed into database, any user in other
session that later queries the modified data views the original data values. Oracle uses current
information in the system global area and information in the undo records to construct a read-
consistent view of a table's data for a query. Only when a transaction is committed, the changes of
the transaction made permanent. The transaction is the key to Oracle's strategy for providing read
consistency.
Start point for read-consistent views is generated on behalf of readers
Controls when modified data can be seen by other transactions of the database for reading or
updating

CONCLUSION:

Thus thedata manipulations operations on populated database on real world application is done
and verified.
EX.5 PERFORMING AUTHORIZATION USING GRANT AND REVOKE

LAB OBJECTIVES:

To understand about Performing Authorization using Grant and Revoke

LAB OUTCOMES:

On Successful Completion, the Student will be able to understand about Performing Authorization
using Grant and Revoke on real world application.

PROCEDURE:

We have already learned about how to create users in MySQL using MySQL | create user
statement. But using the Create User Statement only creates a new user but does not grant any
privileges to the user account. Therefore to grant privileges to a user account, the GRANT
statement is used. Syntax:
GRANT privileges_names ON object TO user;
Parameters Used:
● privileges_name: These are the access rights or privileges granted to the user.
● object:It is the name of the database object to which permissions are being granted. In the
case of granting privileges on a table, this would be the table name.
● user:It is the name of the user to whom the privileges would be granted.
Privileges: The privileges that can be granted to the users are listed below along with the
description:
Let us now learn about different ways of granting privileges to the users:
1. Granting SELECT Privilege to a User in a Table: To grant Select Privilege to a table
named “users” where User Name is Amit, the following GRANT statement should be
executed.
GRANT SELECT ON Users TO'Amit'@'localhost;
1. Granting more than one Privilege to a User in a Table: To grant multiple Privileges to a
user named “Amit” in a table “users”, the following GRANT statement should be executed.
GRANT SELECT, INSERT, DELETE, UPDATE ON Users TO 'Amit'@'localhost;
1. Granting All the Privilege to a User in a Table: To Grant all the privileges to a user
named “Amit” in a table “users”, the following Grant statement should be executed.
GRANT ALL ON Users TO 'Amit'@'localhost;
1. Granting a Privilege to all Users in a Table: To Grant a specific privilege to all the users
in a table “users”, the following Grant statement should be executed.
GRANT SELECT ON Users TO '*'@'localhost;
1. In the above example the “*” symbol is used to grant select permission to all the users of the
table “users”.
2. Granting Privileges on Functions/Procedures: While using functions and procedures, the
Grant statement can be used to grant users the ability to execute the functions and
procedures in MySQL. Granting Execute Privilege: Execute privilege gives the ability to
execute a function or procedure. Syntax:
GRANT EXECUTE ON [ PROCEDURE | FUNCTION ] object TO user;
Different ways of granting EXECUTE Privileges:
Granting EXECUTE privileges on a function in MySQL.: If there is a function named
“CalculateSalary” and you want to grant EXECUTE access to the user named Amit, then the
following GRANT statement should be executed.
GRANT EXECUTE ON FUNCTION Calculatesalary TO 'Amit'@localhost';
Granting EXECUTE privileges to all Users on a function in MySQL.: If there is a function
named “CalculateSalary” and you want to grant EXECUTE access to all the users, then the
following GRANT statement should be executed.
GRANT EXECUTE ON FUNCTION Calculatesalary TO '*'@localhost';
Granting EXECUTE privilege to a Users on a procedure in MySQL.: If there is a procedure
named “DBMSProcedure” and you want to grant EXECUTE access to the user named Amit,
then the following GRANT statement should be executed.
GRANT EXECUTE ON PROCEDURE DBMSProcedure TO 'Amit'@localhost';
Granting EXECUTE privileges to all Users on a procedure in MySQL.: If there is a
procedure called “DBMSProcedure” and you want to grant EXECUTE access to all the users,
then the following GRANT statement should be executed.
GRANT EXECUTE ON PROCEDURE DBMSProcedure TO '*'@localhost';
Checking the Privileges Granted to a User: To see the privileges granted to a user in a table,
the SHOW GRANTS statement is used. To check the privileges granted to a user named “Amit”
and host as “localhost”, the following SHOW GRANTS statement will be executed:
SHOW GRANTS FOR 'Amit'@localhost';
Output:
GRANTS FOR Amit@localhost
GRANT USAGE ON *.* TO `SUPER`@localhost`
Revoking Privileges from a Table
The Revoke statement is used to revoke some or all of the privileges which have been granted to
a user in the past. Syntax:
REVOKE privileges ON object FROM user;
Parameters Used:
● object: It is the name of the database object from which permissions are being revoked. In
the case of revoking privileges from a table, this would be the table name.
● user: It is the name of the user from whom the privileges are being revoked.
Privileges can be of the following
values:

Different Ways of revoking privileges from a user:


1. Revoking SELECT Privilege to a User in a Table: To revoke Select Privilege to a table
named “users” where User Name is Amit, the following revoke statement should be
executed.
REVOKE SELECT ON users FROM 'Amit'@localhost';
1. Revoking more than Privilege to a User in a Table: To revoke multiple Privileges to a
user named “Amit” in a table “users”, the following revoke statement should be executed.
REVOKE SELECT, INSERT, DELETE, UPDATE ON Users FROM 'Amit'@'localhost;
1. Revoking All the Privilege to a User in a Table: To revoke all the privileges to a user
named “Amit” in a table “users”, the following revoke statement should be executed.
REVOKE ALL ON Users FROM 'Amit'@'localhost;
1. Revoking a Privilege to all Users in a Table: To Revoke a specific privilege to all the
users in a table “users”, the following revoke statement should be executed.
REVOKE SELECT ON Users FROM '*'@'localhost;
1. Revoking Privileges on Functions/Procedures: While using functions and procedures, the
revoke statement can be used to revoke the privileges from users which have been
EXECUTE privileges in the past. Syntax:
REVOKE EXECUTE ON [ PROCEDURE | FUNCTION ] object FROM user;
● Revoking EXECUTE privileges on a function in MySQL.: If there is a function called
“CalculateSalary” and you want to revoke EXECUTE access to the user named Amit, then
the following revoke statement should be executed.
REVOKE EXECUTE ON FUNCTION Calculatesalary FROM 'Amit'@localhost';
● Revoking EXECUTE privileges to all Users on a function in MySQL.: If there is a
function called “CalculateSalary” and you want to revoke EXECUTE access to all the users,
then the following revoke statement should be executed.
REVOKE EXECUTE ON FUNCTION Calculatesalary FROM '*'@localhost';
● Revoking EXECUTE privilege to a Users on a procedure in MySQL.: If there is a
procedure called “DBMSProcedure” and you want to revoke EXECUTE access to the user
named Amit, then the following revoke statement should be executed.
REVOKE EXECUTE ON PROCEDURE DBMSProcedure FROM 'Amit'@localhost';
● Revoking EXECUTE privileges to all Users on a procedure in MySQL.: If there is a
procedure called “DBMSProcedure” and you want to revoke EXECUTE access to all the
users, then the following revoke statement should be executed.
REVOKE EXECUTE ON PROCEDURE DBMSProcedure FROM '*'@localhost';

CONCLUSION:
Thus the Performing Authorization using Grant and Revoke is done and verified.
EX.6 IMPLEMENTING BASIC AND COMPLEX SQL QUERIES

LAB OBJECTIVES:

To understand about Implementing Basic and complex SQL queries on real world application.

LAB OUTCOMES:

On Successful Completion, the Student will be able to understand about Implementing Basic and
complex SQL queries on real world application.

PROCEDURE:

Writing my first query

Let’s start by using the surveys table. Here we have data on every individual that was captured at
the site, including when they were captured, what plot they were captured on, their species ID,
sex and weight in grams.
Let’s write an SQL query that selects only the year column from the surveys table. SQL queries
can be written in the box located under the “Execute SQL” tab. Click ‘Run SQL’ to execute the
query in the box.
SELECT year
FROM surveys;
We have capitalized the words SELECT and FROM because they are SQL keywords. SQL is
case insensitive, but it helps for readability, and is good style.
If we want more information, we can just add a new column to the list of fields, right
after SELECT:
SELECT year, month, day
FROM surveys;
Or we can select all of the columns in a table using the wildcard *
SELECT *
FROM surveys;
Unique values

If we want only the unique values so that we can quickly see what species have been sampled we
use DISTINCT
SELECT DISTINCT species_id
FROM surveys;
If we select more than one column, then the distinct pairs of values are returned
SELECT DISTINCT year, species_id
FROM surveys;
Calculated values

We can also do calculations with the values in a query. For example, if we wanted to look at the
mass of each individual on different dates, but we needed it in kg instead of g we would use
SELECT year, month, day, weight/1000.0
FROM surveys;
When we run the query, the expression weight / 1000.0 is evaluated for each row and appended
to that row, in a new column. Expressions can use any fields, any arithmetic operators (+, -, *,
and /) and a variety of built-in functions. For example, we could round the values to make them
easier to read.
SELECT plot_id, species_id, sex, weight, ROUND(weight / 1000.0, 2)
FROM surveys;

Challenge

Write a query that returns the year, month, day, species_id and weight in mg
SOLUTION
SELECT day, month, year, species_id, weight * 1000
FROM surveys;
Filtering

Databases can also filter data – selecting only the data meeting certain criteria. For example, let’s
say we only want data for the species Dipodomysmerriami, which has a species code of DM. We
need to add a WHERE clause to our query:
SELECT *
FROM surveys
WHERE species_id='DM';
We can do the same thing with numbers. Here, we only want the data since 2000:
SELECT * FROM surveys
WHERE year >= 2000;
We can use more sophisticated conditions by combining tests with AND and OR. For example,
suppose we want the data on Dipodomysmerriami starting in the year 2000:
SELECT *
FROM surveys
WHERE (year >= 2000) AND (species_id = 'DM');
Note that the parentheses are not needed, but again, they help with readability. They also ensure
that the computer combines AND and OR in the way that we intend.
If we wanted to get data for any of the Dipodomys species, which have species codes DM, DO,
and DS, we could combine the tests using OR:
SELECT *
FROM surveys
WHERE (species_id = 'DM') OR (species_id = 'DO') OR (species_id = 'DS');
Challenge

Write a query that returns the day, month, year, species_id, and weight (in kg) for individuals
caught on Plot 1 that weigh more than 75 g
SOLUTION
SELECT day, month, year, species_id, weight / 1000.0
FROM surveys
WHERE plot_id = 1
AND weight > 75;

Building more complex queries

Now, lets combine the above queries to get data for the 3 Dipodomys species from the year 2000
on. This time, let’s use IN as one way to make the query easier to understand. It is equivalent to
saying WHERE (species_id = 'DM') OR (species_id = 'DO') OR (species_id = 'DS'), but reads
more neatly:
SELECT *
FROM surveys
WHERE (year >= 2000) AND (species_id IN ('DM', 'DO', 'DS'));
We started with something simple, then added more clauses one by one, testing their effects as
we went along. For complex queries, this is a good strategy, to make sure you are getting what
you want. Sometimes it might help to take a subset of the data that you can easily see in a
temporary database to practice your queries on before working on a larger or more complicated
database.
When the queries become more complex, it can be useful to add comments. In SQL, comments
are started by --, and end at the end of the line. For example, a commented version of the above
query can be written as:
-- Get post 2000 data on Dipodomys' species
-- These are in the surveys table, and we are interested in all columns
SELECT * FROM surveys
-- Sampling year is in the column `year`, and we want to include 2000
WHERE (year >= 2000)
-- Dipodomys' species have the `species_id` DM, DO, and DS
AND (species_id IN ('DM', 'DO', 'DS'));
Although SQL queries often read like plain English, it is always useful to add comments; this is
especially true of more complex queries.
Sorting

We can also sort the results of our queries by using ORDER BY. For simplicity, let’s go back to
the species table and alphabetize it by taxa.
First, let’s look at what’s in the species table. It’s a table of the species_id and the full genus,
species and taxa information for each species_id. Having this in a separate table is nice, because
we didn’t need to include all this information in our main surveys table.
SELECT *
FROM species;
Now let’s order it by taxa.
SELECT *
FROM species
ORDER BY taxa ASC;
The keyword ASC tells us to order it in Ascending order. We could alternately use DESC to get
descending order.
SELECT *
FROM species
ORDER BY taxa DESC;
ASC is the default.
We can also sort on several fields at once. To truly be alphabetical, we might want to order by
genus then species.
SELECT *
FROM species
ORDER BY genus ASC, species ASC;
Challenge

Write a query that returns year, species_id, and weight in kg from the surveys table, sorted with
the largest weights at the top.
SOLUTION
SELECT year, species_id, weight / 1000.0
FROM surveys ORDER BY weight DESC;
Order of execution

Another note for ordering. We don’t actually have to display a column to sort by it. For
example, let’s say we want to order the birds by their species ID, but we only want to see genus
and species.
SELECT genus, species
FROM species
WHERE taxa = 'Bird'
ORDER BY species_id ASC;
We can do this because sorting occurs earlier in the computational pipeline than field
selection.
The computer is basically doing this:

1. Filtering rows according to WHERE


2. Sorting results according to ORDER BY
3. Displaying requested columns or expressions.

Clauses are written in a fixed order: SELECT, FROM, WHERE, then ORDER BY. It is possible
to write a query as a single line, but for readability, we recommend to put each clause on its own
line.
Challenge

Let’s try to combine what we’ve learned so far in a single query. Using the surveys table write a
query to display the three date fields, species_id, and weight in kilograms (rounded to two
decimal places), for individuals captured in 1999, ordered alphabetically by the species_id. Write
the query as a single line, then put each clause on its own line, and see how more legible the
query becomes!
SOLUTION
SELECT year, month, day, species_id, ROUND(weight / 1000.0, 2)
FROM surveys
WHERE year = 1999
ORDER BY species_id;
Conclusion:
Thus Implementing Basic and complex SQL queries on real world application.
EX.7 IMPLEMENTATION OF VIEWS AND TRIGGERS
LAB OBJECTIVES:

To understand about the Implementation of Views and Triggers

LAB OUTCOMES:

On Successful Completion, the Student will be able to understand about the Implementation of
Views and Triggers.

PROCEDURE:

A trigger in SQL is a procedural code that is automatically executed in response to certain events
on a specified table. It is important to understand how these small codes make such a huge
difference in database performance. In this article, you will learn how to implement triggers along
with examples.

The following topics will be covered in this article:

● What is a Trigger?
● Syntax and Example
● Operation in Triggers
● Advantage and Disadvantage

What is a Trigger?
Triggers are the SQL codes that are automatically executed in response to certain events on a
particular table. These are used to maintain the integrity of the data. A trigger in SQL works similar
to a real-world trigger. For example, when the gun trigger is pulled a bullet is fired. We all know
this, but how this is related to Triggers in SQL? To understand this let’s consider a hypothetical
situation.
John is the marketing officer in a company. When a new customer data is entered into the
company’s database he has to send the welcome message to each new customer. If it is one or two
customers John can do it manually, but what if the count is more than a thousand? Well in such
scenario triggers come in handy.

Thus, now John can easily create a trigger which will automatically send a welcome email to the
new customers once their data is entered into the database. So I hope you are clear with the
introduction of Triggers in SQL.

Always remember that there cannot be two triggers with similar action time and event for one
table. For example, we cannot have two BEFORE UPDATE triggers for a table. But we can have
a BEFORE UPDATE and a BEFORE INSERT trigger, or a BEFORE UPDATE and an AFTER
UPDATE trigger.

Before we dive further into the fundamentals of triggers I would suggest you to understand the
concepts of SQL Basics and Normalization so that you get a better grip on Triggers in SQL.

Syntax and Example

Lets now look at the syntax of a trigger.

1 Create Trigger Trigger_Name

2 (Before | After) [ Insert | Update | Delete]

3 on [Table_Name]

4 [ for each row | for each column ]

5 [ trigger_body ]

Now let me break down this syntax and explain each and every part in detail.
● Create Trigger
These two keywords are used to specify that a trigger block is going to be declared.
● Trigger_Name
It specifies the name of the trigger. Trigger name has to be unique and shouldn’t repeat.
● ( Before | After )
This specifies when the trigger will be executed. It tells us the time at which the trigger is
initiated, i.e, either before the ongoing event or after.

● Before Triggers are used to update or validate record values before they’re saved to the
database.
● After Triggers are used to access field values that are set by the system and to effect
changes in other records. The records that activate the after trigger are read-only. We
cannot use After trigger if we want to update a record because it will lead to read-only
error.
● [ Insert | Update | Delete ]
These are the DML operations and we can use either of them in a given trigger.
● on [ Table_Name ]
We need to mention the table name on which the trigger is being applied. Don’t forget to
use on keyword and also make sure the selected table is present in the database.
● [ for each row | for each column ]

1.
1. Row-level trigger gets executed before or after any column value of a row changes
2. Column Level Trigger gets executed before or after the specified column changes

● [ trigger_body]
It consists of queries that need to be executed when the trigger is called.

So this was all about a simple trigger. But we can also create a nested trigger that can do multi-
process. Also handling it and terminating it at the right time is very important. If we don’t end the
trigger properly it may lead to an infinite loop.

You might be wondering in which scenario we can use the nested trigger. Rather than giving you
a tailored answer let me share a scenario with you, which will help you in understanding the nested
trigger in a better way. Continuing from the earlier scenario, John sent an email for every new
customer that was added to the company’s database. Now, what if he wishes to keep track of the
number of customers to whom the email was sent? Now John needs to create a nested trigger to
keep the track of the count along with sending an email.

So that was all about the syntax of triggers, lets now try to implement an example of triggers in
SQL.

Example for Trigger:


In the below trigger, we are trying to calculate the percentage of the student as soon as his details
are updated to the database.

1 CREATE TRIGGER sample_trigger

2 before INSERT

3 ON student

4 FOR EACH ROW

5 SET new.total = new.marks/6;

Here the “NEW” keyword refers to the row that is getting affected.

Operations in Triggers
We can perform many operations using triggers. Some may be simple and some may be a little
complex, but once if we go through the query its easy to understand.

● DROP A Trigger

1 DROP TRIGGER trigger name;

● Display A Trigger

The below code will display all the triggers that are present.

1 SHOW TRIGGERS;

The below code will display all the triggers that are present in a particular database.

1 SHOW TRIGGERS

2 IN database_name;

Example:

1 SHOW TRIGGERS IN edureka;

In the above example, all the triggers that are present in the database named Edureka will be
displayed.

We also look at some major variants of the triggers that is Before insert and After insert. We have
already seen a trigger in the example. But with the help of the table lets see how exactly this works.
As we have already understood how to create a trigger, now let’s understand the two variants of
the trigger those are Before insert and After insert. in order to implement them, let’s create a
student table with various columns as shown below:

1 CREATE TABLE Student(

2 studentID INT NOT NULL AUTO_INCREMENT,

3 FName VARCHAR(20),

4 LName VARCHAR(20),

5 Address VARCHAR(30),

6 City VARCHAR(15),

7 Marks INT,

8 PRIMARY KEY(studentID)

9 );

Now if we execute this query we get the following table.

Let’s try to use the first variant i.e, Before Insert

1 CREATE TRIGGER calculate

2 before INSERT

3 ON student

4 FOR EACH ROW

5 SET new.marks = new.marks+100;

Here when we insert data into the student table automatically the trigger will be invoked. The
trigger will add 100 to the marks column into the student column.

Now let’s use the second variant i.e, After Insert


To use this variant we need one more table i.e, Percentage where the trigger will store the results.
Use the below code to create the Percentage Table.

1 create table Final_mark(

2 per int );

Now let us use the after insert trigger

1 CREATE TRIGGER total_mark

2 after insert

3 ON student

4 FOR EACH ROW

5 insert into Final_mark values(new.marks);

Here when we insert data to the table, total_mark trigger will store the result in the Final_mark
table.

That was all about the operation on triggers, lets now move ahead and look at its advantages and
disadvantages.

Advantages and Disadvantages of Triggers


Advantages

● Forcing security approvals on the table that are present in the database
● Triggers provide another way to check the integrity of data
● Counteracting invalid exchanges
● Triggers handle errors from the database layer
● Normally triggers can be useful for inspecting the data changes in tables
● Triggers give an alternative way to run scheduled tasks. Using triggers, we don’t have to
wait for the scheduled events to run because the triggers are invoked automatically before
or after a change is made to the data in a table

Disadvantages

● Triggers can only provide extended validations, i.e, not all kind validations. For simple
validations, you can use the NOT NULL, UNIQUE, CHECK and FOREIGN KEY
constraints
● Triggers may increase the overhead of the database
● Triggers can be difficult to troubleshoot because they execute automatically in the
database, which may not invisible to the client applications

This brings us to the end of this Triggers in SQL article. I hope you understood the concepts of
Triggers.

If you wish to learn more about MySQL and get to know this open-source relational database, then
check out our MySQL DBA Certification Training which comes with instructor-led live training
and real-life project experience. This training will help you understand MySQL in-depth and help
you achieve mastery over the subject.

Views in SQL are kind of virtual tables. A view also has rows and columns as they are in a real
table in the database. We can create a view by selecting fields from one or more tables present in
the database. A View can either have all the rows of a table or specific rows based on certain
condition.
In this article we will learn about creating , deleting and updating Views.
Sample Tables:
StudentDetails

StudentMarks

CREATING VIEWS
We can create View using CREATE VIEW statement. A View can be created from a single
table or multiple tables.
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE condition;

view_name: Name for the View


table_name: Name of the table
condition: Condition to select rows
Examples:
● Creating View from a single table:
● In this example we will create a View named DetailsView from the table
StudentDetails.
Query:
● CREATE VIEW DetailsView AS

● SELECT NAME, ADDRESS


● FROM StudentDetails
● WHERE S_ID < 5;
To see the data in the View, we can query the view in the same manner as we
query a table.
SELECT * FROM DetailsView;
Output:

● In this example, we will create a view named StudentNames from the table
StudentDetails.
Query:
● CREATE VIEW StudentNames AS

● SELECT S_ID, NAME


● FROM StudentDetails
● ORDER BY NAME;
If we now query the view as,
SELECT * FROM StudentNames;
Output:

● Creating View from multiple tables: In this example we will create a View named
MarksView from two tables StudentDetails and StudentMarks. To create a View from
multiple tables we can simply include multiple tables in the SELECT statement. Query:
● CREATE VIEW MarksView AS

● SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS


● FROM StudentDetails, StudentMarks
● WHERE StudentDetails.NAME = StudentMarks.NAME;
To display data of View MarksView:
SELECT * FROM MarksView;
Output:

DELETING VIEWS
We have learned about creating a View, but what if a created View is not needed any more?
Obviously we will want to delete it. SQL allows us to delete an existing View. We can delete or
drop a View using the DROP statement.
Syntax:
DROP VIEW view_name;

view_name: Name of the View which we want to delete.


For example, if we want to delete the View MarksView, we can do this as:
DROP VIEW MarksView;
UPDATING VIEWS
There are certain conditions needed to be satisfied to update a view. If any one of these
conditions is not met, then we will not be allowed to update the view.
1. The SELECT statement which is used to create the view should not include GROUP BY
clause or ORDER BY clause.
2. The SELECT statement should not have the DISTINCT keyword.
3. The View should have all NOT NULL values.
4. The view should not be created using nested queries or complex queries.
5. The view should be created from a single table. If the view is created using multiple tables
then we will not be allowed to update the view.
● We can use the CREATE OR REPLACE VIEW statement to add or remove fields from a
view.
Syntax:
● CREATE OR REPLACE VIEW view_name AS

● SELECT column1,coulmn2,..
● FROM table_name
● WHERE condition;
For example, if we want to update the view MarksView and add the field AGE to this View
from StudentMarks Table, we can do this as:
CREATE OR REPLACE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS,
StudentMarks.AGE
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
If we fetch all the data from MarksView now as:
SELECT * FROM MarksView;
Output:

● Inserting a row in a view:


We can insert a row in a View in a same way as we do in a table. We can use the INSERT
INTO statement of SQL to insert a row in a View.Syntax:
● INSERT INTO view_name(column1, column2 , column3,..)
● VALUES(value1, value2, value3..);

● view_name: Name of the View


Example:
In the below example we will insert a new row in the View DetailsView which we have
created above in the example of “creating views from a single table”.
INSERT INTO DetailsView(NAME, ADDRESS)
VALUES("Suresh","Gurgaon");
If we fetch all the data from DetailsView now as,
SELECT * FROM DetailsView;
Output:

● Deleting a row from a View:


Deleting rows from a view is also as simple as deleting rows from a table. We can use the
DELETE statement of SQL to delete rows from a view. Also deleting a row from a view
first delete the row from the actual table and the change is then reflected in the view.Syntax:
● DELETE FROM view_name

● WHERE condition;

● view_name:Name of view from where we want to delete rows


● condition: Condition to select rows
Example:
In this example we will delete the last row from the view DetailsView which we just added
in the above example of inserting rows.
DELETE FROM DetailsView
WHERE NAME="Suresh";
If we fetch all the data from DetailsView now as,
SELECT * FROM DetailsView;
Output:

WITH CHECK OPTION


The WITH CHECK OPTION clause in SQL is a very useful clause for views. It is applicable to
a updatable view. If the view is not updatable, then there is no meaning of including this clause
in the CREATE VIEW statement.
● The WITH CHECK OPTION clause is used to prevent the insertion of rows in the view
where the condition in the WHERE clause in CREATE VIEW statement is not satisfied.
● If we have used the WITH CHECK OPTION clause in the CREATE VIEW statement, and
if the UPDATE or INSERT clause does not satisfy the conditions then they will return an
error.
Example:
In the below example we are creating a View SampleView from StudentDetails Table with
WITH CHECK OPTION clause.

CREATE VIEW SampleView AS


SELECT S_ID, NAME
FROM StudentDetails
WHERE NAME IS NOT NULL
WITH CHECK OPTION;
In this View if we now try to insert a new row with null value in the NAME column then it will
give an error because the view is created with the condition for NAME column as NOT NULL.
For example,though the View is updatable but then also the below query for this View is not
valid:
INSERT INTO SampleView(S_ID)
VALUES(6);
NOTE: The default value of NAME column is null.
Uses of a View :
A good database should contain views due to the given reasons:
1. Restricting data access –
Views provide an additional level of table security by restricting access to a predetermined
set of rows and columns of a table.
2. Hiding data complexity –
A view can hide the complexity that exists in a multiple table join.
3. Simplify commands for the user –
Views allows the user to select information from multiple tables without requiring the users
to actually know how to perform a join.
4. Store complex queries –
Views can be used to store complex queries.
5. Rename Columns –
Views can also be used to rename the columns without affecting the base tables provided the
number of columns in view must match the number of columns specified in select statement.
Thus, renaming helps to hide the names of the columns of the base tables.
6. Multiple view facility –
Different views can be created on the same table for different users.

Conclusion:
Thus Triggers and Views on real world application is done and verified.
EX.8 TCL COMMANDS IN SQL

LAB OBJECTIVES:

To understand about TCL commands for real world applications.

LAB OUTCOMES:

On Successful Completion, the Student will be able to understand about TCL Commands on real
world application.

PROCEDURE:

TCL Commands in SQL

o In SQL, TCL stands for Transaction control language.


o A single unit of work in a database is formed after the consecutive execution of commands
is known as a transaction.
o There are certain commands present in SQL known as TCL commands that help the user
manage the transactions that take place in a database.
o COMMIT. ROLLBACK and SAVEPOINT are the most commonly used TCL
commands in SQL.

Now let us take a deeper dive into the TCL commands of SQL with the help of examples. All the
queries in the examples will be written using the MySQL database.
1. COMMIT
COMMIT command in SQL is used to save all the transaction-related changes permanently to the
disk. Whenever DDL commands such as INSERT, UPDATE and DELETE are used, the changes
made by these commands are permanent only after closing the current session. So before closing
the session, one can easily roll back the changes made by the DDL commands. Hence, if we want
the changes to be saved permanently to the disk without closing the session, we will use the commit
command.
Syntax:
1. COMMIT;
Example:

We will select an existing database, i.e., school.

1. mysql> USE school;


To create a table named t_school, we will execute the following query:

1. mysql> CREATE TABLE t_school(ID INT, School_Name VARCHAR(40), Number_Of_Stud


ents INT, Number_Of_Teachers INT, Number_Of_Classrooms INT, EmailID VARCHAR(40))
;

BEGIN / START TRANSACTION command is used to start the transaction.

1. mysql> START TRANSACTION;

Now, we will execute the following query to insert multiple records at the same time in the t_school
table.

1. mysql> INSERT INTO t_school(ID, School_Name, Number_Of_Students, Number_Of_Teache


rs, Number_Of_Classrooms, EmailID) VALUES(1, "Boys Town Public School", 1000, 80, 12, "
[email protected]"), (2, "Guru Govind Singh Public School", 800, 35, 15, "[email protected]
"), (3, "Delhi Public School", 1200, 30, 10, "[email protected]"), (4, "Ashoka Universal Schoo
l", 1110, 40, 40, "[email protected]"), (5, "Calibers English Medium School", 9000, 31, 50, "ce
[email protected]");
We will now execute the SELECT query to verify the execution of the INSERT INTO query
executed above.

1. mysql> SELECT *FROM t_school;


After executing the SELECT query on the t_school table, you will get the following output:

I School_N Number_Of_St Number_Of_Te Number_Of_Clas EmailID


D ame udents achers srooms

1 Boys Town 1000 80 12 btps15@gmail


Public .com
School

2 Guru 800 35 15 ggps25@gmai


Govind l.com
Singh
Public
School

3 Delhi 1200 30 10 dps101@gmai


Public l.com
School

4 Ashoka 1110 40 40 aus17@gmail.


Universal com
School

5 Calibers 9000 31 50 cems@gmail.


English com
Medium
School

The output of the SELECT query shows that all the records are inserted successfully.
We will execute the COMMIT command to save the results of the operations carried on the
t_school table.

1. mysql> COMMIT;

Autocommit is by default enabled in MySQL. To turn it off, we will set the value of autocommit
as 0.

1. mysql> SET autocommit = 0;

MySQL, by default, commits every query the user executes. But if the user wishes to commit only
the specific queries instead of committing every query, then turning off the autocommit is useful.
2. SAVEPOINT
We can divide the database operations into parts. For example, we can consider all the insert related
queries that we will execute consecutively as one part of the transaction and the delete command
as the other part of the transaction. Using the SAVEPOINT command in SQL, we can save these
different parts of the same transaction using different names. For example, we can save all the
insert related queries with the savepoint named INS. To save all the insert related queries in one
savepoint, we have to execute the SAVEPOINT query followed by the savepoint name after
finishing the insert command execution.
Syntax:
1. SAVEPOINT savepoint_name;

3. ROLLBACK
While carrying a transaction, we must create savepoints to save different parts of the transaction.
According to the user's changing requirements, he/she can roll back the transaction to different
savepoints. Consider a scenario: We have initiated a transaction followed by the table creation
and record insertion into the table. After inserting records, we have created a savepoint INS. Then
we executed a delete query, but later we thought that mistakenly we had removed the useful record.
Therefore in such situations, we have an option of rolling back our transaction. In this case, we
have to roll back our transaction using the ROLLBACK command to the savepoint INS, which we
have created before executing the DELETE query.

Syntax:
1. ROLLBACK TO savepoint_name;

Examples to understand the SAVEPOINT and ROLLBACK commands:

Example 1:

We will select an existing database, i.e., school.

1. mysql> USE school;

To create a table named t_school, we will execute the following query:

1. mysql> CREATE TABLE t_school(ID INT, School_Name VARCHAR(40), Number_Of_Stud


ents INT, Number_Of_Teachers INT, Number_Of_Classrooms INT, EmailID VARCHAR(40))
;

Now, we will execute the following query to insert multiple records at the same time in the t_school
table.

1. mysql> INSERT INTO t_school(ID, School_Name, Number_Of_Students, Number_Of_Teache


rs, Number_Of_Classrooms, EmailID) VALUES(1, "Boys Town Public School", 1000, 80, 12, "
[email protected]"), (2, "Guru Govind Singh Public School", 800, 35, 15, "[email protected]
"), (3, "Delhi Public School", 1200, 30, 10, "[email protected]"), (4, "Ashoka Universal Schoo
l", 1110, 40, 40, "[email protected]"), (5, "Calibers English Medium School", 9000, 31, 50, "ce
[email protected]");
We will now execute the SELECT query to verify the execution of the INSERT INTO query
executed above.

1. mysql> SELECT *FROM t_school;

After executing the SELECT query on the t_school table, you will get the following output:

I School_Name Numbe Number_Of Number_Of_Cla EmailID


D r_Of_St _Teachers ssrooms
udents

1 Boys Town Public 80 12 [email protected]


School 1000

2 Guru Govind Singh 800 35 15 ggps25@gma


Public School il.com

3 Delhi Public School 1200 30 10 dps101@gma


il.com

4 Ashoka Universal 1110 40 40 aus17@gmail


School .com

5 Calibers English 9000 31 50 cems@gmail.


Medium School com

The output of the SELECT query shows that all the records are inserted successfully.

BEGIN / START TRANSACTION command is used to start the transaction.

1. mysql> START TRANSACTION;


As we know, the SAVEPOINT command in SQL is used to save the different parts of the same
transaction using different names. Consider till this point as one part of our transaction. We will
save this part using a savepoint named Insertion.

1. mysql> SAVEPOINT Insertion;

Now, we will execute the update command on the t_school table to set the Number_Of_Students
as 9050 for the record with ID 5.

1. mysql> UPDATE t_school SET Number_Of_Students = 9050 WHERE ID = 5;

To verify that the record with ID 5 now has the Number_Of_Students as 9050, we will execute the
SELECT query.

1. mysql> SELECT *FROM t_school;

After executing the SELECT query on the t_school table, you will get the following output:

I School_ Number_Of_S Number_Of_T Number_Of_Cla EmailID


D Name tudents eachers ssrooms

1 Boys Town 1000 80 12 btps15@gmai


Public l.com
School

2 Guru 800 35 15 ggps25@gma


Govind il.com
Singh
Public
School
3 Delhi 1200 30 10 dps101@gma
Public il.com
School

4 Ashoka 1110 40 40 aus17@gmail


Universal .com
School

5 Calibers 9050 31 50 cems@gmail.


English com
Medium
School

The output of the SELECT query shows that the record with ID 5 is updated successfully.

Consider the update operation as one part of our transaction. We will save this part using a
savepoint named Updation.

1. mysql> SAVEPOINT Updation;

Suddenly, our requirement changed, and we realized that we had updated a record that was not
supposed to be. In such a scenario, we need to roll back our transaction to the savepoint, which
was created prior to the execution of the UPDATE command.

1. mysql> ROLLBACK TO Insertion;

We didn't need the updation carried on the record. Hence, we have rolled back to the savepoint
named Insertion.

For confirming that we have got the same t_school table that we had before carrying out the
updation operation, we will again execute the SELECT query.

1. mysql> SELECT *FROM t_school;


I School_ Number_Of_S Number_Of_T Number_Of_Cl EmailID
D Name tudents eachers assrooms

1 Boys 1000 80 12 btps15@gmail.


Town comm
Public
School

2 Guru 800 35 15 ggps25@gmail


Govind .comm
Singh
Public
School

3 Delhi 1200 30 10 dps101@gmail


Public .comm
School

4 Ashoka 1110 40 40 aus17@gmail.


Universal comm
School

5 Calibers 9000 31 50 [email protected]


English om
Medium
School

The SELECT query output confirms that the transaction is now successfully rolled back to the
savepoint 'Insertion'.

Example 2:

We will select an existing database, i.e., bank.

1. mysql> USE bank;


To create a table named customer, we will execute the following query:

1. mysql> CREATE TABLE customer(Customer_ID INT PRIMARY KEY, Name VARCHAR(


20), Age INT, Salary INT, Salary_BankAccount VARCHAR(20));

Now, we will execute the following query to insert multiple records at the same time in the
customer table.

1. mysql> INSERT INTO customer(Customer_ID, Name, Age, Salary, Salary_BankAccount) VA


LUES(1, "Aryan Jain", 51, 56000, "SBI"), (2, "Arohi Dixit", 21, 25000, "Axis"), (3, "Vineet Gar
g", 24, 31000, "ICICI"), (4, "Anuja Sharma", 26, 49000, "HDFC"), (5, "Deepak Kohli", 28, 6500
0, "SBI");

We will now execute the SELECT query to verify the execution of the INSERT INTO query
executed above.

1. mysql> SELECT *FROM customer;

After executing the SELECT query on the t_school table, you will get the following output:
Customer_ID Name Age Salary Salary_BankAccount

1 Aryan Jain 51 56000 SBI

2 Arohi Dixit 21 25000 Axis

3 Vineet Garg 24 31000 ICICI

4 Anuja Sharma 26 49000 HDFC

5 Deepak Kohli 28 65000 SBI

The output of the SELECT query shows that all the records are inserted successfully.

BEGIN / START TRANSACTION command is used to start the transaction.

1. mysql> START TRANSACTION;

As we know, the SAVEPOINT command in SQL is used to save the different parts of the same
transaction using different names. Consider till this point as one part of our transaction. We will
save this part using a savepoint named Insertion.

1. mysql> SAVEPOINT Insertion;

We will execute the delete command on the customer table to remove the record with ID 5.

1. mysql> DELETE FROM customer WHERE Customer_ID = 5;


We will execute the SELECT query to verify that the record with ID 5 has been removed.

1. mysql> SELECT *FROM customer;

Customer_ID Name Age Salary Salary_BankAccount

1 Aryan Jain 51 56000 SBI

2 Arohi Dixit 21 25000 Axis

3 Vineet Garg 24 31000 ICICI

4 Anuja Sharma 26 49000 HDFC

The output of the SELECT query shows that the record with ID 5 is removed successfully.

Consider the delete operation as one part of our transaction. We will save this part using a savepoint
named Deletion.

1. mysql> SAVEPOINT Deletion;

Suddenly, our requirement changed, and we realized that we had deleted a record that was not
supposed to be. In such a scenario, we need to roll back our transaction to the savepoint, which
was created prior to the execution of the DELETE command.

1. mysql> ROLLBACK TO Insertion;

We didn't need the deletion carried on the record. Hence, we have rolled back to the savepoint
named Insertion.

For confirming that we have got the same customer table that we had before carrying out the
deletion operation, we will again execute the SELECT query.

1. mysql> SELECT *FROM customer;


Customer_ID Name Age Salary Salary_BankAccount

1 Aryan Jain 51 56000 SBI

2 Arohi Dixit 21 25000 Axis

3 Vineet Garg 24 31000 ICICI

4 Anuja Sharma 26 49000 HDFC

5 Deepak Kohli 28 65000 SBI

The SELECT query output confirms that the transaction is now successfully rolled back to the
savepoint 'Insertion'.

Conclusion:

Thus the TCL Commands in SQL are done and verified.


EX.9 IMPLEMENTING FUNCTIONS AND PROCEDURES IN SQL

LAB OBJECTIVES:

To understand about the Implementing functions and procedures in SQL

LAB OUTCOMES:

On Successful Completion, the Student will be able to understand about Implementing functions and
procedures in SQL

PROCEDURE:

What are functions?


Functions are methods used to perform data operations. SQL has many in-built functions used to
perform string concatenations, mathematical calculations etc.

SQL functions are categorized into the following two categories:

1. Aggregate Functions
2. Scalar Functions

Let us look into each one of them, one by one.

Aggregate SQL Functions


The Aggregate Functions in SQL perform calculations on a group of values and then return a single
value. Following are a few of the most commonly used Aggregate Functions:

Function Description

SUM() Used to return the sum of a group of values.

Returns the number of rows either based on a


COUNT()
condition, or without a condition.
Used to calculate the average value of a numeric
AVG()
column.

This function returns the minimum value of a


MIN()
column.

MAX() Returns a maximum value of a column.

FIRST() Used to return the first value of the column.

This function returns the last value of the


LAST()
column.

Let us look into each one of the above functions in depth. For your better understanding, I will be
considering the following table to explain to you all the examples.

StudentID StudentName Marks

1 Sanjay 64

2 Varun 72

3 Akash 45

4 Rohit 86

5 Anjali 92

SUM()
Used to return a total sum of numeric column which you choose.

Syntax:
SELECTSUM(ColumnNa
1
me)
2
FROMTableName;

Example:
Write a query to retrieve the sum of marks of all students from the Students table.

SELECTSUM(Ma
1
rks)
2 FROMStudents;

Output:
3
1 5
9

COUNT()
Returns the number of rows present in the table either based on some condition or without any
condition.

Syntax:
SELECTCOUNT(ColumnNa
1
me)
2
FROMTableName
3
WHERECondition;

Example:
Write a query to count the number of students from the Students table.

SELECTCOUNT(Student
1
ID)
2
FROMStudents;

Output:
1 5

Example:
Write a query to count the number of students scoring marks > 75 from the Students table.

SELECTCOUNT(Student
1
ID)
2
FROMStudents
3
WHEREMarks >75;

Output:
1 2

AVG()
This function is used to return the average value of a numeric column.

Syntax:
SELECTAVG(ColumnNa
1
me)
2
FROMTableName;

Example:
Write a query to calculate the average marks of all students from the Students table.

SELECTAVG(Ma
1
rks)
2
FROMStudents;

Output:
7
1
1
.
8

MIN()
Used to return the minimum value of a numeric column.

Syntax:
SELECTMIN(ColumnNa
1
me)
2
FROMTableName;

Example:

Write a query to retrieve the minimum marks out of all students from the Students table.

SELECTMIN(Ma
1
rks)
2
FROMStudents;
Output:
1

MAX()
Returns the maximum value of a numeric column.

Syntax:
SELECTMAX(ColumnNa
1
me)
2
FROMTableName;

Example:
Write a query to retrieve the maximum marks out of all students from the Students table.

SELECTMAX(Ma
1
rks)
2
FROMStudents;

Output:

FIRST()
This function returns the first value of the column which you choose.

Syntax:
SELECTFIRST(ColumnNa
1
me)
2
FROMTableName;

Example:
Write a query to retrieve the marks of the first student.

SELECTFIRST(Ma
1
rks)
2
FROMStudents;

Output:
1

LAST()
Used to return the last value of the column which you choose.

Syntax:
SELECTLAST(ColumnNa
1
me)
2
FROMTableName;

Example:
Write a query to retrieve the marks of the last student.

SELECTLAST(Ma
1
rks)
2
FROMStudents;

Output: 92

Well, with that we come to an end to SQL Aggregate Functions. Next in this article on SQL
Functions, let us understand the various Scalar Functions.

Scalar SQL Functions


The Scalar Functions in SQL are used to return a single value from the given input
value. Following are a few of the most commonly used Aggregate Functions:

Let us look into each one of the above functions in depth.

Function Description

Used to convert string column values to


LCASE()
lowercase

This function is used to convert a string column


UCASE()
values to Uppercase.

Returns the length of the text values in the


LEN()
column.
Extracts substrings in SQL from column values
MID()
having String data type.

Rounds off a numeric value to the nearest


ROUND()
integer.

This function is used to return the current


NOW()
system date and time.

FORMAT() Used to format how a field must be displayed.

LCASE()
Used to convert values of a string column to lowercase characters.

Syntax:
SELECTLCASE(ColumnNa
1
me)
2
FROMTableName;

Example:
Write a query to retrieve the names of all students in lowercase.

SELECTLCASE(StudentNa
1
me)
2
FROMStudents;

Output:
sa
1 nj
ay
2
va
3 ru
n
4
ak
5 as
h
ro
hit

an
jal
i

UCASE()
Used to convert values of a string column to uppercase characters.

Syntax:
SELECTUCASE(ColumnNa
1
me)
2
FROMTableName;

Example:

Write a query to retrieve the names of all students in lowercase.

SELECTUCASE(StudentNa
1
me)
2
FROMStudents;

Output:
SANJ
AY
1 VAR
UN
2
AKA
3
SH
4
ROHI
5 T
ANJ
ALI

LEN()
Used to retrieve the length of the input string.
Syntax:
SELECTLENGTH(String)
1
ASSampleColumn;

Example:
Write a query to extract the length of the student name “Sanjay”.

SELECTLENGTH(“Sanjay”)
1
ASStudentNameLen;

Output:
1 6

MID()
This function is used to extract substrings from columns having string data type.

Syntax:
SELECTMID(ColumnName, Start,
1
Length)
2
FROMTableName;

Example:
Write a query to extract substrings from the StudentName column.

SELECTMID(StudentName,
1
2, 3)
2
FROMStudents;

Output:
1
a
2 n
j
3
a
4 r
u
5
k
a
s

o
h
i

n
j
a

ROUND()
This function is used to round off a numeric value to the nearest integer.

Syntax:
SELECTROUND(ColumnName,
1
Decimals)
2
FROMTableName;

Example:
For this example, let us consider the following Marks table in the Students table.

StudentID StudentName Marks

1 Sanjay 90.76

2 Varun 80.45

3 Akash 54.32

4 Rohit 72.89

5 Anjali 67.66

Write a query to round the marks to the integer value.

1 SELECTROUND(Ma

2 rks)
FROMStudents;

Output:
9
1
1 8
0
2
5
3
4
4
7
5 3
6
8

NOW()
Used to return the current date and time. The date and time are returned in the “YYYY-MM-DD
HH-MM-SS” format.

Syntax:
SELECTNO
1
W();

Example:

Write a query to retrieve the current date and time.

SELECT NOW();

Output:

NOW()

2019-10-14 09:16:36

FORMAT()
This function formats the way a field must be displayed.
Syntax:

FORMAT(InputValue, Format)

Example:

Write a query to display the numbers “123456789” in the format “###-###-###”

SELECT FORMAT(123456789, “###-###-###”);

Output:

123-456-789

WHAT IS A STORED PROCEDURE?

A stored procedure is a prepared SQL code that you can save, so the code can be reused over and
over again.

So if you have an SQL query that you write over and over again, save it as a stored procedure,
and then just call it to execute it.

You can also pass parameters to a stored procedure, so that the stored procedure can act based on
the parameter value(s) that is passed.

Stored Procedure Syntax

CREATE PROCEDURE procedure_name


AS
sql_statement
GO;

Execute a Stored Procedure

EXEC procedure_name;

Demo Database

Below is a selection from the "Customers" table in the Northwind sample database:
CustomerI CustomerName ContactNa Address City PostalCo Countr
D me de y

1 AlfredsFutterkiste Maria Obere Str. Berlin 12209 Germa


Anders 57 ny

2 Ana Trujillo Ana Trujillo Avda. de la Méxi 05021 Mexico


Emparedados y Constitució co
helados n 2222 D.F.

3 Antonio Moreno Antonio Mataderos Méxi 05023 Mexico


Taquería Moreno 2312 co
D.F.

4 Around the Horn Thomas 120 Lond WA1 UK


Hardy Hanover Sq. on 1DP

5 Berglundssnabbkö Christina Berguvsväg Luleå S-958 22 Swede


p Berglund en 8 n
Stored Procedure Example

The following SQL statement creates a stored procedure named "SelectAllCustomers" that
selects all records from the "Customers" table:

Example

CREATE PROCEDURE SelectAllCustomers


AS
SELECT * FROM Customers
GO;

Execute the stored procedure above as follows:

Example

EXEC SelectAllCustomers;

Stored Procedure With One Parameter

The following SQL statement creates a stored procedure that selects Customers from a particular
City from the "Customers" table:

Example

CREATE PROCEDURE SelectAllCustomers @City nvarchar(30)


AS
SELECT * FROM Customers WHERE City = @City
GO;

Execute the stored procedure above as follows:

Example

EXEC SelectAllCustomers @City = 'London';

Stored Procedure With Multiple Parameters

Setting up multiple parameters is very easy. Just list each parameter and the data type separated
by a comma as shown below.
The following SQL statement creates a stored procedure that selects Customers from a particular
City with a particular PostalCode from the "Customers" table:

Example

CREATE PROCEDURE SelectAllCustomers @City nvarchar(30), @PostalCode nvarchar(10)


AS
SELECT * FROM Customers WHERE City = @City AND PostalCode = @PostalCode
GO;

Execute the stored procedure above as follows:

Example

EXEC SelectAllCustomers @City = 'London', @PostalCode = 'WA1 1DP';

Conclusion:

Thus Implementing functions and procedures in SQL is done and verified.


EXPERIMENT-10

AIM: Implementation Of Views And Triggers In Sql

Procedure:

1. Setup the Database and Table:

• Create a sample database and a table to store employee information.

• Insert sample records into the table.

2. Implement Views:

• Create a View to retrieve specific data from the table.

• Modify the View to update its structure.

• Retrieve data using the View.

• Drop the View when no longer needed.

3. Implement Triggers:

• Create an Audit Log Table to track salary changes.

• Define a Trigger that logs changes when a salary update occurs.

• Test the Trigger by updating employee salary.

• Verify that the Trigger captures changes in the audit log.

• Drop the Trigger when no longer needed.

Implementation:

Step 1: Create Database and Table

CREATE DATABASE CompanyDB;


CREATE TABLE Employees (

EmpID INT PRIMARY KEY,

Name VARCHAR(50),

Department VARCHAR(50),

Salary DECIMAL(10,2));

Step 2: Insert Sample Data

INSERT INTO Employees VALUES (1, 'John Doe', 'IT', 60000);

INSERT INTO Employees VALUES (2, 'Jane Smith', 'HR', 55000);

INSERT INTO Employees VALUES (3, 'Alice Johnson', 'Finance', 70000);

Part 1: Implementation of Views

Step 3: Create a View to Show IT Department Employees

CREATE VIEW IT_Employees AS

SELECT EmpID, Name, Salary FROM Employees

WHERE Department = 'IT';

Step 4: Retrieve Data from View

SELECT * FROM IT_Employees;

Step 5: Modify the View

CREATE OR REPLACE VIEW IT_Employees AS

SELECT EmpID, Name FROM Employees WHERE Department = 'IT';

Step 6: Drop the View


DROP VIEW IT_Employees;

Part 2: Implementation of Triggers

Step 7: Create an Audit Table for Salary Updates

CREATE TABLE Salary_Log (

LogID INT AUTO_INCREMENT PRIMARY KEY,

EmpID INT,

OldSalary DECIMAL(10,2),

NewSalary DECIMAL(10,2),

ChangeTime TIMESTAMP DEFAULT CURRENT_TIMESTAMP);

Step 8: Create a Trigger for Salary Updates

CREATE TRIGGER Salary_Update_Trigger

BEFORE UPDATE ON Employees

FOR EACH ROW

BEGIN

INSERT INTO Salary_Log (EmpID, OldSalary, NewSalary)

VALUES (OLD.EmpID, OLD.Salary, NEW.Salary);

END;

Step 9: Test the Trigger by Updating Salary

UPDATE Employees SET Salary = 65000 WHERE EmpID = 1;

SELECT * FROM Salary_Log;

Step 10: Drop the Trigger


DROP TRIGGER Salary_Update_Trigger;

Conclusion:

• Views provide a virtual representation of data, enhancing security and simplifying query
execution.

• Triggers automate database operations by responding to specific changes in a table.

• This experiment successfully demonstrated the creation, modification, and deletion of


Views and Triggers in SQL.
EX.11. DATABASE CONNECTIVITY USING JDBC

LAB OBJECTIVES:

To understand about database connectivity using JDBC

LAB OUTCOMES:

On Successful Completion, the Student will be able to understand about database connectivity
using JDBC

PROCEDURE:

Establishing JDBC Connection in Java


Before establishing a connection between the front end i.e your Java Program and the back end
i.e the database we should learn what precisely a JDBC is and why it came into existence. Now
let us discuss what exactly JDBC stands for and will ease out with the help of real-life
illustration to get it working.
What is JDBC?
JDBC is an acronym for Java Database Connectivity. It’s an advancement for ODBC ( Open
Database Connectivity ). JDBC is a standard API specification developed in order to move data
from frontend to the backend. This API consists of classes and interfaces written in Java. It
basically acts as an interface (not the one we use in Java) or channel between your Java program
and databases i.e it establishes a link between the two so that a programmer could send data from
Java code and store it in the database for future use.
Illustration: Working of JDBC co-relating with real-time
Why JDBC Come into Existence?
As previously told JDBC is an advancement for ODBC, ODBC being platform-dependent had a
lot of drawbacks. ODBC API was written in C, C++, Python, and Core Java and as we know
above languages (except Java and some part of Python )are platform-dependent. Therefore to
remove dependence, JDBC was developed by a database vendor which consisted of classes and
interfaces written in Java.
Steps For Connectivity Between Java Program and Database
1. Import the Packages
2. Load the drivers using the forName() method
3. Register the drivers using DriverManager
4. Establish a connection using the Connection class object
5. Create a statement
6. Execute the query
7. Close the connections
Let us discuss these steps in brief before implementing by writing suitable code to illustrate
connectivity steps for JDBC/
Step 1: Import the Packages
Step 2: Loading the drivers
In order to begin with, you first need to load the driver or register it before using it in the program.
Registration is to be done once in your program. You can register a driver in one of two ways
mentioned below as follows:
2-A Class.forName()
Here we load the driver’s class file into memory at the runtime. No need of using new or create
objects. The following example uses Class.forName() to load the Oracle driver as shown below as
follows:
Class.forName(“oracle.jdbc.driver.OracleDriver”);
2-B DriverManager.registerDriver()
DriverManager is a Java inbuilt class with a static member register. Here we call the constructor
of the driver class at compile time. The following example uses DriverManager.registerDriver()to
register the Oracle driver as shown below:
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())
Step 3: Establish a connection using the Connection class object
After loading the driver, establish connections as shown below as follows:
Connection con = DriverManager.getConnection(url,user,password)
● user: Username from which your SQL command prompt can be accessed.
● password: password from which the SQL command prompt can be accessed.
● con: It is a reference to the Connection interface.
● Url: Uniform Resource Locator which is created as shown below:
String url = “ jdbc:oracle:thin:@localhost:1521:xe”
Where oracle is the database used, thin is the driver used, @localhost is the IP Address where a
database is stored, 1521 is the port number and xe is the service provider. All 3 parameters above
are of String type and are to be declared by the programmer before calling the function. Use of this
can be referred to from the final code.
Step 4: Create a statement
Once a connection is established you can interact with the database. The JDBCStatement,
CallableStatement, and PreparedStatement interfaces define the methods that enable you to send
SQL commands and receive data from your database.
Use of JDBC Statement is as follows:
Statement st = con.createStatement();
Note: Here, con is a reference to Connection interface used in previous step .
Step 5: Execute the query
Now comes the most important part i.e executing the query. The query here is an SQL Query.
Now we know we can have multiple types of queries. Some of them are as follows:
● The query for updating/inserting a table in a database.
● The query for retrieving data.
The executeQuery() method of the Statement interface is used to execute queries of retrieving
values from the database. This method returns the object of ResultSet that can be used to get all
the records of a table.
The executeUpdate(sql query) method of the Statement interface is used to execute queries of
updating/inserting.
Pseudo Code:
int m = st.executeUpdate(sql);
if (m==1)
System.out.println("inserted successfully : "+sql);
else
System.out.println("insertion failed");
Here sql is SQL query of the type String

● Java

// This code is for establishing connection with MySQL


// database and retrieving data
// from db Java Database connectivity
/*
*1. import --->java.sql
*2. load and register the driver --->com.jdbc.
*3. create connection
*4. create a statement
*5. execute the query
*6. process the results
*7. close
*/

importjava.io.*;
importjava.sql.*;

classGFG {
publicstaticvoidmain(String[] args) throwsException
{
String url
= "jdbc:mysql://localhost:3306/table_name"; // table details
String username = "rootgfg"; // MySQL credentials
String password = "gfg123";
String query
= "select *from students"; // query to be run
Class.forName(
"com.mysql.cj.jdbc.Driver"); // Driver name
Connection con = DriverManager.getConnection(
url, username, password);
System.out.println(
"Connection Established successfully");
Statement st = con.createStatement();
ResultSetrs
= st.executeQuery(query); // Execute query
rs.next();
String name
= rs.getString("name"); // Retrieve name from db

System.out.println(name); // Print result on console


st.close(); // close statement
con.close(); // close connection
System.out.println("Connection Closed....");
}
}
Output:

name of the student is retrieved from database

Step 6: Closing the connections


So finally we have sent the data to the specified location and now we are on the verge of completing
our task. By closing the connection, objects of Statement and ResultSet will be closed
automatically. The close() method of the Connection interface is used to close the connection. It
is shown below as follows:
con.close();
Example:

● Java

// Java Program to Establish Connection in JDBC

// Importing database
import java.sql.*;
// Importing required classes
import java.util.*;

// Main class
class Main {

// Main driver method


public static void main(String a[])
{

// Creating the connection using Oracle DB


// Note: url syntax is standard, so do grasp
String url = "jdbc:oracle:thin:@localhost:1521:xe";

// Username and password to access DB


// Custom initialization
String user = "system";
String pass = "12345";

// Entering the data


Scanner k = new Scanner(System.in);

System.out.println("enter name");
String name = k.next();

System.out.println("enter roll no");


int roll = k.nextInt();

System.out.println("enter class");
String cls = k.next();

// Inserting data using SQL query


String sql = "insert into student1 values('" + name
+ "'," + roll + ",'" + cls + "')";

// Connection class object


Connection con = null;

// Try block to check for exceptions


try {

// Registering drivers
DriverManager.registerDriver(
new oracle.jdbc.OracleDriver());

// Reference to connection interface


con = DriverManager.getConnection(url, user,
pass);

// Creating a statement
Statement st = con.createStatement();

// Executing query
int m = st.executeUpdate(sql);
if (m == 1)
System.out.println(
"inserted successfully : " + sql);
else
System.out.println("insertion failed");
// Closing the connections
con.close();
}

// Catch block to handle exceptions


catch (Exception ex) {
// Display message when exceptions occurs
System.err.println(ex);
}
}
}

Output:

Conclusion:
Thus database connectivity using JDBC is done and verified.
EXPERIMENT-12
Aim: Implementation and Demonstration of Transaction and Concurrency Control
Techniques Using Locks

Lab Objective: Prevent data anomalies such as dirty reads, lost updates, and uncommitted data in
concurrent transactions.

Lab Outcomes: Successfully implement transaction management & concurrency control in real-
world database scenarios.

Procedure:

1. Transactions in SQL:
A transaction is a sequence of SQL statements executed as a single unit. Transactions ensure
database integrity through ACID properties:
• Atomicity: Ensures all operations in a transaction either complete successfully or none
execute at all.
• Consistency: Ensures the database remains in a consistent state before and after the
transaction.
• Isolation: Ensures that concurrent transactions do not interfere with each other.
• Durability: Ensures that once a transaction is committed, it is permanently stored in the
database.
Transaction Control Commands (TCL):
Command Description
COMMIT Saves all changes made by the transaction permanently.
ROLLBACK Reverts changes made during the transaction if an error occurs.
SAVEPOINT Creates a point within a transaction to which it can be rolled back.

2. Concurrency Control & Locks:


When multiple transactions access the database at the same time, concurrency control ensures
data consistency.
Types of Locks:
Lock Type Description
Shared Lock (S) Allows multiple transactions to read but not modify data.
Exclusive Lock (X) Prevents other transactions from reading or modifying the locked data.
Implicit Locks Applied automatically by the DBMS.
Explicit Locks Manually applied by using SQL LOCK statements.

Procedure:
Step 1: Create a Sample Database and Table
sql
CopyEdit
CREATE DATABASE BankDB;
USE BankDB;

CREATE TABLE Accounts (


AccountID INT PRIMARY KEY,
AccountHolder VARCHAR(50),
Balance DECIMAL(10,2)
);
Step 2: Insert Sample Data
sql
CopyEdit
INSERT INTO Accounts VALUES (101, 'Alice', 5000.00);
INSERT INTO Accounts VALUES (102, 'Bob', 7000.00);
INSERT INTO Accounts VALUES (103, 'Charlie', 9000.00);

Implementation of Transactions
Step 3: Demonstrate COMMIT & ROLLBACK
sql
CopyEdit
-- Start a transaction
START TRANSACTION;

-- Withdraw 1000 from Alice's account


UPDATE Accounts SET Balance = Balance - 1000 WHERE AccountID = 101;

-- Deposit 1000 into Bob's account


UPDATE Accounts SET Balance = Balance + 1000 WHERE AccountID = 102;

-- Check the balance before commit


SELECT * FROM Accounts;

-- If everything is correct, commit the transaction


COMMIT;
If an error occurs, rollback changes:
sql
CopyEdit
ROLLBACK;
SELECT * FROM Accounts;

Step 4: Using SAVEPOINT in Transactions


sql
CopyEdit
START TRANSACTION;

UPDATE Accounts SET Balance = Balance - 500 WHERE AccountID = 101;


SAVEPOINT Save1;

UPDATE Accounts SET Balance = Balance + 500 WHERE AccountID = 102;


SAVEPOINT Save2;

-- If an issue occurs, rollback to a specific savepoint


ROLLBACK TO Save1;

-- Finalize transaction
COMMIT;

Implementation of Concurrency Control Using Locks


Step 5: Demonstrate Shared Lock (S)
sql
CopyEdit
-- Transaction 1: Apply shared lock on an account
START TRANSACTION;
SELECT * FROM Accounts WHERE AccountID = 101 LOCK IN SHARE MODE;

-- Transaction 2: Try to update the same account (This will wait until the first transaction is
completed)
UPDATE Accounts SET Balance = Balance + 500 WHERE AccountID = 101;

-- Commit first transaction


COMMIT;

Step 6: Demonstrate Exclusive Lock (X)


sql
CopyEdit
-- Transaction 1: Apply an exclusive lock
START TRANSACTION;
SELECT * FROM Accounts WHERE AccountID = 101 FOR UPDATE;

-- Transaction 2: Try to read the same account (It will wait until the first transaction is completed)
SELECT * FROM Accounts WHERE AccountID = 101;

-- Commit first transaction to release lock


COMMIT;

Expected Output:
1. Transaction Implementation:
o The balance should update correctly after COMMIT.
o After ROLLBACK, changes should be undone.
2. Lock Implementation:
o Shared locks allow multiple reads but prevent updates.
o Exclusive locks prevent both reading and updating until the transaction is
committed.

Conclusion:
• Transactions ensure database integrity through ACID properties.
• Concurrency control techniques using locks help in avoiding data inconsistency in
concurrent transactions.
• Using locks (Shared & Exclusive) ensures that race conditions and data corruption do not
occur.
• This experiment successfully demonstrated Transaction Management & Concurrency
Control Techniques in SQL.

You might also like