SQL_LAB
SQL_LAB
LAB OBJECTIVES:
LAB OUTCOMES:
On Successful Completion, the Student will be able to understand about designing an entity-
relationship (er) / extended entity-relationship (eer) modelin the real world application.
PROCEDURE:
ER Diagram stands for Entity Relationship Diagram, also known as ERD is a diagram that
displays the relationship of entity sets stored in a database. In other words, ER diagrams help to
explain the logical structure of databases. ER diagrams are created based on three basic concepts:
entities, attributes and relationships.
ER Diagrams contain different symbols that use rectangles to represent entities, ovals to define
attributes and diamond shapes to represent relationships.
At first look, an ER diagram looks very similar to the flowchart. However, ER Diagram includes
many specialized symbols, and its meanings make this model unique. The purpose of ER
Diagram is to represent the entity framework infrastructure.
Entity Relationship Diagram Example
What is ER Model?
ER Model stands for Entity Relationship Model is a high-level conceptual data model diagram.
ER model helps to systematically analyze data requirements to produce a well-designed
database. The ER Model represents real-world entities and the relationships between them.
Creating an ER Model in DBMS is considered as a best practice before implementing your
database.
ER Modeling helps you to analyze data requirements systematically to produce a well-designed
database. So, it is considered a best practice to complete ER modeling before implementing your
database.
History of ER models
ER diagrams are visual tools that are helpful to represent the ER model. Peter Chen proposed ER
Diagram in 1971 to create a uniform convention that can be used for relational databases and
networks. He aimed to use an ER model as a conceptual modeling approach.
ER Diagram Symbols
● Entities
● Attributes
● Relationships
ER Diagram Examples
For example, in a University database, we might have entities for Students, Courses, and
Lecturers. Students entity can have attributes like Rollno, Name, and DeptID. They might have
relationships with Courses and Lecturers.
Components of the ER Diagram
WHAT IS ENTITY?
A real-world thing either living or non-living that is easily recognizable and nonrecognizable. It
is anything in the enterprise that is to be represented in our database. It may be a physical thing
or simply a fact about the enterprise or an event that happens in the real world.
An entity can be place, person, object, event or a concept, which stores data in the database. The
characteristics of entities are must have an attribute, and a unique key. Every entity is made up of
some ‘attributes’ which represent that entity.
Examples of entities:
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:
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.
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.
Cardinality
Defines the numerical attributes of the relationship between two entities or entity sets.
● One-to-One Relationships
● One-to-Many Relationships
● May to One Relationships
● Many-to-Many Relationships
1.One-to-one:
One entity from entity set X can be associated with at most one entity of entity set Y and vice
versa.
Example: One student can register for numerous courses. However, all those courses have a
single line back to that one student.
2.One-to-many:
One entity from entity set X can be associated with multiple entities of entity set Y, but an entity
from entity set Y can be associated with at least one entity.
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.
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
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.
Super class shape has sub groups: Triangle, Square and Circle.
Sub classes are the group of entities with some unique attributes.Sub class inherits the properties
and attributes from super class.
Specialization and Generalization
Generalization is a process of generalizing an entity which contains generalized attributes or
properties of generalized entities.
It is a Bottom up process i.e. consider we have 3 sub entities Car, Truck and Motorcycle. Now
these three entities can be generalized into one super class named as Vehicle.
Specialization is a process of identifying subsets of an entity that share some different
characteristic. It is a top down approach in which one entity is broken down into low level entity.
In above example Vehicle entity can be a Car, Truck or Motorcycle.
Category or Union
Relationship of one super or sub class with more than one super class.
Owner is the subset of two super class: Vehicle and House.
Aggregation
Represents relationship between a whole object and its component.
Consider a ternary relationship Works_On between Employee, Branch and Manager. Now the
best way to model this situation is to use aggregation, So, the relationship-set, Works_On is a
higher level entity-set. Such an entity-set is treated in the same manner as any other entity-set. We
can create a binary relationship, Manager, between Works_On and Manager to represent who
manages what tasks.
Conclusion:
Thus for designing an entity-relationship (er) / extended entity-relationship (eer) model is studied
and verified for the application.
EX.2 MAPPING ER/EER TO RELATIONAL SCHEMA MODEL
LAB OBJECTIVES:
To understand about Mapping ER/EER to relational Schema Model on real world applications.
LAB OUTCOMES:
On Successful Completion, the Student will be able to understand about Mapping ER/EER to
relational Schema Model on real world applications.
PROCEDURE:
Entity
An entity is any singular, identifiable and separate object. It refers to individuals, organizations,
systems, bits of data or even distinct system components that are considered significant in and of
themselves. For example, People, Property, Organizations, Agreements and, etc. In the ER
diagram, the entity is represented by a rectangle.
Weak Entity
A weak entity is an entity that depends on the existence of another entity. In more technical terms it can
be defined as an entity that cannot be identified by its own attributes.
Attributes
Attributes are the properties that define the entity type. For example, Roll_No, Name, DOB, Age,
Address, Mobile_No are the attributes that define entity type Student. In the ER diagram,
the attribute is represented by an oval.
Multi-valued Attribute
If an attribute can have more than one value it is called a multi-valued attribute.
Derived Attribute
An attribute-based on another attribute.
Relationships
A relationship is an association that describes the interaction between entities.
Recursive Relationship
If the same entity participates more than once in a relationship it is known as a recursive relationship.
The following are the types of entities, attributes, and relationships.
Cardinality
Cardinality refers to the maximum number of times an instance in one entity can relate to instances of
another entity. There are three types of cardinalities.
one to one (1 to 1)
one to many(1 to N)
many to many (M to N)
Participation
Participation constraint specifies the existence of an entity when it is related to another entity in
a relationship type. There are two types. Partial and Total participation.
Total Participation − Each entity is involved in the relationship. Total participation is represented by
double lines.
Partial participation − Not all entities are involved in the relationship. Partial participation is
represented by single lines.
There are three steps in database development.
Requirements Analysis- Understand the data problem through user interviews, forms, reports,
observation and etc.
Component design stage- Create a data model that is a graphical representation of what will be
finally will be implemented.
Implementation stage- Actual development of the database which leads to database actually being
used in the real environment.
In the above stages after the first stage(Requirements analysis) you have to follow the database design
stages.
1. Conceptual design
2. Logical design
3. Physical design
In the Conceptual design, we identify all entities, we define attributes and their properties and we
define relationships between entities.
In the Logical design, we transform the conceptual design into relational, transform entities as tables,
transform entity attributes into table column, and normalization.
In the Physical design, we specify internal storage structure and paths, assign one or more indexes
and tune indexes.
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.
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.
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.
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.🤩
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.
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.
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.
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
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
CONCLUSION:
Thus the Mapping ER/EER to Relational schema model is done and the relevant application is
verified.
EX.3 CREATING A DATABASE USING DDL AND APPLY INTEGRITY
CONSTRAINTS.
LAB Objectives:
To create a database using DDL and apply integrity constraints for a real world application.
LAB OUTCOMES:
On Successful Completion, the Student will be able to understand about to create a database
using DDL and apply integrity constraints for a real world application.
PROCEDURE:
One of the most important features that a DBMS must provide is a way of maintaining the
integrity of data. The constraints, which are used to check the modification or insertion of data,
are called integrity constraints. The task of maintaining integrity constraints can be handled by
the user in application programs or by the DBMS.
The most important benefits of handling integrity constraints by the DBMS are the following:
● Simple maintenance
Using the DBMS to define integrity constraints increases the reliability of data because there is
no possibility that the integrity constraints can be forgotten by a programmer. (If an integrity
constraint is handled by application programs, all programs concerning the constraint must
include the corresponding code. If the code is omitted in one application program, the
consistency of data is compromised.)
An integrity constraint not handled by the DBMS must be defined in every application program
that uses the data involved in the constraint. In contrast, the same integrity constraint must be
defined only once if it is to be handled by the DBMS. Additionally, application-enforced
constraints are usually more complex to code than are database enforced constraints.
If an integrity constraint is handled by the DBMS, the modification of the structure of the
constraint must be handled only once, in the DBMS. The modification of a structure in
application programs requires the modification of every program that involves the corresponding
code.
● Procedural integrity constraints that are handled by triggers (for the definition of triggers, see
The declarative constraints are defined using the DDL statements CREATE TABLE and ALTER
TABLE. They can be column-level constraints or table-level constraints. Column-level
constraints, together with the data type and other column properties, are placed within the
declaration of the column, while table-level constraints are always defined at the end of the
CREATE TABLE or ALTER TABLE statement, after the definition of all columns.
Note – There is only one difference between column-level constraints and table-level constraints:
a column-level constraint can be applied only upon one column, while a table-level constraint
can cover one or more columns of a table.
Each declarative constraint has a name. The name of the constraint can be explicitly assigned
using the CONSTRAINT option in the CREATE TABLE statement or the ALTER TABLE
statement. If the CONSTRAINT option is omitted, the Database Engine assigns an implicit name
for the constraint.
Note – Using explicit constraint names is strongly recommended. The search for an integrity
constraint can be greatly enhanced if an explicit name for a constraint is used.
All declarative constraints can be categorized into several groups:
● DEFAULT clause
● UNIQUE clause
● CHECK 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.
[CONSTRAINT c_name]
The CONSTRAINT option in the UNIQUE clause assigns an explicit name to the candidate key.
The option CLUSTERED or NONCLUSTERED relates to the fact that the Database Engine
always generates an index for each candidate key of a table. The index can be clustered—that is,
the physical order of rows is specified using the indexed order of the column values. If the order
is not specified, the index is nonclustered (see also Chapter on Indices). The default value is
NONCLUSTERED. col_name1 is a column name that builds the candidate key. (The maximum
number of columns per candidate key is 16.)
Example 5.6 shows the use of the UNIQUE clause. (You have to drop the projects table, via
DROP TABLE projects, before you execute the following example.)
USEsample;3
CREATE TABLE projects (project_no CHAR(4) DEFAULT'p1',
project_name CHAR(15) NOT NULL,
budget FLOAT NULL
CONSTRAINT unique_no UNIQUE (project_no));
Each value of the project_no column of the projects table is unique, including the NULL value.
(Just as with any other value with a UNIQUE constraint, if NULL values are allowed on a
corresponding column, there can be at most one row with the NULL value for that particular
column.) If an existing value should be inserted into the column project_no, the system rejects it.
The explicit name of the constraint that is defined in Example 5.6 is unique_no.
The PRIMARY KEY Clause
The primary key of a table is a column or group of columns whose value is different in every
row. Each primary key is defined using the PRIMARY KEY clause in the CREATE TABLE or
the ALTER TABLE statement.
[CONSTRAINT c_name]
All options of the PRIMARY KEY clause have the same meaning as the corresponding options
with the same name in the UNIQUE clause. In contrast to UNIQUE, the PRIMARY KEY
column must be NOT NULL, and its default value is CLUSTERED.
Example 5.7 shows the specification of the primary key for the employee table of the sample
database.
Note – You have to drop the employee table (DROP TABLE employee) before you execute the
following example.
Example 5.7
USEsample;
CREATE TABLE employee (emp_no INTEGER NOT NULL,
emp_fname CHAR(20) NOT NULL,
emp_lname CHAR(20) NOT NULL,
dept_no CHAR(4) NULL,
CONSTRAINT prim_empl PRIMARY KEY (emp_no));
The employee table is re-created and its primary key is defined in Example 5.7. The primary key
of the table is specified using the declarative integrity constraint named prim_empl. This
integrity constraint is a table-level constraint, because it is specified after the definition of all
columns of the employee table.
Example 5.8 is equivalent to Example 5.7, except for the specification of the primary key of the
employee table as a column-level constraint.
Note – Again, you have to drop the employee table (DROP TABLE employee) before you
execute the following example.
Example 5.8
USEsample;
CREATE TABLE employee
(emp_no INTEGER NOT NULL CONSTRAINT prim_empl PRIMARY KEY,
emp_fname CHAR(20) NOT NULL,
emp_lname CHAR(20) NOT NULL,
dept_no CHAR(4) NULL);
In Example 5.8, the PRIMARY KEY clause belongs to the declaration of the corresponding
column, together with its data type and nullability. For this reason, it is called a column-level
constraint.
The check 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
USEsample;
CREATE TABLE customer
(cust_no INTEGER NOT NULL,
cust_group CHAR(3) NULL,
CHECK (cust_group IN ('c1', 'c2', 'c10')));
Code language:PHP(php)
The customer table that is created in Example 5.9 contains the cust_group column with the
corresponding check constraint. The database system returns an error if the cust_group column,
after a modification of its existing values or after the insertion of a new row, would contain a
value different from the values in the set (‘c1’, ‘c2’, ‘c10’).
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.
[CONSTRAINT c_name]
[[FOREIGN KEY] ({col_name1} ,...)]
REFERENCES table_name ({col_name2},...)
[ON DELETE {NO ACTION| CASCADE | SET NULL | SET DEFAULT}]
[ON UPDATE {NO ACTION | CASCADE | SET NULL | SET
DEFAULT}]
Code language:PHP(php)
The FOREIGN KEY clause defines all columns explicitly that belong to the foreign key. The
REFERENCES clause specifies the table name with all columns that build the corresponding
primary key. The number and the data types of the columns in the FOREIGN KEY clause must
match the number and the corresponding data types of columns in the REFERENCES clause
(and, of course, both of these must match the number and data types of the columns in the
primary key of the referenced table).
The table that contains the foreign key is called the referencing table, and the table that contains
the corresponding primary key is called the parent table or referenced table. Example 5.10 shows
the specification of the foreign key in the works_on table of the sample database.
Note – You have to drop the works_on table before you execute the following example.
Example 5.10
USEsample;
CREATE TABLE works_on
(emp_no INTEGER NOT NULL,
project_no CHAR(4) NOT NULL,
job CHAR (15) NULL,
enter_date DATE NULL,
CONSTRAINT prim_works PRIMARY KEY(emp_no, project_no),
CONSTRAINT foreign_works FOREIGN KEY(emp_no)
REFERENCES employee (emp_no));
Code language:PHP(php)
The works_on table in Example 5.10 is specified with two declarative integrity constraints:
prim_works and foreign_works. Both constraints are table-level constraints, where the former
specifies the primary key and the latter the foreign key of the works_on table. Further, the
constraint foreign_works specifies the employee table as the parent table and its emp_no column
as the corresponding primary key of the column with the same name in the works_on table.
The FOREIGN KEY clause can be omitted if the foreign key is defined as a column-level
constraint, because the column being constrained is the implicit column “list” of the foreign key,
and the keyword REFERENCES is sufficient to indicate what kind of constraint this is. The
maximum number of FOREIGN KEY constraints in a table is 63.
A definition of the foreign keys in tables of a database imposes the specification of another
important integrity constraint: the referential integrity, described next.
CONCLUSION:
Thus Create a database using DDL and apply integrity constraints is done and verified.
EX.4 PERFORMING DATA MANIPULATIONS OPERATIONS ON POPULATED
DATABASE
LAB OBJECTIVES:
To understand about the to perform data manipulations operations on populated database on real
world application.
LAB OUTCOMES:
On Successful Completion, the Student will be able to understand about data manipulations
operations on populated database on real world application.
PROCEDURE:
Oracle provide Data Manipulation Language commands to exercise data operations in the
database.Data operations can be populating the database tables with the application or business
data,modifying the data and removing the data from the database,whenever required. Besides the
data operations,there are set of commands which are used to control these operations.These
commands are grouped as Transaction Control Language.
There are three types of DML statements involved in a logical SQL transaction namely, Insert,
Update, Delete and Merge.A transaction is the logical collection of DML actions within a database
session.
INSERT statement
The INSERT command is used to store data in tables. The INSERT command is often used in
higher-level programming languages such as Visual Basic.NET or C++ as an embedded SQL
command; however,this command can also be executed at the SQL*PLUS prompt in command
mode.There are two different forms of the INSERT command. The first form is used if a new row
will have a value inserted into each column of the row. The second form of the INSERT command
is used to insert rows where some of the column data is unknown or defaulted from another
business logic.This form of the INSERT command requires that you specify column names for
which data are being stored.
Syntax:
The below syntax can be followed if the values for all the columns in the table is definite and
known.
INSERT INTO table
VALUES (column1 value, column2 value,
...);
The below syntax can be used if only few columns from the table have to be populated with a
value. Rest of the columns can deduce their values either as NULL or from a different business
logic.
INSERT INTO table (column1 name, column2 name,...)
VALUES (column1 value, column2 value,...);
The INSERT statement below creates a new employee record in the EMPLOYEES table. Note
that it inserts the values for the primary columns EMPLOYEE_ID, FIRST_NAME, SALARY and
DEPARTMENT_ID.
INSERT INTO employees (EMPLOYEE_ID, FIRST_NAME, SALARY, DEPARTMENT_ID)
VALUES (130,'KEMP',3800,10);
Otherwise, complete employee data can be inserted in the EMPLOYEES table without specifying
the column list using the below INSERT statement - provided the values are known beforehand
and must be in compliance with the data type and position of columns in the table.
INSERT INTO employees
VALUES (130,'KEMP','GARNER','[email protected]','48309290',TO_DATE ('01-JAN-
2012'),'SALES',3800,0,110,10);
Values to be inserted must be compatible with the data type of the column. Literals, fixed values
and special values like functions, SYSDATE, CURRENT_DATE, SEQ.CURRVAL
(NEXTVAL), or USER can be used as column values. Values specified must follow the generic
rules. String literals and date values must be enclosed within quotes. Date value can be supplied
in DD-MON-RR or D-MON-YYYY format, but YYYY is preferred since it clearly specifies the
century and does not depend on internal RR century calculation logic.
INSERT-AS-SELECT (IAS) statement
Data can be populated into the target table from the source table using INSERT..AS..SELECT
(IAS) operation. Its a direct path read operation.Its a simple way of creating copy of the data from
one table to another or creating a backup copy of the table which the source table operations are
online.
For example, data can be copied from EMPLOYEES table to EMP_HISTORY table.
INSERT INTO EMP_HISTORY
SELECT EMPLOYEE_ID, EMPLOYEE_NAME, SALARY, DEPARTMENT_ID
FROM employees;
UPDATE statement
The UPDATE command modifies the data stored in a column.It can update single or multiple rows
at a time depending on the result set filtered by conditions specified in WHERE clause. Note that
Updating columns is different from altering columns. Earlier in this chapter, you studied the
ALTER command.The ALTER command changes the table structure, but leaves the table data
unaffected.The UPDATE command changes data in the table, not the table structure.
Syntax:
UPDATE table
SET column =value[, column =value...]
[WHERE condition]
From the syntax,
The SET column = expression can be any combination of characters, formulas, or functions that
will update data in the specified column name.The WHERE clause is optional, but if it is included,
it specifies which rows will be updated.Only one table can be updated at a time with an UPDATE
command.
The UPDATE statement below updates the salary of employee JOHN to 5000.
UPDATE employees
SET salary =5000
WHERE UPPER (first_name)='JOHN';
Though WHERE predicates are optional, but must be logically appended so as to modify only the
required row in the table. The UPDATE statement below updates the salaries of all the employees
in the table.
UPDATE employees
SET salary =5000;
Multiple columns can also be updated by specifying multiple columns in SET clause separated by
a comma. For example, if both salary and job role has to be changed to 5000 and SALES
respectively for JOHN, the UPDATE statement looks like,
UPDATE employees
SET SALARY =5000,
JOB_ID ='SALES'
WHERE UPPER (first_name)='JOHN';
1 row updated.
Another way of updating multiple columns of the same row shows the usage of subquery.
UPDATE employees
SET (SALARY, JOB_ID)=(SELECT 5000,'SALES' FROM DUAL)
WHERE UPPER (ENAME)='JOHN'
DELETE statement
The DELETE command is one of the simplest of the SQL statements. It removes one or more rows
from a table. Multiple table delete operations are not allowed in SQL.The syntax of the DELETE
command is as below.
DELETE FROM table_name
[WHERE condition];
The DELETE command deletes all rows in the table that satisfy the condition in the optional
WHERE clause. Since the WHERE clause is optional, one can easily delete all rows from a table
by omitting a WHERE clause since the WHERE clause limits the scope of the DELETE operation.
The below DELETE statement would remove EDWIN's details from EMP table.
DELETE employees
WHERE UPPER (ENAME)='EDWIN'
1 row deleted.
Note: DELETE [TABLE NAME] and DELETE FROM [TABLE NAME] hold the same meaning.
The WHERE condition in the conditional delete statements can make use of subquery as shown
below.
DELETE FROM employees
WHERE DEPARTMENT_ID IN (SELECT DEPARTMENT_ID
FROM LOCATIONS
WHERE LOCATION_CODE ='SFO')
TRUNCATE
Truncate is a DDL command which is used to flush out all records from a table but retaining the
table structure. It does not supports WHERE condition to remove the selected records.
Syntax:
TRUNCATE [table name]
It is Auto Commit i.e. it commits the current active transaction in the session. Truncating the table
does not drops dependent indexes, triggers or table constraints. If a table A is parent of a reference
constraint of a table B in the database, the table A could not be truncated.
Transaction
A transaction is a logical unit of work done in database. It can either contain -
● Multiple DML commands ending with a TCL command i.e. COMMIT or ROLLBACK
● One DDL command
● One DCL command
Beginning of a transaction is marked with the first DML command. It ends with a TCL, DDL or
DCL command. A TCL command i.e. COMMIT or ROLLBACK is issues explicitly to end an
active transaction. By virtue of their basic behavior, if any of DDL or DCL commands get executed
in a database session, commit the ongoing active transaction in the session. If the database instance
crashes abnormally, the transaction is stopped.
COMMIT, ROLLBACK and SAVEPOINT are the transaction control language. COMMIT
applies the data changes permanently into the database while ROLLBACK does anti-commit
operation. SAVEPOINT controls the series of a transaction by setting markers at different
transaction stages. User can roll back the current transaction to the desired save point, which was
set earlier.
COMMIT - Commit ends the current active transaction by applying the data changes permanently
into the database tables. COMMIT is a TCL command which explicitly ends the transaction.
However, the DDL and DCL command implicitly commit the transaction.
SAVEPOINT - Savepoint is used to mark a specific point in the current transaction in the session.
Since it is logical marker in the transaction, savepoints cannot be queried in the data dictionaries.
ROLLBACK - The ROLLBACK command is used to end the entire transaction by discarding the
data changes. If the transaction contains marked savepoints, ROLLBACK TO SAVEPOINT
[name] can be used to rollback the transaction upto the specified savepoint only. As a result, all
the data changes upto the specified savepoint will be discarded.
Demonstration
Consider the EMPLOYEES table which gets populated with newly hired employee details during
first quarter of every year. The clerical staff appends each employee detail with a savepoint, so as
to rollback any faulty data at any moment during the data feeding activity. Note that he keeps the
savepoint names same as the employee names.
INSERT INTO employees (employee_id,first_name,hire_date,job_id, salary,department_id)
VALUES (105,'Allen',TO_DATE('15-JAN-2013','SALES',10000,10);
SAVEPOINT Allen;
SAVEPOINT Kate;
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;
SAVEPOINT Kate;
SAVEPOINT McMan;
Once he is done with the data entry, he can commit the entire transaction by issuing COMMIT in
the current session.
Read Consistency
Oracle maintains consistency among the users in each session in terms of data access and
read/write actions.
When a DML occurs on a table, the original data values changed by the action are recorded in the
database undo records. As long as transaction is not committed into database, any user in other
session that later queries the modified data views the original data values. Oracle uses current
information in the system global area and information in the undo records to construct a read-
consistent view of a table's data for a query. Only when a transaction is committed, the changes of
the transaction made permanent. The transaction is the key to Oracle's strategy for providing read
consistency.
Start point for read-consistent views is generated on behalf of readers
Controls when modified data can be seen by other transactions of the database for reading or
updating
CONCLUSION:
Thus thedata manipulations operations on populated database on real world application is done
and verified.
EX.5 PERFORMING AUTHORIZATION USING GRANT AND REVOKE
LAB OBJECTIVES:
LAB OUTCOMES:
On Successful Completion, the Student will be able to understand about Performing Authorization
using Grant and Revoke on real world application.
PROCEDURE:
We have already learned about how to create users in MySQL using MySQL | create user
statement. But using the Create User Statement only creates a new user but does not grant any
privileges to the user account. Therefore to grant privileges to a user account, the GRANT
statement is used. Syntax:
GRANT privileges_names ON object TO user;
Parameters Used:
● privileges_name: These are the access rights or privileges granted to the user.
● object:It is the name of the database object to which permissions are being granted. In the
case of granting privileges on a table, this would be the table name.
● user:It is the name of the user to whom the privileges would be granted.
Privileges: The privileges that can be granted to the users are listed below along with the
description:
Let us now learn about different ways of granting privileges to the users:
1. Granting SELECT Privilege to a User in a Table: To grant Select Privilege to a table
named “users” where User Name is Amit, the following GRANT statement should be
executed.
GRANT SELECT ON Users TO'Amit'@'localhost;
1. Granting more than one Privilege to a User in a Table: To grant multiple Privileges to a
user named “Amit” in a table “users”, the following GRANT statement should be executed.
GRANT SELECT, INSERT, DELETE, UPDATE ON Users TO 'Amit'@'localhost;
1. Granting All the Privilege to a User in a Table: To Grant all the privileges to a user
named “Amit” in a table “users”, the following Grant statement should be executed.
GRANT ALL ON Users TO 'Amit'@'localhost;
1. Granting a Privilege to all Users in a Table: To Grant a specific privilege to all the users
in a table “users”, the following Grant statement should be executed.
GRANT SELECT ON Users TO '*'@'localhost;
1. In the above example the “*” symbol is used to grant select permission to all the users of the
table “users”.
2. Granting Privileges on Functions/Procedures: While using functions and procedures, the
Grant statement can be used to grant users the ability to execute the functions and
procedures in MySQL. Granting Execute Privilege: Execute privilege gives the ability to
execute a function or procedure. Syntax:
GRANT EXECUTE ON [ PROCEDURE | FUNCTION ] object TO user;
Different ways of granting EXECUTE Privileges:
Granting EXECUTE privileges on a function in MySQL.: If there is a function named
“CalculateSalary” and you want to grant EXECUTE access to the user named Amit, then the
following GRANT statement should be executed.
GRANT EXECUTE ON FUNCTION Calculatesalary TO 'Amit'@localhost';
Granting EXECUTE privileges to all Users on a function in MySQL.: If there is a function
named “CalculateSalary” and you want to grant EXECUTE access to all the users, then the
following GRANT statement should be executed.
GRANT EXECUTE ON FUNCTION Calculatesalary TO '*'@localhost';
Granting EXECUTE privilege to a Users on a procedure in MySQL.: If there is a procedure
named “DBMSProcedure” and you want to grant EXECUTE access to the user named Amit,
then the following GRANT statement should be executed.
GRANT EXECUTE ON PROCEDURE DBMSProcedure TO 'Amit'@localhost';
Granting EXECUTE privileges to all Users on a procedure in MySQL.: If there is a
procedure called “DBMSProcedure” and you want to grant EXECUTE access to all the users,
then the following GRANT statement should be executed.
GRANT EXECUTE ON PROCEDURE DBMSProcedure TO '*'@localhost';
Checking the Privileges Granted to a User: To see the privileges granted to a user in a table,
the SHOW GRANTS statement is used. To check the privileges granted to a user named “Amit”
and host as “localhost”, the following SHOW GRANTS statement will be executed:
SHOW GRANTS FOR 'Amit'@localhost';
Output:
GRANTS FOR Amit@localhost
GRANT USAGE ON *.* TO `SUPER`@localhost`
Revoking Privileges from a Table
The Revoke statement is used to revoke some or all of the privileges which have been granted to
a user in the past. Syntax:
REVOKE privileges ON object FROM user;
Parameters Used:
● object: It is the name of the database object from which permissions are being revoked. In
the case of revoking privileges from a table, this would be the table name.
● user: It is the name of the user from whom the privileges are being revoked.
Privileges can be of the following
values:
CONCLUSION:
Thus the Performing Authorization using Grant and Revoke is done and verified.
EX.6 IMPLEMENTING BASIC AND COMPLEX SQL QUERIES
LAB OBJECTIVES:
To understand about Implementing Basic and complex SQL queries on real world application.
LAB OUTCOMES:
On Successful Completion, the Student will be able to understand about Implementing Basic and
complex SQL queries on real world application.
PROCEDURE:
Let’s start by using the surveys table. Here we have data on every individual that was captured at
the site, including when they were captured, what plot they were captured on, their species ID,
sex and weight in grams.
Let’s write an SQL query that selects only the year column from the surveys table. SQL queries
can be written in the box located under the “Execute SQL” tab. Click ‘Run SQL’ to execute the
query in the box.
SELECT year
FROM surveys;
We have capitalized the words SELECT and FROM because they are SQL keywords. SQL is
case insensitive, but it helps for readability, and is good style.
If we want more information, we can just add a new column to the list of fields, right
after SELECT:
SELECT year, month, day
FROM surveys;
Or we can select all of the columns in a table using the wildcard *
SELECT *
FROM surveys;
Unique values
If we want only the unique values so that we can quickly see what species have been sampled we
use DISTINCT
SELECT DISTINCT species_id
FROM surveys;
If we select more than one column, then the distinct pairs of values are returned
SELECT DISTINCT year, species_id
FROM surveys;
Calculated values
We can also do calculations with the values in a query. For example, if we wanted to look at the
mass of each individual on different dates, but we needed it in kg instead of g we would use
SELECT year, month, day, weight/1000.0
FROM surveys;
When we run the query, the expression weight / 1000.0 is evaluated for each row and appended
to that row, in a new column. Expressions can use any fields, any arithmetic operators (+, -, *,
and /) and a variety of built-in functions. For example, we could round the values to make them
easier to read.
SELECT plot_id, species_id, sex, weight, ROUND(weight / 1000.0, 2)
FROM surveys;
Challenge
Write a query that returns the year, month, day, species_id and weight in mg
SOLUTION
SELECT day, month, year, species_id, weight * 1000
FROM surveys;
Filtering
Databases can also filter data – selecting only the data meeting certain criteria. For example, let’s
say we only want data for the species Dipodomysmerriami, which has a species code of DM. We
need to add a WHERE clause to our query:
SELECT *
FROM surveys
WHERE species_id='DM';
We can do the same thing with numbers. Here, we only want the data since 2000:
SELECT * FROM surveys
WHERE year >= 2000;
We can use more sophisticated conditions by combining tests with AND and OR. For example,
suppose we want the data on Dipodomysmerriami starting in the year 2000:
SELECT *
FROM surveys
WHERE (year >= 2000) AND (species_id = 'DM');
Note that the parentheses are not needed, but again, they help with readability. They also ensure
that the computer combines AND and OR in the way that we intend.
If we wanted to get data for any of the Dipodomys species, which have species codes DM, DO,
and DS, we could combine the tests using OR:
SELECT *
FROM surveys
WHERE (species_id = 'DM') OR (species_id = 'DO') OR (species_id = 'DS');
Challenge
Write a query that returns the day, month, year, species_id, and weight (in kg) for individuals
caught on Plot 1 that weigh more than 75 g
SOLUTION
SELECT day, month, year, species_id, weight / 1000.0
FROM surveys
WHERE plot_id = 1
AND weight > 75;
Now, lets combine the above queries to get data for the 3 Dipodomys species from the year 2000
on. This time, let’s use IN as one way to make the query easier to understand. It is equivalent to
saying WHERE (species_id = 'DM') OR (species_id = 'DO') OR (species_id = 'DS'), but reads
more neatly:
SELECT *
FROM surveys
WHERE (year >= 2000) AND (species_id IN ('DM', 'DO', 'DS'));
We started with something simple, then added more clauses one by one, testing their effects as
we went along. For complex queries, this is a good strategy, to make sure you are getting what
you want. Sometimes it might help to take a subset of the data that you can easily see in a
temporary database to practice your queries on before working on a larger or more complicated
database.
When the queries become more complex, it can be useful to add comments. In SQL, comments
are started by --, and end at the end of the line. For example, a commented version of the above
query can be written as:
-- Get post 2000 data on Dipodomys' species
-- These are in the surveys table, and we are interested in all columns
SELECT * FROM surveys
-- Sampling year is in the column `year`, and we want to include 2000
WHERE (year >= 2000)
-- Dipodomys' species have the `species_id` DM, DO, and DS
AND (species_id IN ('DM', 'DO', 'DS'));
Although SQL queries often read like plain English, it is always useful to add comments; this is
especially true of more complex queries.
Sorting
We can also sort the results of our queries by using ORDER BY. For simplicity, let’s go back to
the species table and alphabetize it by taxa.
First, let’s look at what’s in the species table. It’s a table of the species_id and the full genus,
species and taxa information for each species_id. Having this in a separate table is nice, because
we didn’t need to include all this information in our main surveys table.
SELECT *
FROM species;
Now let’s order it by taxa.
SELECT *
FROM species
ORDER BY taxa ASC;
The keyword ASC tells us to order it in Ascending order. We could alternately use DESC to get
descending order.
SELECT *
FROM species
ORDER BY taxa DESC;
ASC is the default.
We can also sort on several fields at once. To truly be alphabetical, we might want to order by
genus then species.
SELECT *
FROM species
ORDER BY genus ASC, species ASC;
Challenge
Write a query that returns year, species_id, and weight in kg from the surveys table, sorted with
the largest weights at the top.
SOLUTION
SELECT year, species_id, weight / 1000.0
FROM surveys ORDER BY weight DESC;
Order of execution
Another note for ordering. We don’t actually have to display a column to sort by it. For
example, let’s say we want to order the birds by their species ID, but we only want to see genus
and species.
SELECT genus, species
FROM species
WHERE taxa = 'Bird'
ORDER BY species_id ASC;
We can do this because sorting occurs earlier in the computational pipeline than field
selection.
The computer is basically doing this:
Clauses are written in a fixed order: SELECT, FROM, WHERE, then ORDER BY. It is possible
to write a query as a single line, but for readability, we recommend to put each clause on its own
line.
Challenge
Let’s try to combine what we’ve learned so far in a single query. Using the surveys table write a
query to display the three date fields, species_id, and weight in kilograms (rounded to two
decimal places), for individuals captured in 1999, ordered alphabetically by the species_id. Write
the query as a single line, then put each clause on its own line, and see how more legible the
query becomes!
SOLUTION
SELECT year, month, day, species_id, ROUND(weight / 1000.0, 2)
FROM surveys
WHERE year = 1999
ORDER BY species_id;
Conclusion:
Thus Implementing Basic and complex SQL queries on real world application.
EX.7 IMPLEMENTATION OF VIEWS AND TRIGGERS
LAB OBJECTIVES:
LAB OUTCOMES:
On Successful Completion, the Student will be able to understand about the Implementation of
Views and Triggers.
PROCEDURE:
A trigger in SQL is a procedural code that is automatically executed in response to certain events
on a specified table. It is important to understand how these small codes make such a huge
difference in database performance. In this article, you will learn how to implement triggers along
with examples.
● What is a Trigger?
● Syntax and Example
● Operation in Triggers
● Advantage and Disadvantage
What is a Trigger?
Triggers are the SQL codes that are automatically executed in response to certain events on a
particular table. These are used to maintain the integrity of the data. A trigger in SQL works similar
to a real-world trigger. For example, when the gun trigger is pulled a bullet is fired. We all know
this, but how this is related to Triggers in SQL? To understand this let’s consider a hypothetical
situation.
John is the marketing officer in a company. When a new customer data is entered into the
company’s database he has to send the welcome message to each new customer. If it is one or two
customers John can do it manually, but what if the count is more than a thousand? Well in such
scenario triggers come in handy.
Thus, now John can easily create a trigger which will automatically send a welcome email to the
new customers once their data is entered into the database. So I hope you are clear with the
introduction of Triggers in SQL.
Always remember that there cannot be two triggers with similar action time and event for one
table. For example, we cannot have two BEFORE UPDATE triggers for a table. But we can have
a BEFORE UPDATE and a BEFORE INSERT trigger, or a BEFORE UPDATE and an AFTER
UPDATE trigger.
Before we dive further into the fundamentals of triggers I would suggest you to understand the
concepts of SQL Basics and Normalization so that you get a better grip on Triggers in SQL.
3 on [Table_Name]
5 [ trigger_body ]
Now let me break down this syntax and explain each and every part in detail.
● Create Trigger
These two keywords are used to specify that a trigger block is going to be declared.
● Trigger_Name
It specifies the name of the trigger. Trigger name has to be unique and shouldn’t repeat.
● ( Before | After )
This specifies when the trigger will be executed. It tells us the time at which the trigger is
initiated, i.e, either before the ongoing event or after.
● Before Triggers are used to update or validate record values before they’re saved to the
database.
● After Triggers are used to access field values that are set by the system and to effect
changes in other records. The records that activate the after trigger are read-only. We
cannot use After trigger if we want to update a record because it will lead to read-only
error.
● [ Insert | Update | Delete ]
These are the DML operations and we can use either of them in a given trigger.
● on [ Table_Name ]
We need to mention the table name on which the trigger is being applied. Don’t forget to
use on keyword and also make sure the selected table is present in the database.
● [ for each row | for each column ]
1.
1. Row-level trigger gets executed before or after any column value of a row changes
2. Column Level Trigger gets executed before or after the specified column changes
● [ trigger_body]
It consists of queries that need to be executed when the trigger is called.
So this was all about a simple trigger. But we can also create a nested trigger that can do multi-
process. Also handling it and terminating it at the right time is very important. If we don’t end the
trigger properly it may lead to an infinite loop.
You might be wondering in which scenario we can use the nested trigger. Rather than giving you
a tailored answer let me share a scenario with you, which will help you in understanding the nested
trigger in a better way. Continuing from the earlier scenario, John sent an email for every new
customer that was added to the company’s database. Now, what if he wishes to keep track of the
number of customers to whom the email was sent? Now John needs to create a nested trigger to
keep the track of the count along with sending an email.
So that was all about the syntax of triggers, lets now try to implement an example of triggers in
SQL.
2 before INSERT
3 ON student
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
● Display A Trigger
The below code will display all the triggers that are present.
1 SHOW TRIGGERS;
The below code will display all the triggers that are present in a particular database.
1 SHOW TRIGGERS
2 IN database_name;
Example:
In the above example, all the triggers that are present in the database named Edureka will be
displayed.
We also look at some major variants of the triggers that is Before insert and After insert. We have
already seen a trigger in the example. But with the help of the table lets see how exactly this works.
As we have already understood how to create a trigger, now let’s understand the two variants of
the trigger those are Before insert and After insert. in order to implement them, let’s create a
student table with various columns as shown below:
3 FName VARCHAR(20),
4 LName VARCHAR(20),
5 Address VARCHAR(30),
6 City VARCHAR(15),
7 Marks INT,
8 PRIMARY KEY(studentID)
9 );
2 before INSERT
3 ON student
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.
2 per int );
2 after insert
3 ON student
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.
● Forcing security approvals on the table that are present in the database
● Triggers provide another way to check the integrity of data
● Counteracting invalid exchanges
● Triggers handle errors from the database layer
● Normally triggers can be useful for inspecting the data changes in tables
● Triggers give an alternative way to run scheduled tasks. Using triggers, we don’t have to
wait for the scheduled events to run because the triggers are invoked automatically before
or after a change is made to the data in a table
Disadvantages
● Triggers can only provide extended validations, i.e, not all kind validations. For simple
validations, you can use the NOT NULL, UNIQUE, CHECK and FOREIGN KEY
constraints
● Triggers may increase the overhead of the database
● Triggers can be difficult to troubleshoot because they execute automatically in the
database, which may not invisible to the client applications
This brings us to the end of this Triggers in SQL article. I hope you understood the concepts of
Triggers.
If you wish to learn more about MySQL and get to know this open-source relational database, then
check out our MySQL DBA Certification Training which comes with instructor-led live training
and real-life project experience. This training will help you understand MySQL in-depth and help
you achieve mastery over the subject.
Views in SQL are kind of virtual tables. A view also has rows and columns as they are in a real
table in the database. We can create a view by selecting fields from one or more tables present in
the database. A View can either have all the rows of a table or specific rows based on certain
condition.
In this article we will learn about creating , deleting and updating Views.
Sample Tables:
StudentDetails
StudentMarks
CREATING VIEWS
We can create View using CREATE VIEW statement. A View can be created from a single
table or multiple tables.
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE condition;
● In this example, we will create a view named StudentNames from the table
StudentDetails.
Query:
● CREATE VIEW StudentNames AS
● 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
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;
● SELECT column1,coulmn2,..
● FROM table_name
● WHERE condition;
For example, if we want to update the view MarksView and add the field AGE to this View
from StudentMarks Table, we can do this as:
CREATE OR REPLACE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS,
StudentMarks.AGE
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
If we fetch all the data from MarksView now as:
SELECT * FROM MarksView;
Output:
● WHERE condition;
●
Conclusion:
Thus Triggers and Views on real world application is done and verified.
EX.8 TCL COMMANDS IN SQL
LAB OBJECTIVES:
LAB OUTCOMES:
On Successful Completion, the Student will be able to understand about TCL Commands on real
world application.
PROCEDURE:
Now let us take a deeper dive into the TCL commands of SQL with the help of examples. All the
queries in the examples will be written using the MySQL database.
1. COMMIT
COMMIT command in SQL is used to save all the transaction-related changes permanently to the
disk. Whenever DDL commands such as INSERT, UPDATE and DELETE are used, the changes
made by these commands are permanent only after closing the current session. So before closing
the session, one can easily roll back the changes made by the DDL commands. Hence, if we want
the changes to be saved permanently to the disk without closing the session, we will use the commit
command.
Syntax:
1. COMMIT;
Example:
Now, we will execute the following query to insert multiple records at the same time in the t_school
table.
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.
MySQL, by default, commits every query the user executes. But if the user wishes to commit only
the specific queries instead of committing every query, then turning off the autocommit is useful.
2. SAVEPOINT
We can divide the database operations into parts. For example, we can consider all the insert related
queries that we will execute consecutively as one part of the transaction and the delete command
as the other part of the transaction. Using the SAVEPOINT command in SQL, we can save these
different parts of the same transaction using different names. For example, we can save all the
insert related queries with the savepoint named INS. To save all the insert related queries in one
savepoint, we have to execute the SAVEPOINT query followed by the savepoint name after
finishing the insert command execution.
Syntax:
1. SAVEPOINT savepoint_name;
3. ROLLBACK
While carrying a transaction, we must create savepoints to save different parts of the transaction.
According to the user's changing requirements, he/she can roll back the transaction to different
savepoints. Consider a scenario: We have initiated a transaction followed by the table creation
and record insertion into the table. After inserting records, we have created a savepoint INS. Then
we executed a delete query, but later we thought that mistakenly we had removed the useful record.
Therefore in such situations, we have an option of rolling back our transaction. In this case, we
have to roll back our transaction using the ROLLBACK command to the savepoint INS, which we
have created before executing the DELETE query.
Syntax:
1. ROLLBACK TO savepoint_name;
Example 1:
Now, we will execute the following query to insert multiple records at the same time in the t_school
table.
After executing the SELECT query on the t_school table, you will get the following output:
The output of the SELECT query shows that all the records are inserted successfully.
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.
To verify that the record with ID 5 now has the Number_Of_Students as 9050, we will execute the
SELECT query.
After executing the SELECT query on the t_school table, you will get the following output:
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.
Suddenly, our requirement changed, and we realized that we had updated a record that was not
supposed to be. In such a scenario, we need to roll back our transaction to the savepoint, which
was created prior to the execution of the UPDATE command.
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.
The SELECT query output confirms that the transaction is now successfully rolled back to the
savepoint 'Insertion'.
Example 2:
Now, we will execute the following query to insert multiple records at the same time in the
customer table.
We will now execute the SELECT query to verify the execution of the INSERT INTO query
executed above.
After executing the SELECT query on the t_school table, you will get the following output:
Customer_ID Name Age Salary Salary_BankAccount
The output of the SELECT query shows that all the records are inserted successfully.
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.
We will execute the delete command on the customer table to remove the record with ID 5.
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.
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.
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.
The SELECT query output confirms that the transaction is now successfully rolled back to the
savepoint 'Insertion'.
Conclusion:
LAB OBJECTIVES:
LAB OUTCOMES:
On Successful Completion, the Student will be able to understand about Implementing functions and
procedures in SQL
PROCEDURE:
1. Aggregate Functions
2. Scalar Functions
Function Description
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.
1 Sanjay 64
2 Varun 72
3 Akash 45
4 Rohit 86
5 Anjali 92
SUM()
Used to return a total sum of numeric column which you choose.
Syntax:
SELECTSUM(ColumnNa
1
me)
2
FROMTableName;
Example:
Write a query to retrieve the sum of marks of all students from the Students table.
SELECTSUM(Ma
1
rks)
2 FROMStudents;
Output:
3
1 5
9
COUNT()
Returns the number of rows present in the table either based on some condition or without any
condition.
Syntax:
SELECTCOUNT(ColumnNa
1
me)
2
FROMTableName
3
WHERECondition;
Example:
Write a query to count the number of students from the Students table.
SELECTCOUNT(Student
1
ID)
2
FROMStudents;
Output:
1 5
Example:
Write a query to count the number of students scoring marks > 75 from the Students table.
SELECTCOUNT(Student
1
ID)
2
FROMStudents
3
WHEREMarks >75;
Output:
1 2
AVG()
This function is used to return the average value of a numeric column.
Syntax:
SELECTAVG(ColumnNa
1
me)
2
FROMTableName;
Example:
Write a query to calculate the average marks of all students from the Students table.
SELECTAVG(Ma
1
rks)
2
FROMStudents;
Output:
7
1
1
.
8
MIN()
Used to return the minimum value of a numeric column.
Syntax:
SELECTMIN(ColumnNa
1
me)
2
FROMTableName;
Example:
Write a query to retrieve the minimum marks out of all students from the Students table.
SELECTMIN(Ma
1
rks)
2
FROMStudents;
Output:
1
MAX()
Returns the maximum value of a numeric column.
Syntax:
SELECTMAX(ColumnNa
1
me)
2
FROMTableName;
Example:
Write a query to retrieve the maximum marks out of all students from the Students table.
SELECTMAX(Ma
1
rks)
2
FROMStudents;
Output:
FIRST()
This function returns the first value of the column which you choose.
Syntax:
SELECTFIRST(ColumnNa
1
me)
2
FROMTableName;
Example:
Write a query to retrieve the marks of the first student.
SELECTFIRST(Ma
1
rks)
2
FROMStudents;
Output:
1
LAST()
Used to return the last value of the column which you choose.
Syntax:
SELECTLAST(ColumnNa
1
me)
2
FROMTableName;
Example:
Write a query to retrieve the marks of the last student.
SELECTLAST(Ma
1
rks)
2
FROMStudents;
Output: 92
Well, with that we come to an end to SQL Aggregate Functions. Next in this article on SQL
Functions, let us understand the various Scalar Functions.
Function Description
LCASE()
Used to convert values of a string column to lowercase characters.
Syntax:
SELECTLCASE(ColumnNa
1
me)
2
FROMTableName;
Example:
Write a query to retrieve the names of all students in lowercase.
SELECTLCASE(StudentNa
1
me)
2
FROMStudents;
Output:
sa
1 nj
ay
2
va
3 ru
n
4
ak
5 as
h
ro
hit
an
jal
i
UCASE()
Used to convert values of a string column to uppercase characters.
Syntax:
SELECTUCASE(ColumnNa
1
me)
2
FROMTableName;
Example:
SELECTUCASE(StudentNa
1
me)
2
FROMStudents;
Output:
SANJ
AY
1 VAR
UN
2
AKA
3
SH
4
ROHI
5 T
ANJ
ALI
LEN()
Used to retrieve the length of the input string.
Syntax:
SELECTLENGTH(String)
1
ASSampleColumn;
Example:
Write a query to extract the length of the student name “Sanjay”.
SELECTLENGTH(“Sanjay”)
1
ASStudentNameLen;
Output:
1 6
MID()
This function is used to extract substrings from columns having string data type.
Syntax:
SELECTMID(ColumnName, Start,
1
Length)
2
FROMTableName;
Example:
Write a query to extract substrings from the StudentName column.
SELECTMID(StudentName,
1
2, 3)
2
FROMStudents;
Output:
1
a
2 n
j
3
a
4 r
u
5
k
a
s
o
h
i
n
j
a
ROUND()
This function is used to round off a numeric value to the nearest integer.
Syntax:
SELECTROUND(ColumnName,
1
Decimals)
2
FROMTableName;
Example:
For this example, let us consider the following Marks table in the Students table.
1 Sanjay 90.76
2 Varun 80.45
3 Akash 54.32
4 Rohit 72.89
5 Anjali 67.66
1 SELECTROUND(Ma
2 rks)
FROMStudents;
Output:
9
1
1 8
0
2
5
3
4
4
7
5 3
6
8
NOW()
Used to return the current date and time. The date and time are returned in the “YYYY-MM-DD
HH-MM-SS” format.
Syntax:
SELECTNO
1
W();
Example:
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:
Output:
123-456-789
A stored procedure is a prepared SQL code that you can save, so the code can be reused over and
over again.
So if you have an SQL query that you write over and over again, save it as a stored procedure,
and then just call it to execute it.
You can also pass parameters to a stored procedure, so that the stored procedure can act based on
the parameter value(s) that is passed.
EXEC procedure_name;
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
CustomerI CustomerName ContactNa Address City PostalCo Countr
D me de y
The following SQL statement creates a stored procedure named "SelectAllCustomers" that
selects all records from the "Customers" table:
Example
Example
EXEC SelectAllCustomers;
The following SQL statement creates a stored procedure that selects Customers from a particular
City from the "Customers" table:
Example
Example
Setting up multiple parameters is very easy. Just list each parameter and the data type separated
by a comma as shown below.
The following SQL statement creates a stored procedure that selects Customers from a particular
City with a particular PostalCode from the "Customers" table:
Example
Example
Conclusion:
Procedure:
2. Implement Views:
3. Implement Triggers:
Implementation:
Name VARCHAR(50),
Department VARCHAR(50),
Salary DECIMAL(10,2));
EmpID INT,
OldSalary DECIMAL(10,2),
NewSalary DECIMAL(10,2),
BEGIN
END;
Conclusion:
• Views provide a virtual representation of data, enhancing security and simplifying query
execution.
LAB OBJECTIVES:
LAB OUTCOMES:
On Successful Completion, the Student will be able to understand about database connectivity
using JDBC
PROCEDURE:
● Java
importjava.io.*;
importjava.sql.*;
classGFG {
publicstaticvoidmain(String[] args) throwsException
{
String url
= "jdbc:mysql://localhost:3306/table_name"; // table details
String username = "rootgfg"; // MySQL credentials
String password = "gfg123";
String query
= "select *from students"; // query to be run
Class.forName(
"com.mysql.cj.jdbc.Driver"); // Driver name
Connection con = DriverManager.getConnection(
url, username, password);
System.out.println(
"Connection Established successfully");
Statement st = con.createStatement();
ResultSetrs
= st.executeQuery(query); // Execute query
rs.next();
String name
= rs.getString("name"); // Retrieve name from db
● Java
// Importing database
import java.sql.*;
// Importing required classes
import java.util.*;
// Main class
class Main {
System.out.println("enter name");
String name = k.next();
System.out.println("enter class");
String cls = k.next();
// Registering drivers
DriverManager.registerDriver(
new oracle.jdbc.OracleDriver());
// 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();
}
Output:
Conclusion:
Thus database connectivity using JDBC is done and verified.
EXPERIMENT-12
Aim: Implementation and Demonstration of Transaction and Concurrency Control
Techniques Using Locks
Lab Objective: Prevent data anomalies such as dirty reads, lost updates, and uncommitted data in
concurrent transactions.
Lab Outcomes: Successfully implement transaction management & concurrency control in real-
world database scenarios.
Procedure:
1. Transactions in SQL:
A transaction is a sequence of SQL statements executed as a single unit. Transactions ensure
database integrity through ACID properties:
• Atomicity: Ensures all operations in a transaction either complete successfully or none
execute at all.
• Consistency: Ensures the database remains in a consistent state before and after the
transaction.
• Isolation: Ensures that concurrent transactions do not interfere with each other.
• Durability: Ensures that once a transaction is committed, it is permanently stored in the
database.
Transaction Control Commands (TCL):
Command Description
COMMIT Saves all changes made by the transaction permanently.
ROLLBACK Reverts changes made during the transaction if an error occurs.
SAVEPOINT Creates a point within a transaction to which it can be rolled back.
Procedure:
Step 1: Create a Sample Database and Table
sql
CopyEdit
CREATE DATABASE BankDB;
USE BankDB;
Implementation of Transactions
Step 3: Demonstrate COMMIT & ROLLBACK
sql
CopyEdit
-- Start a transaction
START TRANSACTION;
-- Finalize transaction
COMMIT;
-- Transaction 2: Try to update the same account (This will wait until the first transaction is
completed)
UPDATE Accounts SET Balance = Balance + 500 WHERE AccountID = 101;
-- Transaction 2: Try to read the same account (It will wait until the first transaction is completed)
SELECT * FROM Accounts WHERE AccountID = 101;
Expected Output:
1. Transaction Implementation:
o The balance should update correctly after COMMIT.
o After ROLLBACK, changes should be undone.
2. Lock Implementation:
o Shared locks allow multiple reads but prevent updates.
o Exclusive locks prevent both reading and updating until the transaction is
committed.
Conclusion:
• Transactions ensure database integrity through ACID properties.
• Concurrency control techniques using locks help in avoiding data inconsistency in
concurrent transactions.
• Using locks (Shared & Exclusive) ensures that race conditions and data corruption do not
occur.
• This experiment successfully demonstrated Transaction Management & Concurrency
Control Techniques in SQL.