You are on page 1of 48

Module 5

Embedded SQL
Trigger
• A trigger is a stored procedure in database
which automatically invokes whenever a
special event in the database occurs. For
example, a trigger can be invoked when a row
is inserted into a specified table or when
certain table columns are being updated.
Trigger
• create trigger [trigger_name]: Creates or replaces an existing
trigger with the trigger_name.
• [before | after]: This specifies when the trigger will be executed.
• {insert | update | delete}: This specifies the DML operation.
• on [table_name]: This specifies the name of the table associated
with the trigger.
• [for each row]: This specifies a row-level trigger, i.e., the trigger
will be executed for each row being affected.
• [trigger_body]: This provides the operation to be performed as
trigger is fired.

• BEFORE triggers run the trigger action before the triggering


statement is run.
AFTER triggers run the trigger action after the triggering statement
is run.
Example:
• Given Student Report Database, in which student marks
assessment is recorded.
• In such schema, create a trigger so that the total and average
of specified marks is automatically inserted whenever a
record is insert.
• SQL Trigger to problem statement.
create trigger stud_marks
before INSERT
on Student
for each row set
Student.total = Student.subj1 + Student.subj2 + Student.subj3,
Student.per = Student.total * 60 / 100;
• create trigger stud_marks before INSERT on
Student for each row set Student.total =
Student.subj1 + Student.subj2 +
Student.subj3, Student.per = Student.total *
60 / 100;
Event-Condition-Action (ECA) Model
• Triggers follow an Event-condition-action (ECA) model
– Event:
• Database modification
– E.g., insert, delete, update),
– Condition:
• Any true/false expression
– Optional: If no condition is specified then condition is always true
– Action:
• Sequence of SQL statements that will be automatically executed
Triggers
• Triggers can be
– Row-level
• FOR EACH ROW specifies a row-level trigger
– Statement-level
• Default (when FOR EACH ROW is not specified)
• Row level triggers
– Executed separately for each affected row
• Statement-level triggers
– Execute once for the SQL statement,
Triggers
• An event can be considered in 3 ways
– Immediate consideration
– Deferred consideration
– Detached consideration
Triggers
• Immediate consideration
– Part of the same transaction and can be one of the following
depending on the situation
• Before
• After
• Instead of
• Deferred consideration
– Condition is evaluated at the end of the transaction
• Detached consideration
– Condition is evaluated in a separate transaction
Advantages of Triggers

• Triggers provide a way to check the integrity of


the data. When there is a change in the
database the triggers can adjust the entire
database.
• Triggers help in keeking User Interface
lightweight. Instead of putting the same
function call all over the application you can
put a trigger and it will be executed.
Disadvantages of Triggers
• Triggers may be difficult to troubleshoot as
they execute automatically in the database. If
there is some error then it is hard to find the
logic of trigger because they are fired before
or after updates/inserts happen.
• The triggers may increase the overhead of the
database as they are executed every time any
field is updated.
Stored Procedure
• A stored procedure is a prepared SQL code
that you can save, so the code can be reused
over and over again.
• So if you have an SQL query that you write
over and over again, save it as a stored
procedure, and then just call it to execute it.
• You can also pass parameters to a stored
procedure, so that the stored procedure can
act based on the parameter value(s) that is
passed.
Stored Procedure
• CREATE PROCEDURE 
procedure_name
AS
sql_statement
GO;

• Execute a Stored Procedure


EXEC procedure_name;
Stored Procedure With One Parameter
Stored Procedure With Multiple Parameters

• Setting up multiple parameters is very easy.


Just list each parameter and the data type
separated by a comma as shown below.
• The following SQL statement creates a stored
procedure that selects Customers from a
particular City with a particular PostalCode
from the "Customers" table:
Stored Procedure With Multiple Parameters
Stored Procedure
Advantages:
• Better Performance –
The procedure calls are quick and efficient as stored procedures are compiled once
and stored in executable form. Hence the response is quick. The executable code is
automatically cached, hence lowers the memory requirements.
• Higher Productivity –
Since the same piece of code is used again and again so, it results in higher
productivity.
• Ease of Use –
To create a stored procedure, one can use any Java Integrated Development
Environment (IDE). Then, they can be deployed on any tier of network
architecture.
• Scalability –
Stored procedures increase scalability by isolating application processing on the
server.
• Maintainability –
Maintaining a procedure on a server is much easier then maintaining copies on
various client machines, this is because scripts are in one location.
• Security –
Access to the Oracle data can be restricted by allowing users to manipulate the data
Stored Procedure
The main disadvantages of stored procedures are given below:
• Testing –
Testing of a logic which is encapsulated inside a stored procedure is very
difficult. Any data errors in handling stored procedures are not generated
until runtime.
• Debugging –
Depending on the database technology, debugging stored procedures will
either be very difficult or not possible at all. Some relational databases
such as SQL Server have some debugging capabilities.
• Versioning –
Version control is not supported by the stored procedure.
• Cost –
An extra developer in the form of DBA is required to access the SQL and
write a better stored procedure. This will automatically incur added cost.
• Portability –
Complex stored procedures will not always port to upgraded versions of
the same database. This is specially true in case of moving from one
database type(Oracle) to another database type(MS SQL Server).
Example for Triggers
Example for Triggers
Example for Triggers
Example for Triggers
Example for Triggers
Triggers
Triggers
Triggers
Triggers
Triggers
Triggers
Triggers
Triggers
Stored Procedures
Stored Procedures
Stored Procedures
• In this syntax:
• The uspProductList is the name of the stored
procedure.
• The AS keyword separates the heading and the
body of the stored procedure.
• If the stored procedure has one statement,
the BEGIN and END keywords surrounding the
statement are optional. However, it is a good
practice to include them to make the code clear
Stored Procedures
• For example, to execute
the uspProductList stored procedure, you use
the following statement:
• EXEC uspProductList;
Stored Procedures
NoSQL
• A NoSQL originally referring to non SQL or non
relational is a database that provides a
mechanism for storage and retrieval of data.
• This data is modelled in means other than the
tabular relations used in relational databases.
• NoSQL databases are used in real-time web
applications and big data and their use are
increasing over time.
• NoSQL systems are also sometimes called Not
only SQL to emphasize the fact that they may
support SQL-like query languages.
NoSQL
• A NoSQL database includes simplicity of design,
simpler horizontal scaling to clusters of machines and
finer control over availability.
• The data structures used by NoSQL databases are
different from those used by default in relational
databases which makes some operations faster in
NoSQL.
• The suitability of a given NoSQL database depends on
the problem it should solve.
• Data structures used by NoSQL databases are
sometimes also viewed as more flexible than relational
database tables.
Advantages
High scalability –
• NoSQL database use sharing for horizontal scaling.
• Partitioning of data and placing it on multiple machines in such a way that
the order of the data is preserved is sharing.
• Vertical scaling means adding more resources to the existing machine
whereas horizontal scaling means adding more machines to handle the
data.
• Vertical scaling is not that easy to implement but horizontal scaling is easy
to implement.
• Examples of horizontal scaling databases are MongoDB, Cassandra etc.
• NoSQL can handle huge amount of data because of scalability, as the data
grows NoSQL scale itself to handle that data in efficient manner.

High availability –
Auto replication feature in NoSQL databases makes it highly available because
in case of any failure data replicates itself to the previous consistent state.
Disadvantages of NoSQL:
1.Narrow focus –
NoSQL databases have very narrow focus as it is mainly designed for storage but it provides very
little functionality. Relational databases are a better choice in the field of Transaction Management
than NoSQL.
2.Open-source –
NoSQL is open-source database. There is no reliable standard for NoSQL yet. In other words two
database systems are likely to be unequal.
3.Management challenge –
The purpose of big data tools is to make management of a large amount of data as simple as
possible. But it is not so easy. Data management in NoSQL is much more complex than a
relational database. NoSQL, in particular, has a reputation for being challenging to install and even
more hectic to manage on a daily basis.
4.GUI is not available –
GUI mode tools to access the database is not flexibly available in the market.
5.Backup –
Backup is a great weak point for some NoSQL databases like MongoDB. MongoDB has no
approach for the backup of data in a consistent manner.
6.Large document size –
Some database systems like MongoDB and CouchDB store data in JSON format. Which means
that documents are quite large (BigData, network bandwidth, speed), and having descriptive key
names actually hurts, since they increase the document size.
Types of NoSQL database:
1.Key value store:  Redis, Coherence
2.Tabular: Hbase, Big Table, Accumulo
3.Document based: MongoDB, CouchDB,
Cloudant
4.Graph Store:Ontotext GraphDB
When should NoSQL be used:

1. When huge amount of data need to be stored


and retrieved .
2. The relationship between the data you store is
not that important
3. The data changing over time and is not
structured.
4. Support of Constraints and Joins is not required
at database level
5. The data is growing continuously and you need
to scale the database regular to handle the data.
How Does a NoSQL (nonrelational) Database Work?

• NoSQL databases use a variety of data models for accessing and managing
data.

Consider the example of modelling the schema for a simple book database:
• In a relational database, a book record is often dissembled (or “normalized”)
and stored in separate tables, and relationships are defined by primary and
foreign key constraints. In this example, the Books table has columns
for ISBN, Book Title, and Edition Number, the Authors table has columns
for AuthorID and Author Name, and finally the Author-ISBN table has
columns for AuthorID and ISBN. The relational model is designed to enable
the database to enforce referential integrity between tables in the database,
normalized to reduce the redundancy, and generally optimized for storage.

• In a NoSQL database, a book record is usually stored as a JSON(JavaScript


Object Notation) document. For each book, the item, ISBN, Book
Title, Edition Number, Author Name, and AuthorID are stored as attributes in
a single document. In this model, data is optimized for intuitive development
and horizontal scalability.
RDBMS vs MongoDB
Differences
SQL vs NOSQL

You might also like