0% found this document useful (0 votes)
29 views

ADB - CH2 - Advanced SQL

This document outlines the key topics covered in Chapter Two of Advanced Structured Query Language (SQL). It discusses database architecture including 1-tier, 2-tier, and 3-tier systems. Querying tools, storage and indexing, and query processing and optimization are also covered. The document provides details on features like indexing types, order-indexing, and multilevel indexing. It defines what a database query is and distinguishes between database and information retrieval queries.

Uploaded by

Abenezer Teshome
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

ADB - CH2 - Advanced SQL

This document outlines the key topics covered in Chapter Two of Advanced Structured Query Language (SQL). It discusses database architecture including 1-tier, 2-tier, and 3-tier systems. Querying tools, storage and indexing, and query processing and optimization are also covered. The document provides details on features like indexing types, order-indexing, and multilevel indexing. It defines what a database query is and distinguishes between database and information retrieval queries.

Uploaded by

Abenezer Teshome
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 60

Chapter Two

Advanced Structured Query Language


(SQL)

1
Outline
 Features and basic architecture
 Database Design and Querying Tools
 Storage and Indexing
 Query Processing, Evaluation and Optimization
 Assertion and views
 Cursors, triggers and stored procedures
 Embedded SQL, dynamic SQL, SQLJ,
 SQL Variations and Extensions
 Transaction Management

2
Features and basic architecture
⚫ The design of a DBMS depends on its architecture. It can be centralized
or decentralized or hierarchical.
⚫ The architecture of a DBMS can be seen as either single tier or multi-tier.
⚫ An n-tier architecture divides the whole system into related but
independent n modules, which can be independently modified, altered,
changed, or replaced.
⚫ In 1-tier architecture, the DBMS is the only entity where the user
directly sits on the DBMS and uses it.
⚫ Any changes done here will directly be done on the DBMS itself.
⚫ It does not provide handy tools for end-users.
⚫ Database designers and programmers normally prefer to use single-tier
architecture.

3
Cont`d…

 2-tier, then it must have an application through which the


DBMS can be accessed.
 Programmers use 2-tier architecture where they access
the DBMS by means of an application.
 Here the application tier is entirely independent of the
database in terms of operation, design, and programming.
⚫ 3-tier Architecture
A 3-tier architecture separates its tiers from each other
based on the complexity of the users and how they use
the data present in the database. It is the most widely
used architecture to design a DBMS.

4
3-tier Architecture

Database (Data) Tier - At this tier, the database


resides along with its query processing languages. We
also have the relations that define the data and their
constraints at this level.
Application (Middle) Tier - At this tier reside the
application server and the programs that access the
database.
For a user, this application tier presents an abstracted
view of the database.
End-users are unaware of any existence of the
database beyond the application. At the other end, the
database tier is not aware of any other user beyond
the application tier.
Hence, the application layer sits in the middle and acts
as a mediator between the end-user and the database.
5
3-tier Architecture… cont`d

User (Presentation) Tier - End-users operate on this tier


and they know nothing about any existence of the database
beyond this layer.
At this layer, multiple views of the database can be provided
by the application.
All views are generated by applications that reside in the
application tier.
Multiple-tier database architecture is highly modifiable, as
almost all its components are independent and can be
changed independently.
Querying tools

 The query tool provides data access, filtering and simple


formatting.
 Also it offers an integrated environment that that lets you
monitor, query, design and configure your local and online
database.
 The platform also offers robust security options to help keep
data protected all times while completely available for free
 If you are distributing reports across your enterprise or need
to generate form-safe presentation, you use a reporting
tools.
 E.g., Microsoft SQL server Management studio, MySQL
workbench, PostgreSQL, DbVisualizer, Oracle SQL
developer, Tableplus, SQLite studio, dbForge studio …
Storage and Indexing
Databases are stored in file formats, which contain records. At
physical level, the actual data is stored in electromagnetic format on
some device. These storage devices can be broadly categorized
into three types –
Primary Storage - The memory storage
that is directly accessible to the CPU
comes under this category. CPU's internal
memory (registers), fast memory Relational Data Model(4)
(cache),
and main memory (RAM) are directly
accessible to the CPU, as they are all
placed on the motherboard or CPU chipset.
This storage is typically very small, ultra-
fast, and volatile.
Primary storage requires continuous power
supply in order to maintain its state. In case
of a power failure, all its data is lost.
Storage and Indexing…cont`d
 Secondary Storage - Secondary storage devices are used
Relational
to store data for future use orData Model(5)
as backup.
Secondary storage includes memory devices that are not a
part of the CPU chipset or motherboard, for example,
magnetic disks, optical disks (DVD, CD, etc.), hard disks,
flash drives, and magnetic tapes.
 Tertiary Storage - Tertiary storage is used to store huge
volumes of data. Since such storage devices are external to
the computer system, they are the slowest in speed.
These storage devices are mostly used to take the back up of
an entire system. Optical disks and magnetic tapes are widely
used as tertiary storage.
Indexing
 Indexing is a data structure technique to efficiently retrieve records
from the database files based on some attributes on which the indexing
has been done. Indexing in database systems is similar to what we see
in books.
 The utilization of indexes can dramatically reduce the execution time of
various operations such as select and join.
 Indexing is defined based on its indexing attributes. Indexing can be of
the following types –
 Primary Index - Primary index is defined on an ordered data file.
The data file is ordered on a key field. The key field is generally the
primary key of the relation.
 Secondary Index - Secondary index may be generated from a field
which is a candidate key and has a unique value in every record, or
a non-key with duplicate values.
 Clustering Index - Clustering index is defined on an ordered data
file. The data file is ordered on a non-key field.
Order-Indexing…. Cont`d
Ordered Indexing is of two types - Dense Index and Sparse Index
Dense Index
In dense index, there is an index record for every
search key value in the database. This makes
searching faster but requires more space to store
index records itself.
Index records contain search key value and a
pointer to the actual record on the disk.

Sparse Index
In sparse index, index records are not created for every search key. An index
record here contains a search key and an actual pointer to the data on the disk.
To search a record, we first proceed by index record
and reach at the actual location of the data. If the
data we are looking for is not where we directly
reach by following the index, then the system starts
sequential search until the desired data is found.
Cont`d…..

Multilevel Index
Index records comprise search-key values and
data pointers. Multilevel index is stored on the disk
along with the actual database files.
As the size of the database grows, so does the
size of the indices. There is an immense need to
keep the index records in the main memory so as
to speed up the search operations. If single-level
index is used, then a large size index cannot be same
kept in memory which leads to multiple disk
accesses.

Multi-level Index helps in breaking down the index into several


smaller indices in order to make the outermost level so small
that it can be saved in a single disk block,
which can easily be accommodated everywhere in the
memory
Query

 Is a piece of code that is sent to a database in order to get


information back from the database. It is used as the way (refers
to the action) of retrieving the data/information from database.
 A database "query" is basically a "question" that you ask the
database. The term 'query' means to search, to question, or to
find. When you query a database, your searching for information
in the database. Queries are one of the things that make
databases so powerful.
 The result of the query is the information that is returned by the
database management system. Queries are usually constructed
using SQL (structured query language) which resembles a high-
level programming language. As with many other tasks, you can
query a database either programmatically or via a user interface.
Database query Vs information retrieval query

Query's Are computer languages used to make queries into


databases and information systems.
Broadly, can be classified according to whether they are
database query languages or information retrieval query
languages.
The difference is that a database query language attempts to
give factual answers to factual questions,
While an information retrieval query language attempts to find
documents containing information that is relevant to an area of
inquiry.
Query Languages != programming languages!
QLs not intended to be used for complex calculations but
support easy, efficient access to large data sets.
Query Processing and Optimization

Query Processing: Activities involved in retrieving/manipulating data from the database.


Usually, you will be selective with how much data you want returned. If you have a lot of
data in your database, you probably don't want to see everything.
 A database query is the vehicle for instructing a DBMS to update or retrieve specific data
to/from the physically stored medium.
 Transform query written in high-level language (e.g. SQL), into correct and efficient
execution strategy expressed in low-level language(implementing the relational algebra)
since The actual updating and retrieval of data is performed through various “low-level”
operations.
 Executes the strategy to retrieve required data.

Query Optimization: Choosing an efficient execution strategy for processing query.


 As there are many equivalent transformations of same high-level query, aim of QO is to
choose one that minimizes resource usage and reduce total execution time of query.
Phases of Query Processing
There are phases that a query passes through during the DBMS’ processing
of that query:

1. Decomposition(Scanning, Parsing and


Validation)
2. Optimization
3. Code generation and
4. Execution/run time DB processor
Phases of Query Processing … cont`d

 Scanner identifies the query tokens such as SQL keywords, attribute names, and
relation names.
 Parser checks the query syntax to determine whether it is formulated according to the
syntax rules of the query language. The primary job of the parser is to extract the
tokens from the raw string of characters and translate them into the corresponding
internal data elements (i.e. relational algebra operations and operands) and structures
(i.e. query tree, query graph).
 The query must also be validated by checking that all attribute and relation names are
valid and semantically meaningful names in the schema of the particular database
being queried. An internal representation of the query is then created, usually as a tree
data structure called a query tree. It is also possible to represent the query using a
graph data structure called a query graph.
Phases of Query Processing … cont`d

Query Code Generator: Interpreters and compilers that are embedded


in DBMS that checks errors and debugs faults.

Runtime database processor has the task of running (executing) the


query code, whether in compiled or interpreted mode, to produce the
query result. If a runtime error results, an error message is generated
by the runtime database processor.
The query processor

Most queries submitted to a DBMS are in a high-level language such as


SQL. During the parsing and translation stage, the human readable form
of the query is translated into forms usable by the DBMS. These can be
in the forms of a relational algebra expression, query tree and query
graph.
 After parsing and translation into a relational algebra expression, the
query is then transformed into a form, usually a query tree or graph,
that can be handled by the optimization engine.
 The optimization engine then performs various analyses on the query
data, generating a number of valid evaluation plans.
 From there, it determines the most appropriate evaluation plan to
execute.
 After the evaluation plan has been selected, it is passed into the
DMBS’ query-execution engine (also referred to as the runtime
database processor), where the plan is executed and the results are
returned.
Parsing and Translating the Query

 The first step in processing a query submitted to a DBMS is to convert


the query into a form usable by the query processing engine.
 High-level query languages such as SQL represent a query as a string,
or sequence, of characters.
 Certain sequences of characters represent various types of tokens such
as keywords, operators, operands, literal strings, etc. Like all languages,
there are rules (syntax and grammar) that govern how the tokens can be
combined into understandable (i.e. valid) statements.
 The primary job of the parser is to extract the tokens from the raw string
of characters and translate them into the corresponding internal data
elements (i.e. relational algebra operations and operands) and structures
(i.e. query tree, query graph).
 The last job of the parser is to verify the validity and syntax of the original
query string.
Optimizing the Query

 In this stage, the query processor applies rules to the internal


data structures of the query to transform these structures into
equivalent, but more efficient representations.
 The rules can be based upon mathematical models of the
relational algebra expression and tree (heuristics), upon cost
estimates of different algorithms applied to operations or upon
the semantics within the query and the relations it involves.
 Selecting the proper rules to apply, when to apply them and
how they are applied is the function of the query optimization
engine.
Evaluating the Query

 The final step in processing a query is the evaluation


phase.
 The best evaluation plan candidate generated by the
optimization engine is selected and then executed.
 Note that there can exist multiple methods of executing a
query. Besides processing a query in a simple sequential
manner, some of a query’s individual operations can be
processed in parallel—either as independent processes or
as interdependent pipelines of processes or threads.
 Regardless of the method chosen, the actual results
should be same.
Relational Algebra

 The basic set of operations for the relational model is known as the relational
algebra. The algebra operations thus produce new relations, which can be further
manipulated using operations of the same algebra.
 A sequence of relational algebra operations forms a relational algebra expression,
whose result will also be a relation that represents the result of a database query (or
retrieval request).
 Relational algebra is a theoretical language with operations that work on one or
more relations to define another relation without changing the original relation.
 The output from one operation can become the input to another operation (nesting
is possible)
Selection

 Selects/Filters subset of tuples/rows in a relation that satisfy selection condition.


 Selection operation is a unary operator (it is applied to a single relation)
 Set of conditions can be combined using Boolean operations (∧(AND),
∨(OR),~(NOT))
 Result relation can be the input for another relational algebra operation!
Projection

 Selects certain attributes while discarding the other from the base relation.
 The PROJECT creates a vertical partitioning – one with the needed columns
(attributes) containing results of the operation.
 Deletes attributes that are not in projection list.
UNION and INTERSECTION Operation

 Union operation, denoted by R U S, is a relation that includes all tuples that are either
in R or in S or in both R and S. Duplicate tuples are eliminated.
 Intersection denoted by R ∩ S, is a relation that includes all tuples that are in both R
and S.
CARTESIAN (cross product) Operation

 This operation is used to combine tuples from two relations in a combinatorial fashion.
That means, every tuple in Relation1(R) one will be related with every other tuple in
Relation2 (S).
The resulting relation Q has one tuple for each combination of tuples—one from R and
one from S.
Hence, if R has n tuples, and S has m tuples, then | R x S | will have n* m tuples.
JOIN Operation

 In a relational database, data is distributed in multiple logical tables. to get a complete


meaningful set of data, you need to query data from these tables by using joins. SQL Server
supports many kinds of joins including inner join, left join, right join, full outer join, and cross
join.
 Each join type specifies how SQL Server uses data from one table to select rows in another
table.
 Inner join: produces a data set that includes rows from the left table which have matching rows
from the right table.
 Left Join: selects data starting from the left table and matching rows in the right table. The left
join returns all rows from the left table and the matching rows from the right table. If a row in
the left table does not have a matching row in the right table, the columns of the right table will
have nulls. The left join is also known as left outer join. The outer keyword is optional.
 The right join or right outer join selects data starting from the right table. It
is a reversed version of the left join The right join returns a result set that contains all rows from
the right table and the matching rows in the left table. If a row in the right table that does not
have a matching row in the left table, all columns in the left table will contain nulls.
 The full outer join or full join returns a result set that contains all rows from both left and right
tables, with the matching rows from both sides where available. In case there is no match, the
missing side will have NULL values.
JOIN Operation … cont`d

 The sequence of Cartesian product followed by select is used quite commonly to identify
and select related tuples from two relations, a special operation, called JOIN. Thus in
JOIN operation, the Cartesian Operation and the Selection Operations are used together.
 This operation is very important for any relational database with more than a single
relation, because it allows us to process relationships among relations.
 This type of JOIN is called a THETA JOIN (θ - JOIN)
Where θ is the logical operator used in the join condition.
θ Could be { <, ≤ , >, ≥, ≠, = }
Example:
Thus in the above example we want to extract employee information about managers of the
departments, the algebra query using the JOIN operation will be.
JOIN Operation … example
Translating SQL Queries into Relational Algebra

SQL query is first translated into an equivalent extended relational algebra expression
that is represented as a query tree data structure. It is then optimized. Typically, SQL
queries are decomposed into query blocks, which form the basic units that can be
translated into the algebraic operators and optimized.

Figure: Relational Database Schema Example


Translating SQL Queries into Relational Algebra … cont`d

Example of translating SQL queries into relation Algebra 1: Consider the following SQL query on the
EMPLOYEE relation based on the above schema diagram for company relational database schema.

where c represents the result returned from the inner block. The inner block could
be translated into the following extended relational algebra expression:

and the outer block into the expression

The query optimizer would then choose an execution plan for each query block.
Notice that in the above example, the inner block needs to be evaluated only once to
produce the maximum salary of employees in department 5, which is then used as the
constant c by the outer block.
 Consider the following SQL query: This can be translated into
either of the following relational algebra expressions, query
graphs or query tree:
select make
from vehicles
where make = “Ford”
Which can also be represented as either of the following query trees:

query trees

relational algebra expressions

query graph
Heuristics Based Query Optimization

 Heuristic rules that help to modify the internal representation of a query, which is usually in the form
of a query tree and a query graph data structure to improve its expected performance.
 A query tree is a tree data structure that corresponds to a relational algebra expression. It represents
the input relations of the query as leaf nodes of the tree and represents the relational algebra
operations as internal nodes.
 The order of execution of operations starts at the leaf nodes, which represents the input database
relations for the query, and ends at the root node, which represents the final operation of the query.
The execution terminates when the root node operation is executed and produces the result relation
for the query.
 The scanner and parser of an SQL query first generate a data structure that corresponds to an initial
query representation, which is then optimized according to heuristic rules.
One of the main heuristic rules is to apply SELECT and PROJECT operations before applying the
JOIN or other binary operations, because the size of the file resulting from a binary operation such as
JOIN is usually a multiplicative function of the sizes of the input files. The SELECT and PROJECT
operations reduce the size of a file and hence should be applied before a join or other binary operation.
Transformation of Relational
Expressions

The heuristic query optimizer must include rules for equivalence among relational
algebra expressions to transform the initial tree into the final, optimized query tree.
The heuristic query optimizer will transform this initial query tree into an equivalent
final query tree that is efficient to execute.
Example of Transforming a Query 1. Consider the following query Q on the database in Figure
: Find the last names of employees born after 1957 who work on a project named .‘Aquarius’.
This query can be specified in SQL as follows:

The initial query tree for Q is shown in step (a). Executing this tree directly first creates a very
large file containing the CARTESIAN PRODUCT of the entire EMPLOYEE, WORKS_ON,
and PROJECT files. That is why the initial query tree is never executed but is transformed into
another equivalent tree that is efficient to execute. This particular query needs only one record
from the PROJECT relation for the ‘Aquarius’ project and only the EMPLOYEE records for
those whose date of birth is after ‘1957-12-31’.
Steps in converting a query tree during heuristic optimization. 
1. Initial (canonical) query tree for SQL query Q.
2. Moving SELECT operations down the query tree to reduce the number of attributes.
3. Applying the more restrictive SELECT operation first. This is done by reordering the leaf nodes of the
tree among themselves and adjusting the rest of the tree appropriately.)
4. Replacing CARTESIAN PRODUCT and SELECT with JOIN operations.
5. Moving PROJECT operations down the query tree.
  (a). Initial (canonical) query tree for SQL query Q.

Figure a: canonical query in order of relation from the query


(b). Moving SELECT operations down the query tree

Figure b: SELECT operations go down the query tree


(c). Applying the more restrictive SELECT operation first.

Figure c: Restrictive selection operations


(d). Replacing CARTESIAN PRODUCT and SELECT with JOIN operations.

Figure d: JOIN operations replaces Cartesian Product and selection


(e). Moving PROJECT operations down the query tree.

Figure e: PROJECT operations go down to the query tree


A further improvement is achieved by switching the positions of the EMPLOYEE and
PROJECT relations in the tree, Figure (c). This uses the information that Pnumber is a
key attribute of the PROJECT relation, hence the SELECT operation on the PROJECT
relation will retrieve a single record only. We can further improve the query tree by
replacing any CARTESIAN PRODUCT operation that is followed by a join condition
with a JOIN operation, as shown in Figure(d).

Another improvement is to keep only the attributes needed by subsequent operations in


the intermediate relations, by including PROJECT (π) operations as early as possible in
the query tree, as shown in Figure 3.9(e). This reduces the attributes (columns) of the
intermediate relations, whereas the SELECT operations reduce the number of tuples
(records).
Example of Transforming a Query 2. For every project located in ‘Stafford’, retrieve the
project number, the controlling department number, and the department manager’s last name,
address, and birthdate from projects, employee and department relations.
In Figure,
The leaf nodes P, D, and E represent the three
relations PROJECT, DEPARTMENT, and
EMPLOYEE, respectively, and the internal tree nodes
represent the relational algebra operations of the
expression. When this query tree is executed, the
node marked (1) in Figure 3.4 must begin execution
before node (2) because some resulting tuples of

Fig: Optimized Query tree


operation (1) must be available before we can begin
executing operation (2). Similarly, node (2) must
begin executing and producing results before node
(3) can start execution, and so on.

Home take exercise: Show the query transformation process for the above example .
Assertions

 Assertions are conditions that the database must always satisfy


 Domain constraints and referential-integrity constraints are
specific forms of assertions
 CHECK – verify the assertion on one-table, one-attribute
 ASSERTION – verify one or more tables, one or more attributes
 Some constraints cannot be expressed by using only domain
constraints or referential-integrity constraints; for example,
“Every student must have course load<21 every semester”
must be expressed as an assertion
Note: Although ASSERTION is in the SQL standard, most DBMS
does not support it. Therefore, CHECK and TRIGGERS are
commonly used as work around approaches.
SQL- Views

 A view is nothing more than a SQL statement that is stored in the


database with an associated name.
 A view is actually a composition of a table in the form of a
predefined SQL query. A view can contain all rows of a table or
select rows from a table.
 A view can be created from one or many tables which depends
on the written SQL query to create a view. Views, which are a
type of virtual tables allow users to do the following –
 Structure data in a way that users or classes of users find
natural or intuitive.
 Restrict access to the data in such a way that a user can see
and (sometimes) modify exactly what they need and no more.
 Summarize data from various tables which can be used to
generate reports.
Creating Views ….. cont`d

 Database views are created using the CREATE VIEW


statement. Views can be created from a single table, multiple
tables or another view.
 To create a view, a user must have the appropriate system
privilege according to the specific implementation.
The basic CREATE VIEW syntax is as follows –
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE [condition];
You can include multiple tables in your SELECT statement in a
similar way as you use them in a normal SQL SELECT query.

NB: we can updating VIEWS, inserting, updating rows in to a


VIEW and dropping VIEWS.
(follow lab sessions)
Why use views?

 To hide data from users


 To hide complexity from users
 Logical data independence
• If applications deal with views, we can change the
underlying schema without affecting applications
• Recall physical data independence: change the physical
organization of data without affecting applications
 To provide a uniform interface for different
implementations or sources
 Real database applications use tons of views
Database Cursors

 A record pointer in database, when a database file is


selected and the cursor is opened, the cursor points to the
first record in the file.
 Using various commands, the cursor can be moved forward,
backward, to top of file, bottom of file and so forth.
 Cursors are used by database programmers to process
individual rows returned by database system queries
 Cursors enables manipulation of whole result sets at once.
Example: sequential processing of rows in a result set
 Its purpose is to keep track of the position in the result set
and allows to perform multiple operations row by row
against a result set, with or with out returning to the original
table. i.e. cursors conceptually returned a result set based
on tables with in database
Triggers

 A trigger is an event-condition-action (ECA) rule, When event


occurs, test condition; if condition is satisfied, execute action.
 A mechanism that initiates an action when an event occurs
such as reaching a certain time or date or upon receiving
some type of input. A trigger generally causes a program
routine to be executed.
 In an SQL procedure that is executed when a recorded is
added or deleted.
 Used to maintain referential integrity in the database
Trigger options

Possible events include:


 INSERT ON table
 DELETE ON table
 UPDATE [OF column] ON table
• Granularity—trigger can be activated:
 FOR EACH ROW modified
 FOR EACH STATEMENT that performs
modification
• Timing—action can be executed:
 AFTER or BEFORE the triggering event
 INSTEAD OF the triggering event on views (more
later)

(follow lab sessions)


Stored Procedures

 A stored procedure groups one or more Transact-SQL


statements into a logical unit, stored as an object in a SQL
Server database.
 When a stored procedure is executed for the first time, SQL
Server creates an execution plan and stores it in the plan
cache.
 SQL Server can then reuse the plan on subsequent
executions of this stored procedure.
 Plan reuse allows stored procedures to provide fast and
reliable performance compared to non-compiled and
unprepared ad hoc query equivalents.
Why stored procedures

 SP help centralize your Transact-SQL code in the data tier.


 can reduce network traffic for larger ad hoc queries
 Stored procedures encourage code reusability.
 allow you to obscure the method of data retrieval
 can do more than views
 have a stabilizing influence on query response time.
 Have better security benefits
Creating Stored procedure …

Create procedure sp_std(@course varchar(50))

As
Select * from stud_course where coursetitle=@course

EXECUTE sp_std 'dbms'

drop procedure sp_std

(follow lab sessions)


Embedded SQL, static SQL and dynamic SQL

 Is method of combining the computing power of a


programming language and the database
manipulation capabilities of SQL and are written
inline with the program source code of the host
language.
 SQL statements that are written in to a high-level
programming language such as C or Pascal or
java.
 In a processing stage, the SQL code is converted
in to function calls, which may be optimized to
provide the fastest result.
Why embedded SQL?
 Helps to access the database from any where,
 allows integrating authentication service for large scale
applications.
 Allows extra security to database transaction
 Avoids logical errors while performing transactions on our
database.
Static vs Dynamic SQL
 If a programmer knows exactly what the query is going to do,
the query does not change, it is called static SQL. Are SQL
statements in an application that do not change at run time
and therefore can be hard-codded in to the applications
 If the user requires user input at run time, it is called
dynamic SQL. SQL statements that are constructed at run
time. E.g. the application may allow users to enter their own
queries.
SQLJ and JDBC

 If the user program passes the SQL statements directly to the


database server without any intermediate step, it is called pass-
through SQL.
 A programming interface that allows SQL statements to be
expressed at a high-level In a JAVA programming.
 SQL statements are converted in to JDBC commands.
 Java Data Base Connectivity(JDBC) is a programming interface
that lets java applications access a database via SQL language.
 Since java interpreters are available for all major client platforms,
this allows platform independent database applications to be
written.
 In 1996 JDBC was the first extension to the java platform.
 JDBC is the java counterpart of Microsoft`s ODBC(open
database connectivity)
Transaction management

 A transaction is a unit of work that is performed against a


database.
 Transactions are units or sequences of work accomplished
in a logical order, whether in a manual fashion by a user or
automatically by some sort of a database program.
 A transaction is the propagation of one or more changes to
the database.eg., if you are creating a record or
updating/deleting a record from the table, then you are
performing a transaction on that table.
 It is important to control these transactions to ensure the
data integrity and to handle database errors.
 Practically, you will club many SQL queries into a group and
you will execute all of them together as a part of a
transaction
Properties of Transactions

 Transactions have the following four standard properties, usually


referred to by the acronym ACID.
 Atomicity - ensures that all operations within the work unit
are completed successfully. Otherwise, the transaction is
aborted at the point of failure and all the previous operations
are rolled back to their former state.
 Consistency - ensures that the database properly changes
states upon a successfully committed transaction.
 Isolation - enables transactions to operate independently of
and transparent to each other.
 Durability - ensures that the result or effect of a committed
transaction persists in case of a system failure.

You might also like