SlideShare a Scribd company logo
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.
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
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.
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
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
Strong Entity Set Weak Entity Set
Strong entity set always has a primary key.
It does not have enough attributes to build
a primary 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
symbol.
It contains a Partial Key which is
represented by a dashed underline symbol.
The member of a strong entity set is called as
dominant entity set.
The member of a weak entity set called as
a subordinate entity set.
 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.
Conclusion:
Thus for designing an entity-relationship (er) / extended entity-relationship (eer) model is studied and verified
for the application.
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 en ty is involved in the rela onship. Total par cipa on is represented by double
lines.
Partial participation − Not all en es are involved in the rela onship. Par al par cipa on 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.
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.
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.)
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.
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.
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.)
Example 5.6
USE sample;
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} ,...)
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
USE sample;
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.
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
USE sample;
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
USE sample;
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.
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.
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.
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', 'kemp.garner@xxx.com', '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.
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.
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.
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 the data manipulations operations on populated database on real world application is done and verified.
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.
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 select more than one column, then the distinct pairs of values are returned
SELECT DISTINCT year, species_id
FROM surveys;
Calculated values
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 Dipodomys merriami, 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 use more sophisticated conditions by combining tests with AND and OR . For example, suppose we
want the data on Dipodomys merriami starting in the year 2000:
SELECT *
FROM surveys
WHERE (year >= 2000) AND (species_id = 'DM');
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.
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.
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.
Conclusion:
Thus Implementing Basic and complex SQL queries on real world application.
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.
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
2
3
4
5
Create Trigger Trigger_Name
(Before | After) [ Insert | Update | Delete]
on [Table_Name]
[ for each row | for each column ]
[ trigger_body ]
Now let me break down this syntax and explain each and every part in detail.
 Create 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.
 [ 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.
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
2
3
4
5
CREATE TRIGGER sample_trigger
before INSERT
ON student
FOR EACH ROW
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;
Now if we execute this query we get the following table.
Let’s try to use the first variant i.e, Before Insert
1
2
CREATE TRIGGER calculate
before INSERT
3
4
5
ON student
FOR EACH ROW
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
2
create table Final_mark(
per int );
Now let us use the after insert trigger
1
2
3
4
5
CREATE TRIGGER total_mark
after insert
ON student
FOR EACH ROW
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
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
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;
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;
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.
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.
Conclusion:
Thus Triggers and Views on real world application is done and verified.
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.
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
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”
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
import java.io.*;
import java.sql.*;
class GFG {
url, username, password)
System.out.println(
public static void main(String[] args) throws
Exception
{
String url
=
"jdbc:mysql://localhost:3306/table_name";
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(
"Connection Established successfully");
Statement st = con.createStatement();
ResultSet rs
= 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
// Inserting data using SQL query
String sql = "insert into student1 values('" + name
+ "'," + roll + ",'" + cls + "')";
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");
// 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
String cls = k.next(); catch (Exception ex) {
// Display message when exceptions occurs
System.err.println(ex);
}
}
}
Output:
Conclusion:
Thus database connectivity using JDBC is done and verified.
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.
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_Students INT, Num
ber_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_Teachers, Number_Of
_Classrooms, EmailID) VALUES(1, "Boys Town Public School", 1000, 80, 12, "btps15@gmail.com"), (2, "Gu
ru Govind Singh Public School", 800, 35, 15, "ggps25@gmail.com"), (3, "Delhi Public School", 1200, 30, 10, "
dps101@gmail.com"), (4, "Ashoka Universal School", 1110, 40, 40, "aus17@gmail.com"), (5, "Calibers Englis
h Medium School", 9000, 31, 50, "cems@gmail.com");
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:
ID School_Name Number_Of_Students Number_Of_Teachers Number_Of_Classrooms EmailID
1 Boys Town Public School 1000 80 12 btps15@gmail.com
2 Guru Govind Singh Public
School
800 35 15 ggps25@gmail.com
3 Delhi Public School 1200 30 10 dps101@gmail.com
4 Ashoka Universal School 1110 40 40 aus17@gmail.com
5 Calibers English Medium
School
9000 31 50 cems@gmail.com
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.
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.
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_Students INT, Num
ber_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_Teachers, Number_Of
_Classrooms, EmailID) VALUES(1, "Boys Town Public School", 1000, 80, 12, "btps15@gmail.com"), (2, "Gu
ru Govind Singh Public School", 800, 35, 15, "ggps25@gmail.com"), (3, "Delhi Public School", 1200, 30, 10, "
dps101@gmail.com"), (4, "Ashoka Universal School", 1110, 40, 40, "aus17@gmail.com"), (5, "Calibers Englis
h Medium School", 9000, 31, 50, "cems@gmail.com");
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:
ID School_Name Number_Of_Students Number_Of_Teachers Number_Of_Classrooms EmailID
1 Boys Town
Public School
1000
80 12 btps15@gmail.com
2 Guru Govind
Singh Public
School
800 35 15 ggps25@gmail.com
3 Delhi Public
School
1200 30 10 dps101@gmail.com
4 Ashoka
Universal School
1110 40 40 aus17@gmail.com
5 Calibers English
Medium School
9000 31 50 cems@gmail.com
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
D
School_Na
me
Number_Of_Stu
dents
Number_Of_Teac
hers
Number_Of_Classr
ooms
EmailID
1
Boys Town
Public
School
1000 80 12
btps15@gmail.c
om
2
Guru Govind
Singh Public
School
800 35 15
ggps25@gmail.
com
3
Delhi Public
School
1200 30 10
dps101@gmail.
com
4
Ashoka
Universal
School
1110 40 40
aus17@gmail.c
om
5
Calibers
English
Medium
School
9050 31 50
cems@gmail.co
m
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;
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
D
School_N
ame
Number_Of_St
udents
Number_Of_Te
achers
Number_Of_Clas
srooms
EmailID
1 Boys Town
Public
School
1000 80 12 btps15@gmail.c
omm
2 Guru
Govind
Singh
Public
School
800 35 15 ggps25@gmail.
comm
3 Delhi
Public
School
1200 30 10 dps101@gmail.
comm
4 Ashoka
Universal
School
1110 40 40 aus17@gmail.c
omm
5 Calibers
English
Medium
School
9000 31 50 cems@gmail.co
m
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) VALUES(1, "Arya
n Jain", 51, 56000, "SBI"), (2, "Arohi Dixit", 21, 25000, "Axis"), (3, "Vineet Garg", 24, 31000, "ICICI"), (4, "A
nuja Sharma", 26, 49000, "HDFC"), (5, "Deepak Kohli", 28, 65000, "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;
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_BankAccoun
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;
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.
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:
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:
1
2
SELECT SUM(ColumnName)
FROM TableName;
COUNT()
Returns the number of rows present in the table either based on some condition or without any condition.
Syntax:
1
2
3
SELECT COUNT(ColumnName)
FROM TableName
WHERE Condition;
Example:
Example:
Write a query to count the number of students scoring marks > 75 from the Students table.
1 SELECT COUNT(StudentID)
2
3
FROM Students
WHERE Marks >75;
Output:
1 2
AVG()
This function is used to return the average value of a numeric column.
Syntax:
1
2
SELECT AVG(ColumnName)
FROM TableName;
Example:
Write a query to calculate the average marks of all students from the Students table.
1
2
SELECT AVG(Marks)
FROM Students;
Output:
1 71.8
MIN()
Used to return the minimum value of a numeric column.
Syntax:
1
2
SELECT MIN(ColumnName)
FROM TableName;
Example:
Write a query to retrieve the minimum marks out of all students from the Students table.
1
2
SELECT MIN(Marks)
FROM Students;
Output:
1
MAX()
Returns the maximum value of a numeric column.
Syntax:
1
2
SELECT MAX(ColumnName)
FROM TableName;
Example:
Write a query to retrieve the maximum marks out of all students from the Students table.
1
2
SELECT MAX(Marks)
FROM Students;
Output:
1
FIRST()
This function returns the first value of the column which you choose.
Syntax:
1
2
SELECT FIRST(ColumnName)
FROM TableName;
Example:
Write a query to retrieve the marks of the first student.
1
2
SELECT FIRST(Marks)
FROM Students;
Output:
1
LAST()
Used to return the last value of the column which you choose.
Syntax:
1
2
SELECT LAST(ColumnName)
FROM TableName;
Example:
Write a query to retrieve the marks of the last student.
1
2
SELECT LAST(Marks)
FROM Students;
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.
LCASE()
Used to convert values of a string column to lowercase characters.
Syntax:
1
2
SELECT LCASE(ColumnName)
FROM TableName;
Example:
Write a query to retrieve the names of all students in lowercase.
1
2
SELECT LCASE(StudentName)
FROM Students;
UCASE()
Used to convert values of a string column to uppercase characters.
Syntax:
1
2
SELECT UCASE(ColumnName)
FROM TableName;
Example:
Write a query to retrieve the names of all students in lowercase.
1
2
SELECT UCASE(StudentName)
FROM Students;
Output:
1
2
3
4
5
SANJAY
VARUN
AKASH
ROHIT
ANJALI
LEN()
Used to retrieve the length of the input string.
Syntax:
1 SELECT LENGTH(String) AS SampleColumn;
Example:
Write a query to extract the length of the student name “Sanjay”.
1 SELECT LENGTH(“Sanjay”) AS StudentNameLen;
Output:
1 6
MID()
This function is used to extract substrings from columns having string data type.
Syntax:
1
2
SELECT MID(ColumnName, Start, Length)
FROM TableName;
Example:
Write a query to extract substrings from the StudentName column.
1
2
SELECT MID(StudentName, 2, 3)
FROM Students;
Output:
1
2
anj
aru
3
4
5
kas
ohi
nja
ROUND()
This function is used to round off a numeric value to the nearest integer.
Syntax:
1
2
SELECT ROUND(ColumnName, Decimals)
FROM TableName;
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
2
SELECT ROUND(Marks)
FROM Students;
Output:
1
2
3
4
5
91
80
54
73
68
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:
1 SELECT NOW();
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.
Stored Procedure Syntax
CREATE PROCEDURE procedure_name
AS
sql_statement
GO;
Execute a Stored Procedure
EXEC procedure_name;
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.
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.

More Related Content

PPTX
Entity Relationship Modelling
PPTX
PPTX
PPTX
E_R-Diagram (2).pptx
PPTX
Data Models and Relational Database Design.pptx
PPTX
Basic building entity relationship model
DOCX
ER Diagram_Kameshwari.docx
PPTX
E - R Models.pptx SQL and plsql database
Entity Relationship Modelling
E_R-Diagram (2).pptx
Data Models and Relational Database Design.pptx
Basic building entity relationship model
ER Diagram_Kameshwari.docx
E - R Models.pptx SQL and plsql database

Similar to dbms mannual.pdf (20)

PDF
ER diagram is created based on three principal components: entities, attribut...
PPTX
Entity Relationship Diagram – ER Diagram in DBMS.pptx
PPTX
Use analyzed requirements in the design of database.pptx
PPTX
Administrator of Online Examination has multiple features such as Add, Delete...
PPT
Data Modeling Er
PPTX
DBMS Unit-2_Final.pptx
PPTX
Chapter 4_ERD- introduction to entity relationship diagram.pptx
PPTX
Entity Relationship Diagram – ER Diagram in DBMS.pptx
PDF
Advantages and disadvantages of er model in DBMS. Types of database models ..
PPTX
ER Diagram- Cardinality.pptx
PPTX
Er model
PDF
Lecture one db
PPTX
Unit-1-DBMS-SUN-4 everything you need to know.pptx
PPTX
5e7ry754.pptx
PPTX
42_16SCCCS4_20200520053835884587894.pptx
PPTX
E-R Diagram and their models using datbase
PPTX
Attribites.pptx related important topic of dbms
PDF
Entity Relationship Diagram part9
PPTX
Fundamentals of database system - Data Modeling Using the Entity-Relationshi...
PPT
enrity relationship model and diagram .ppt
ER diagram is created based on three principal components: entities, attribut...
Entity Relationship Diagram – ER Diagram in DBMS.pptx
Use analyzed requirements in the design of database.pptx
Administrator of Online Examination has multiple features such as Add, Delete...
Data Modeling Er
DBMS Unit-2_Final.pptx
Chapter 4_ERD- introduction to entity relationship diagram.pptx
Entity Relationship Diagram – ER Diagram in DBMS.pptx
Advantages and disadvantages of er model in DBMS. Types of database models ..
ER Diagram- Cardinality.pptx
Er model
Lecture one db
Unit-1-DBMS-SUN-4 everything you need to know.pptx
5e7ry754.pptx
42_16SCCCS4_20200520053835884587894.pptx
E-R Diagram and their models using datbase
Attribites.pptx related important topic of dbms
Entity Relationship Diagram part9
Fundamentals of database system - Data Modeling Using the Entity-Relationshi...
enrity relationship model and diagram .ppt
Ad

Recently uploaded (20)

PPTX
01_intro xxxxxxxxxxfffffffffffaaaaaaaaaaafg
PPTX
CYBER SECURITY the Next Warefare Tactics
PPTX
sac 451hinhgsgshssjsjsjheegdggeegegdggddgeg.pptx
PPT
lectureusjsjdhdsjjshdshshddhdhddhhd1.ppt
PDF
Introduction to the R Programming Language
PDF
Optimise Shopper Experiences with a Strong Data Estate.pdf
PPTX
Qualitative Qantitative and Mixed Methods.pptx
PPTX
AI Strategy room jwfjksfksfjsjsjsjsjfsjfsj
PDF
Data Engineering Interview Questions & Answers Cloud Data Stacks (AWS, Azure,...
PPTX
importance of Data-Visualization-in-Data-Science. for mba studnts
PPTX
Database Infoormation System (DBIS).pptx
PPTX
modul_python (1).pptx for professional and student
PPTX
STERILIZATION AND DISINFECTION-1.ppthhhbx
PDF
Data Engineering Interview Questions & Answers Batch Processing (Spark, Hadoo...
PPTX
Topic 5 Presentation 5 Lesson 5 Corporate Fin
PPTX
Microsoft-Fabric-Unifying-Analytics-for-the-Modern-Enterprise Solution.pptx
PPTX
Leprosy and NLEP programme community medicine
PDF
REAL ILLUMINATI AGENT IN KAMPALA UGANDA CALL ON+256765750853/0705037305
PDF
OneRead_20250728_1808.pdfhdhddhshahwhwwjjaaja
PPTX
IBA_Chapter_11_Slides_Final_Accessible.pptx
01_intro xxxxxxxxxxfffffffffffaaaaaaaaaaafg
CYBER SECURITY the Next Warefare Tactics
sac 451hinhgsgshssjsjsjheegdggeegegdggddgeg.pptx
lectureusjsjdhdsjjshdshshddhdhddhhd1.ppt
Introduction to the R Programming Language
Optimise Shopper Experiences with a Strong Data Estate.pdf
Qualitative Qantitative and Mixed Methods.pptx
AI Strategy room jwfjksfksfjsjsjsjsjfsjfsj
Data Engineering Interview Questions & Answers Cloud Data Stacks (AWS, Azure,...
importance of Data-Visualization-in-Data-Science. for mba studnts
Database Infoormation System (DBIS).pptx
modul_python (1).pptx for professional and student
STERILIZATION AND DISINFECTION-1.ppthhhbx
Data Engineering Interview Questions & Answers Batch Processing (Spark, Hadoo...
Topic 5 Presentation 5 Lesson 5 Corporate Fin
Microsoft-Fabric-Unifying-Analytics-for-the-Modern-Enterprise Solution.pptx
Leprosy and NLEP programme community medicine
REAL ILLUMINATI AGENT IN KAMPALA UGANDA CALL ON+256765750853/0705037305
OneRead_20250728_1808.pdfhdhddhshahwhwwjjaaja
IBA_Chapter_11_Slides_Final_Accessible.pptx
Ad

dbms mannual.pdf

  • 1. 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. 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
  • 2.  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 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.
  • 3. 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
  • 4.  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. 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 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 Strong Entity Set Weak Entity Set Strong entity set always has a primary key. It does not have enough attributes to build a primary 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 symbol. It contains a Partial Key which is represented by a dashed underline symbol. The member of a strong entity set is called as dominant entity set. The member of a weak entity set called as a subordinate entity set.
  • 5.  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.
  • 6. 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
  • 7.  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
  • 8.  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. Conclusion: Thus for designing an entity-relationship (er) / extended entity-relationship (eer) model is studied and verified for the application.
  • 9. 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)
  • 10. 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 en ty is involved in the rela onship. Total par cipa on is represented by double lines. Partial participation − Not all en es are involved in the rela onship. Par al par cipa on 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.
  • 11. 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.
  • 12. 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
  • 13. 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.
  • 14. 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.
  • 15. 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.
  • 16. 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.
  • 17. 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.
  • 18. 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. 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.
  • 19. 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.
  • 20. 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.) 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. 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. 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
  • 21. 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.) Example 5.6 USE sample; 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} ,...) 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 USE sample; CREATE TABLE employee (emp_no INTEGER NOT NULL, emp_fname CHAR(20) NOT NULL,
  • 22. 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. 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 USE sample; 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]
  • 23. [[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 USE sample; 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. 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.
  • 24. 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. 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', 'kemp.garner@xxx.com', '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. 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.
  • 25. 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. 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.
  • 26. 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
  • 27.  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.
  • 28. 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. 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 the data manipulations operations on populated database on real world application is done and verified.
  • 29. 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';
  • 30. 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;
  • 31. 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.
  • 32. 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 select more than one column, then the distinct pairs of values are returned SELECT DISTINCT year, species_id FROM surveys; Calculated values 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 Dipodomys merriami, which has a species code of DM. We need to add a WHERE clause to our query:
  • 33. SELECT * FROM surveys WHERE species_id='DM'; We can use more sophisticated conditions by combining tests with AND and OR . For example, suppose we want the data on Dipodomys merriami starting in the year 2000: SELECT * FROM surveys WHERE (year >= 2000) AND (species_id = 'DM'); 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. 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.
  • 34. 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. Conclusion: Thus Implementing Basic and complex SQL queries on real world application.
  • 35. 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. 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 2 3 4 5 Create Trigger Trigger_Name (Before | After) [ Insert | Update | Delete] on [Table_Name] [ for each row | for each column ] [ trigger_body ] Now let me break down this syntax and explain each and every part in detail.  Create 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.  [ 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.
  • 36.  [ 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. 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 2 3 4 5 CREATE TRIGGER sample_trigger before INSERT ON student FOR EACH ROW 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; Now if we execute this query we get the following table. Let’s try to use the first variant i.e, Before Insert 1 2 CREATE TRIGGER calculate before INSERT
  • 37. 3 4 5 ON student FOR EACH ROW 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 2 create table Final_mark( per int ); Now let us use the after insert trigger 1 2 3 4 5 CREATE TRIGGER total_mark after insert ON student FOR EACH ROW 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 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 In this article we will learn about creating , deleting and updating Views. Sample Tables: StudentDetails
  • 38. 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;
  • 39. 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; 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;
  • 40. 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; 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:
  • 41.  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;
  • 42. 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. 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. Conclusion: Thus Triggers and Views on real world application is done and verified.
  • 43. 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. 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 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)
  • 44.  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” 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 import java.io.*; import java.sql.*; class GFG { url, username, password) System.out.println(
  • 45. public static void main(String[] args) throws Exception { String url = "jdbc:mysql://localhost:3306/table_name"; 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( "Connection Established successfully"); Statement st = con.createStatement(); ResultSet rs = 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 // Inserting data using SQL query String sql = "insert into student1 values('" + name + "'," + roll + ",'" + cls + "')";
  • 46. 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"); // 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
  • 47. String cls = k.next(); catch (Exception ex) { // Display message when exceptions occurs System.err.println(ex); } } } Output: Conclusion: Thus database connectivity using JDBC is done and verified.
  • 48. 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. 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_Students INT, Num ber_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_Teachers, Number_Of _Classrooms, EmailID) VALUES(1, "Boys Town Public School", 1000, 80, 12, "btps15@gmail.com"), (2, "Gu ru Govind Singh Public School", 800, 35, 15, "ggps25@gmail.com"), (3, "Delhi Public School", 1200, 30, 10, " dps101@gmail.com"), (4, "Ashoka Universal School", 1110, 40, 40, "aus17@gmail.com"), (5, "Calibers Englis h Medium School", 9000, 31, 50, "cems@gmail.com");
  • 49. 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: ID School_Name Number_Of_Students Number_Of_Teachers Number_Of_Classrooms EmailID 1 Boys Town Public School 1000 80 12 btps15@gmail.com 2 Guru Govind Singh Public School 800 35 15 ggps25@gmail.com 3 Delhi Public School 1200 30 10 dps101@gmail.com 4 Ashoka Universal School 1110 40 40 aus17@gmail.com 5 Calibers English Medium School 9000 31 50 cems@gmail.com 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. Syntax: 1. SAVEPOINT savepoint_name;
  • 50. 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. 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_Students INT, Num ber_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_Teachers, Number_Of _Classrooms, EmailID) VALUES(1, "Boys Town Public School", 1000, 80, 12, "btps15@gmail.com"), (2, "Gu ru Govind Singh Public School", 800, 35, 15, "ggps25@gmail.com"), (3, "Delhi Public School", 1200, 30, 10, " dps101@gmail.com"), (4, "Ashoka Universal School", 1110, 40, 40, "aus17@gmail.com"), (5, "Calibers Englis h Medium School", 9000, 31, 50, "cems@gmail.com"); 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: ID School_Name Number_Of_Students Number_Of_Teachers Number_Of_Classrooms EmailID
  • 51. 1 Boys Town Public School 1000 80 12 btps15@gmail.com 2 Guru Govind Singh Public School 800 35 15 ggps25@gmail.com 3 Delhi Public School 1200 30 10 dps101@gmail.com 4 Ashoka Universal School 1110 40 40 aus17@gmail.com 5 Calibers English Medium School 9000 31 50 cems@gmail.com 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 D School_Na me Number_Of_Stu dents Number_Of_Teac hers Number_Of_Classr ooms EmailID
  • 52. 1 Boys Town Public School 1000 80 12 btps15@gmail.c om 2 Guru Govind Singh Public School 800 35 15 ggps25@gmail. com 3 Delhi Public School 1200 30 10 dps101@gmail. com 4 Ashoka Universal School 1110 40 40 aus17@gmail.c om 5 Calibers English Medium School 9050 31 50 cems@gmail.co m 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; 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 D School_N ame Number_Of_St udents Number_Of_Te achers Number_Of_Clas srooms EmailID 1 Boys Town Public School 1000 80 12 btps15@gmail.c omm
  • 53. 2 Guru Govind Singh Public School 800 35 15 ggps25@gmail. comm 3 Delhi Public School 1200 30 10 dps101@gmail. comm 4 Ashoka Universal School 1110 40 40 aus17@gmail.c omm 5 Calibers English Medium School 9000 31 50 cems@gmail.co m 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.
  • 54. 1. mysql> INSERT INTO customer(Customer_ID, Name, Age, Salary, Salary_BankAccount) VALUES(1, "Arya n Jain", 51, 56000, "SBI"), (2, "Arohi Dixit", 21, 25000, "Axis"), (3, "Vineet Garg", 24, 31000, "ICICI"), (4, "A nuja Sharma", 26, 49000, "HDFC"), (5, "Deepak Kohli", 28, 65000, "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; 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;
  • 55. 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_BankAccoun 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; 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.
  • 56. 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: 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: 1 2 SELECT SUM(ColumnName) FROM TableName; COUNT() Returns the number of rows present in the table either based on some condition or without any condition. Syntax: 1 2 3 SELECT COUNT(ColumnName) FROM TableName WHERE Condition; Example: Example: Write a query to count the number of students scoring marks > 75 from the Students table. 1 SELECT COUNT(StudentID)
  • 57. 2 3 FROM Students WHERE Marks >75; Output: 1 2 AVG() This function is used to return the average value of a numeric column. Syntax: 1 2 SELECT AVG(ColumnName) FROM TableName; Example: Write a query to calculate the average marks of all students from the Students table. 1 2 SELECT AVG(Marks) FROM Students; Output: 1 71.8 MIN() Used to return the minimum value of a numeric column. Syntax: 1 2 SELECT MIN(ColumnName) FROM TableName; Example: Write a query to retrieve the minimum marks out of all students from the Students table. 1 2 SELECT MIN(Marks) FROM Students; Output: 1 MAX() Returns the maximum value of a numeric column. Syntax: 1 2 SELECT MAX(ColumnName) FROM TableName; Example: Write a query to retrieve the maximum marks out of all students from the Students table. 1 2 SELECT MAX(Marks) FROM Students; Output:
  • 58. 1 FIRST() This function returns the first value of the column which you choose. Syntax: 1 2 SELECT FIRST(ColumnName) FROM TableName; Example: Write a query to retrieve the marks of the first student. 1 2 SELECT FIRST(Marks) FROM Students; Output: 1 LAST() Used to return the last value of the column which you choose. Syntax: 1 2 SELECT LAST(ColumnName) FROM TableName; Example: Write a query to retrieve the marks of the last student. 1 2 SELECT LAST(Marks) FROM Students; 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. LCASE() Used to convert values of a string column to lowercase characters. Syntax: 1 2 SELECT LCASE(ColumnName) FROM TableName; Example: Write a query to retrieve the names of all students in lowercase. 1 2 SELECT LCASE(StudentName) FROM Students;
  • 59. UCASE() Used to convert values of a string column to uppercase characters. Syntax: 1 2 SELECT UCASE(ColumnName) FROM TableName; Example: Write a query to retrieve the names of all students in lowercase. 1 2 SELECT UCASE(StudentName) FROM Students; Output: 1 2 3 4 5 SANJAY VARUN AKASH ROHIT ANJALI LEN() Used to retrieve the length of the input string. Syntax: 1 SELECT LENGTH(String) AS SampleColumn; Example: Write a query to extract the length of the student name “Sanjay”. 1 SELECT LENGTH(“Sanjay”) AS StudentNameLen; Output: 1 6 MID() This function is used to extract substrings from columns having string data type. Syntax: 1 2 SELECT MID(ColumnName, Start, Length) FROM TableName; Example: Write a query to extract substrings from the StudentName column. 1 2 SELECT MID(StudentName, 2, 3) FROM Students; Output: 1 2 anj aru
  • 60. 3 4 5 kas ohi nja ROUND() This function is used to round off a numeric value to the nearest integer. Syntax: 1 2 SELECT ROUND(ColumnName, Decimals) FROM TableName; 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 2 SELECT ROUND(Marks) FROM Students; Output: 1 2 3 4 5 91 80 54 73 68 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: 1 SELECT NOW(); Example: Write a query to retrieve the current date and time. SELECT NOW(); Output: NOW()
  • 61. 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. Stored Procedure Syntax CREATE PROCEDURE procedure_name AS sql_statement GO; Execute a Stored Procedure EXEC procedure_name; 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;
  • 62. 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. 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.