0% found this document useful (0 votes)
14 views85 pages

Unit 2

The document provides an overview of the structure and concepts of Relational Database Management Systems (RDBMS), including tables, tuples, and integrity constraints. It discusses relational query languages such as relational algebra and relational calculus, detailing operations like selection, projection, and joins. Additionally, it covers safety of expressions in relational calculus and provides examples of queries to illustrate the concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views85 pages

Unit 2

The document provides an overview of the structure and concepts of Relational Database Management Systems (RDBMS), including tables, tuples, and integrity constraints. It discusses relational query languages such as relational algebra and relational calculus, detailing operations like selection, projection, and joins. Additionally, it covers safety of expressions in relational calculus and provides examples of queries to illustrate the concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 85

DBMS

Unit-2
Dr. D. SUDHEER
Assistant Professor
Department of CSE
VNR VJIET (NAAC: A++, NIRF: 113)
Hyderabad, Telangana.
Structure of RDBMS
• A relational database consists of a collection of tables,
each of which is assigned a unique name.
• For example, consider the instructor table of Figure
2.1, which stores information about instructors.
• The table has four column headers: ID, name, dept
name, and salary. Each row of this table records
information about an instructor, consisting of the
instructor’s ID, name, dept name, and salary.
Introduction to Relational Model
⚫ Relational data model is the primary data model,
which is used widely around the world for data
storage and processing.
⚫ This model is simple and it has all the properties
and capabilities required to process data with
storage efficiency.
Concepts
⚫Tables − In relational data model, relations are
saved in the format of Tables. This format stores the
relation among entities. A table has rows and
columns, where rows represents records and
columns represent the attributes.
⚫Tuple − A single row of a table, which contains a
single record for that relation is called a tuple.
⚫Relation instance − A finite set of tuples in the
relational database system represents relation
instance. Relation instances do not have duplicate
tuples.
Concepts(cont..)
⚫Relation schema − A relation schema describes
the relation name (table name), attributes, and
their names.
⚫Relation key − Each row has one or more
attributes, known as relation key, which can
identify the row in the relation (table) uniquely.
⚫Attribute domain − Every attribute has some pre-
defined value scope, known as attribute domain.
Integrity Constraints
• Integrity constraints are a set of rules. It is used to
maintain the quality of information.
• Integrity constraints ensure that the data insertion,
updating, and other processes have to be performed in
such a way that data integrity is not affected.
• Integrity constraints ensure that the data insertion,
updating, and other processes have to be performed in
such a way that data integrity is not affected.
Domain Constraints
• Domain constraints can be defined as the definition of a valid set of
values for an attribute.
• The data type of domain includes string, character, integer, time,
date, currency, etc. The value of the attribute must be available in the
corresponding domain.
Entity integrity
• constraints
The entity integrity constraint states that primary key value can't be
null.
• This is because the primary key value is used to identify individual
rows in relation and if the primary key has a null value, then we can't
identify those rows.
• A table can contain a null value other than the primary key field.
Referential Integrity Constraints
• A referential integrity constraint is specified between
two tables.
• In the Referential integrity constraints, if a foreign key
in Table 1 refers to the Primary Key of Table 2, then
every value of the Foreign Key in Table 1 must be null
or be available in Table 2.
Key constraints
• Keys are the entity set that is used to identify an entity within its
entity set uniquely.
• An entity set can have multiple keys, but out of which one key will be
the primary key.
• refer unit 1 ppt for more info about key constraints.
Relational Query Languages
⚫ Relational database systems are expected to be
equipped with a query language that can assist its
users to query the database instances. There are two
kinds of query languages − relational algebra and
relational calculus.
⚫ Query languages: Allow manipulation and retrieval
of data from a database.
⚫ Query Languages != programming languages!
◦ QLs not intended to be used for complex
calculations.
◦ QLs support easy, efficient access to large data sets.
Formal Relational Query Languages
⚫ Two mathematical Query Languages form
the basis for “real” languages (e.g. SQL),
and for implementation:
◦ Relational Algebra: More operational
(procedural), very useful for representing
execution plans.
◦ Relational Calculus: Lets users describe what
they want, rather than how to compute it: Non-
operational, declarative.
Relational Algebra
⚫ Procedural language
⚫ Six basic operators
◦ select: σ
◦ project: ∏
◦ union: ∪
◦ set difference: –
◦ Cartesian product: x
◦ rename: ρ
⚫ The operators take one or two relations as inputs and
produce a new relation as a result.
Select Operation
Notation: σ p(r)
p is called the prepositional logic of selection predicate
Defined as:

σp(r) = {t | t ∈ r and p(t)}

Where p is a formula in propositional calculus consisting of


terms connected by : ∧ (and), ∨ (or), ¬ (not)
Each term is one of:
<attribute> op <attribute> or <constant>
where op is one of: =, ≠, >, ≥. <. ≤

Example of selection:

σ dept_name=“Physics” (instructor)
Project Operation
⚫ Notation:

where A 1, A2 are attribute names and r is a relation name.


⚫ The result is defined as the relation of k columns obtained
by erasing the columns that are not listed
⚫ Duplicate rows removed from result, since relations are sets
⚫ Example: To eliminate the dept_name attribute of instructor

∏ID, name, salary (instructor)


Union Operation
Notation: r ∪ s
Defined as:
r ∪ s = {t | t ∈ r or t ∈ s}
For r ∪ s to be valid.
1. r, s must have the same arity (same number of
attributes)
2. The attribute domains must be compatible (example: 2nd
column
of r deals with the same type of values as does the 2nd
column of s)
Example: to find all courses taught in the Fall 2009 semester, or
in the Spring 2010 semester, or in both
∏course_id (σ semester=“Fall” Λ year=2009 (section)) ∪
∏course_id (σ semester=“Spring” Λ year=2010 (section))
Set Difference Operation
Notation r – s
Defined as:
r – s = {t | t ∈ r and t ∉ s}

Set differences must be taken between compatible relations.


r and s must have the same arity
attribute domains of r and s must be compatible
Example: to find all courses taught in the Fall 2009 semester, but not in
the Spring 2010 semester

∏course_id (σ semester=“Fall” Λ year=2009 (section)) −

∏course_id (σ semester=“Spring” Λ year=2010 (section))


Relational Algebra Summary:

• The basic set of operations for the relational model is the relational
algebra.
• The sequence of relational algebra operations forms a relational
expression, which result also be a relation.
• SELECT and PROJECT operations are unary operations.
• UNION, INTERSECTION, JOIN, SET DIFFERENCE, CARTESIAN
PRODUCT are binary operations.
Sequence of operations:
• We can write the operations as single relational algebra expressions
by nesting the operations as follows:

• Alternatively we can give sequence of operations, giving name to


each intermediate relation as follows:
Rename Operation
⚫ Allows us to name, and therefore to refer to, the results of
relational-algebra expressions.
⚫ Allows us to refer to a relation by more than one name.
⚫ Example:
ρ x (E)

returns the expression E under the name X


⚫ If a relational-algebra expression E has arity n, then

returns the result of expression E under the name X, and


with the
attributes renamed to A 1 , A2 , …., An .
Cartesian Product:
• It is also known as CROSS PRODUCT or CROSS JOIN which is
denoted by x.
• This is also a binary set operation.
• It do not require to be union compatible.
• It will produce new element by combining with every member in
one relation with every member in other relation.
• Let R and S are two relations, Q is resulting relation.
• R has nR tupples, and S has n S tupples.
⚫ Notation r x s
⚫ Defined as:
r x s = {t q | t ∈ r and q ∈ s}

⚫ Assume that attributes of r(R) and


s(S) are disjoint. (That is, R ∩ S = ∅).
⚫ If attributes of r(R) and s(S) are not
disjoint, then renaming must be
used.
Relational operation on Cartesian product:
Joins

Joins

Non Equi
Equi Joins
Joins

Outer
Inner Joins
Joins

left Join left Join

left Join
Natural
Self Join
Join
Joins
• An SQL JOIN clause combines rows from two or more tables. It
creates a set of rows in a temporary table.
Equijoin: SQL EQUI JOIN
performs a JOIN against
equality or matching
column(s) values of the
associated tables.
Where R1 and R2 are two relations, Theta is join conditiion
Non EquiJoin

• The SQL NON EQUI JOIN uses


comparison operator instead of
the equal sign like >, <, >=,
<= along with conditions.
Natural Join:
• The SQL NATURAL JOIN is a type of EQUI JOIN and is structured in
such a way that, columns with the same name of associated tables
will appear once only.
• The associated tables have one or more pairs of identically named
columns.
• The columns must be the same data type.
• Don’t use ON clause in a natural join.
• There is one significant difference between INNER JOIN and
NATURAL JOIN is the number of columns returned.
Sub Queries

Correlated Queries:
Correlated subqueries are used for row-by-row
processing. Each subquery is executed once for every
row of the outer query.
• An SQL Subquery, is a SELECT query within another
query. It is also known as Inner query or Nested
query and the query containing it is the outer query.
• The outer query can contain the SELECT, INSERT,
UPDATE, and DELETE statements. We can use the
subquery as a column expression, as a condition in SQL
clauses, and with operators like =, >, <, >=, <=, IN,
BETWEEN, etc.
• Rules:
• Subqueries must be enclosed within parentheses.
• Subqueries can be nested within another subquery.
• A subquery must contain the SELECT query and the
FROM clause always.
Correlated Query example
Relational Calculus

• Relational Calculus in database management system


(DBMS) is all about "What you want ?".
• Relational calculus does not tell us how to get the
results from the Database.
• Procedural Language - Those Languages which
clearly define how to get the required results from the
Database are called Procedural Language. Relational
algebra is a Procedural Language.
• Declarative Language - Those Language that only
cares about What to get from the database without
getting into how to get the results are called
Declarative Language. Relational Calculus is a
Declarative Language.
Tuple relational calculus:
• Tuple Relational Calculus in DBMS uses a tuple
variable (t) that goes to each row of the table and
checks if the predicate is true or false for the given row.
• Depending on the given predicate condition, it returns
the row or part of the row.
⚫ A nonprocedural query language, where each query
is of the form
{t | P (t ) }
⚫ It is the set of all tuples t such that predicate P is
true for t
⚫ t is a tuple variable, t [A ] denotes the value of tuple t
on attribute A
⚫ t ∈ r denotes that tuple t is in relation r
⚫ P is a formula similar to that of the predicate
calculus
Ref: Database System concepts, 5 th edition, Silberschatz, et al.
Predicate calculus formula

1.Set of attributes and constants


2.Set of comparison operators: (e.g., <, ≤, =, ≠, >, ≥)
3.Set of connectives: and (∧), or (v)‚ not (¬)
4.Implication (⇒): x ⇒ y,
5.Set of quantifiers:
▶ ∃ t ∈ r (Q (t )) ≡ ”there exists” a tuple in t in
relation r
such that predicate Q (t ) is true
▶ ∀t ∈ r (Q (t )) ≡ Q is true “for all” tuples t in
relation r
Example Queries?

Relations for queries:

Book_scheme(Acc_No, Year_pub, Title);

User_scheme(CardNo, B_Name,B_addr);

Supplier_scheme(S_name,S_addr);

B_by_Scheme(Acc_No, Card_No, DOI);

S_by_Scheme(AccNO,S_name,Price,DOS);
Query:
1. Select all books published in the year of 1991.

Query:
2. Select title of books published in the year of 1991.

Query:
3. Get the name of all suppliers such that each supplier must supplied
at least one book which prize > 1000.
Query:
4. Find all the barrowers and their address for who have issued a
book on 14-08-2022.
Safety of Expressions

⚫ It is possible to write tuple calculus expressions that


generate infinite relations.
⚫ For example, { t | ¬ t ∈ r } results in an infinite relation if
the domain of any attribute of relation r is infinite
⚫ To guard against the problem, we restrict the set of
allowable expressions to safe expressions.
⚫ An expression {t | P (t )} in the tuple relational calculus
is safe if every component of t appears in one of the
relations, tuples, or constants that appear in P
◦ NOTE: this is more than just a syntax condition.
● E.g. { t | t [A] = 5 ∨ true } is not safe --- it defines an
infinite set with attribute values that do not appear
in any relation or tuples or constants in P.
Domain relational calculus:
• Domain Relational Calculus uses domain Variables to get the column
values required from the database based on the predicate expression


or condition.
A nonprocedural query language equivalent in
power to the tuple relational calculus
⚫ Each query is an expression of the form:

{ < x1, x2, …, xn > | P (x1, x2, …, xn)}

◦ x1, x2, …, xn represent domain variables


◦ P represents a formula similar to that of the
predicate calculus
Query:
1. Select all from s_by_scheme which price > 1000.

2. As in the previous query, but output only the AccNo attribute


value

3. Find all barrower names where date of issue is on 18-11-22


Safety of Expressions

The expression:
{ < x1, x2, …, xn > | P (x1, x2, …, xn )}

is safe if all of the following hold:


1. All values that appear in tuples of the expression are values
from dom (P ) (that is, the values appear either in P or in a
tuple of a relation mentioned in P ).
2. For every “there exists” subformula of the form ∃ x (P1(x )),
the subformula is true if and only if there is a value of x in
dom (P1) such that P1(x ) is true.
3. For every “for all” subformula of the form ∀ x (P1 (x )), the
subformula is true if and only if P1(x ) is true for all values x
from dom (P1).
Introduction to SQL
Introduction to SQL
Structured Query Language (SQL), as we all know, is the
database language by the use of which we can perform
certain operations on the existing database, and also
we can use this language to create a database.

SQL commands are like instructions to a table. It is used


to interact with the database with some operations. It is
also used to perform specific tasks, functions, and
queries of data. SQL can perform various tasks like
creating a table, adding data to tables, dropping the
table, modifying the table, set permission for users.
DDL commands:

Create: This command is used to create the database or its objects


(like table, index, function, views, store procedure, and triggers).
a. Create table syntax
create table table_name(column1 datatype(size), column2
datatype(size));
b. Create view syntax:
create view ciew_name as select query;

Drop: This command is used to delete objects from the database.


Drop table Table_name;
Drop view view_name;
Alter: This is used to alter the structure of the database.
alter table table_name add column_name Datatype;
alter table table_name drop column column_name;
alter table table_name modify column_name Datatype;
Truncate: This is used to remove all records from a table, including all
spaces allocated for the records are removed.

TRUNCATE TABLE table_name;


DROP TRUNCATE

In the drop table data and its definition is deleted It preserves the structure of the table for further use
with their full structure. exist but deletes all the data.

Drop is used to eliminate existing complications and


Truncate is used to eliminate the tuples from the
fewer complications in the whole database from the
table.
table.

Integrity constraints get removed in the DROP Integrity constraint doesn’t get removed in the
command. Truncate command.

Since the structure does not exist, the View of the Since the structure exists, the View of the table exists
table does not exist in the Drop command. in the Truncate command.

Drop query frees the table space complications from This query does not free the table space from
memory. memory.

It is slow as there are so many complications It is fast as compared to the DROP command as there
compared to the TRUNCATE command. are fewer complications.
Comment:
This is used to add comments to the data dictionary.
Comments are used to explain sections
of SQL statements or to prevent SQL statements from
being executed.

Comments can be written in the following three


formats:
Single-line comments (--)
Multi-line comments (/* comment lines */)
In-line comments (/* comment */)

Rename: This is used to rename an object existing in


the database.
Select: It is used to retrieve data from the database.
• The SELECT Statement in SQL is used to retrieve or fetch data from
a database.
Syntax: SELECT column1, column2,...columnN FROM table_name.

Alias for Columns and Table


• Alias makes a column more readable in the result set.
SELECT EmpId "Employee Id", FirstName AS Name FROM Employee;

Operators in SELECT Statement


You can specify the operators in the select statement to perform
some action on the column value. For example, the + operator in MS
SQL Server and || operator in PostgreSQL, MySQL, and Oracle
database concatenates string values or adds numeric values.

SELECT EmpId, FirstName + ' ' + LastName AS "Full Name" FROM


Employee;
FROM Clause
The SELECT statement must have the FROM clause.
The FROM clause is used to list down table names from
which we want to select data and specify joins between
those tables.
Ex: SELECT * FROM Employee, Deparatment;
SELECT Employee.*, Department.* FROM Employee,
Deparatment;

SELECT emp.*, dept.* FROM Employee emp,


Deparatment dept;

SELECT emp.FirstName, dept.DipartmentName FROM


Employee emp, Deparatment dept;
WHERE Clause
• The SELECT query can also have an optional WHERE clause to filter
the data. The WHERE clause can include one or more boolean
conditions to filter out data of the tables.
• The WHERE clause always comes after the FROM clause and before
GROUP BY, HAVING, and ORDER BY clauses.

• SELECT column1, column2,...columnN


FROM table_name
WHERE conditions

EX: between operator


SELECT * FROM Employee WHERE Salary BETWEEN 15000 AND
20000;
The following operators can be used in the WHERE
conditions.
Operator Description
= Equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
<> or != Not equal. In some databases, the != is used to compare
values which are not equal.

BETWEEN Between some range


LIKE Search for a pattern
IN To specify multiple possible values for a column
GROUP BY Clause

• The GROUP BY clause is used to get the summary data


based on one or more groups. The groups can be
formed on one or more columns. For example, the
GROUP BY query will be used to count the number of
employees in each department, or to get the
department wise total salaries.
• You must use the aggregate functions such as COUNT(),
MAX(), MIN(), SUM(), AVG(), etc., in the SELECT query.
The result of the GROUP BY clause returns a single row
for each value of the GROUP BY column.
SELECT column1, column2,...columnN FROM table_name
[WHERE]
[GROUP BY column1, column2...columnN]
[HAVING]
[ORDER BY]

Characterstics:
The GROUP BY clause is used to form the groups of
records.
The GROUP BY clause must come after the WHERE
clause if present and before the HAVING clause.
The GROUP BY clause can include one or more
columns to form one or more groups based on that
columns.
Only the GROUP BY columns can be included in the
SELECT clause. To use other columns in the SELECT
HAVING Clause
The HAVING clause includes one or more conditions that should be
TRUE for groups of records. It is like the WHERE clause of the GROUP
BY clause. The only difference is that the WHERE clause cannot be
used with aggregate functions, whereas the HAVING clause can use
aggregate functions.

SELECT column1, column2,...columnN


FROM table_name
[WHERE]
[GROUP BY column1, column2...columnN]
[HAVING conditions]
[ORDER BY]
• The HAVING clause is used to filter out grouping
records.
• The HAVING clause must come after the GROUP BY
clause and before the ORDER BY clause.
• The HAVING clause can include one or more conditions.
• The HAVING condition can only include columns that
are used with the GROUP BY clause. To use other
columns in the HAVING condition, use the aggregate
functions with them.

ORDER BY CLUASE:
• The ORDER BY clause can be used in the SELECT query
to sort the result in ascending or descending order of
one or more columns.
SELECT column1, column2,...columnN FROM table_name [WHERE]
[GROUP BY] [HAVING] [ORDER BY column(s) [ASC|DESC]]

The ORDER BY clause is used to get the sorted records on one or more
columns in ascending or descending order.
The ORDER BY clause must come after the WHERE, GROUP BY, and
HAVING clause if present in the query.
Use ASC or DESC to specify the sorting order after the column name. Use
ASC to sort the records in ascending order or use DESC for descending
order. By default, the ORDER BY clause sort the records in ascending
order if the order is not specified.
EX1:
SELECT EmpId, FirstName, LastName FROM Employee
ORDER BY FirstName DESC;
EX2:
SELECT * FROM Employee ORDER BY DeptId,
FirstName;
Views

• A view is a “virtual” table whose data is the result of


a stored query.

Advantages:
• Simplifying data retrieval.
• Maintaining logical data independence.
• Implementing data security.
Syntax:
CREATE VIEW view_name AS SELECT columns
FROM tables
WHERE conditions;
Update view:
CREATE OR REPLACE VIEW view_name AS
SELECT columns
FROM table
WHERE conditions;

Retrieving information from View:

Select * from View;

Drop View:

DROP VIEW view_name;


Triggers

• A trigger is a statement that the system executes


automatically as a side effect of a modification to the
database.
1. Specify when a trigger is to be executed. This is
broken up into an event that causes the trigger to be
checked and a condition that must be satisfied for
trigger execution to proceed.
2. Specify the actions to be taken when the trigger
executes.

once we enter a trigger into the database, the database


system takes on the responsibility of executing it
Types of triggers:
Before Insert: It is activated before the insertion of
data into the table.
After Insert: It is activated after the insertion of data
into the table.
Before Update: It is activated before the update of
data in the table.
After Update: It is activated after the update of the
data in the table.
Before Delete: It is activated before the data is
removed from the table.
After Delete: It is activated after the deletion of data
from the table.
A trigger is called a special procedure because it
cannot be called directly like a stored procedure. The
main difference between the trigger and procedure is
that a trigger is called automatically when a data
modification event is made against a table. In contrast,
a stored procedure must be called explicitly.
• Triggers are of two types according to
the SQL standard: row-level triggers and statement-
level triggers.
• Row-Level Trigger: It is a trigger, which is activated
for each row by a triggering statement such as insert,
update, or delete.
• Statement-Level Trigger: It is a trigger, which is fired
once for each event that occurs on a table regardless of
Limitations and Syntax:
Triggers are invoked and executed invisibly from the
client application. Therefore, it isn't easy to
troubleshoot what happens in the database layer.
Triggers may increase the overhead of the database
server.
Trigger Activation Time: BEFORE | AFTER
Trigger Event: INSERT | UPDATE | DELETE
CREATE TRIGGER trigger_name
(AFTER | BEFORE) (INSERT | UPDATE | DELETE)
ON table_name FOR EACH ROW
BEGIN
--variable declarations
--trigger code
Cursors

• Cursor is a Temporary Memory or Temporary Work


Station. It is Allocated by Database Server at the Time of
Performing DML(Data Manipulation Language)
operations on the Table by the User. Cursors are used to
store Database Tables.
There are 2 types of Cursors: Implicit Cursors, and
Explicit Cursors. These are explained as following
below.
Implicit Cursors: Implicit Cursors are also known as
Default Cursors of SQL SERVER. These Cursors are
allocated by SQL SERVER when the user performs DML
operations.
Explicit Cursors: Explicit Cursors are Created by Users
Operations to be performed using Explicit cursors:
• Declare (declare c1 cursor is select sno from student)
• Open (open c1)
• Fetch
• FETCH FIRST FROM c1
• FETCH LAST FROM c1
• FETCH NEXT FROM c1
• FETCH PRIOR FROM c1
• FETCH ABSOLUTE 7 FROM c1
• FETCH RELATIVE -2 FROM c1
• Close (close c1)

Deallocate cursor memory: (deallocate c1)


Implicit cursor:
An implicit cursor is a cursor that is automatically
created by PL/SQL when you execute a SQL statement.
You don’t need to declare or open an implicit cursor
explicitly. Instead, PL/SQL manages the cursor for you
behind the scenes.

In PL/SQL, when we perform INSERT,


UPDATE or DELETE operations, an implicit cursor is
automatically created. This cursor holds the data to be
inserted or identifies the rows to be updated or deleted.
SQL cursor has several useful attributes
%FOUND is true if the most recent SQL operation affected at least one
row.
%NOTFOUND is true if it didn’t affect any rows.
%ROWCOUNT is returns the number of rows affected.
%ISOPEN checks if the cursor is open.

Advantages:
1. Cursors allow us to process data row-by-row.
2. Cursors allow us to iterate over a result set
multiple times, which can be useful when we need to
perform multiple operations on the same data.
3. Cursors are especially useful when processing data
from multiple tables where the relationships are not
straightforward.
Limitations:
1. When processing data, it imposes locks on a subset
or the entire table.
2. The cursor updates table records one row at a time,
which slows down its performance.
3. Another factor that influences cursor speed is the
quantity of rows and columns brought into the cursor.
Sample cursor:
DECLARE
S_N STUDENT2.SNO%TYPE;
CAT STUDENT2.CATEGORY%TYPE;
CURSOR C2 IS SELECT SNO,CATEGORY FROM STUDENT2;
BEGIN
OPEN C2;
LOOP
FETCH C2 INTO S_N, CAT;
EXIT WHEN C2%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(S_N||' '||CAT);
END LOOP;
CLOSE C2;
END;
Embedded SQL

• The SQL standard defines embeddings of SQL in a


variety of programming languages, such as C, C++,
Cobol, Pascal, Java, PL/I, and Fortran.
• A language in which SQL queries are embedded is
referred to as a host language.
• The SQL structures permitted in the host language
constitute embedded SQL.
• Programs written in the host language can use the
embedded SQL syntax to access and update data stored
in a database.
• An embedded SQL program must be processed by a
special preprocessor prior to compilation. (Ex: slpp file
for c or c++).
• The preprocessor replaces embedded SQL requests
with host-language declarations and procedure calls
that allow runtime execution of the database accesses.
• Then the resulting program is compiled by the host
language compiler.
• The programmer must have access to database from
general purpose programming languages for two
reasons:
1. SQL does not provide full expressive power as
general purpose language. Few functionalities
can not be done through sql.
2. Non declarative actions such as printing the
report, sending the results to GUI
• To identify embedded SQL requests to the preprocessor, we use
the EXEC SQL statement;

EXEC SQL <embedded SQL statement > END-EXEC


• The exact syntax for embedded Sql requests depends on the
language in which SQL is embedded.
• For instance, a semicolon is used instead of END-EXEC when SQL
is embedded in C.
• The Java embedding of SQL (called SQLJ) uses the syntax.

# SQL { <embedded SQL statement > };


• Variables of the host language can be used within embedded SQL
statements, but they must be preceded by a colon (:) to distinguish
them from SQL variables.
• Before executing any SQL statements, the program must first
connect to the database. This is done using.
EXEC SQL connect to server user user-name END-EXEC
• To write a relational query, we use the declare cursor statement.
• The program must use the open and fetch commands to obtain
the result tuples.
• EXEC SQL
declare c cursor for
select customer-name, customer-city
from depositor, customer, account
where depositor.customer_name = customer.
customer_name and
account.account_number = depositor.account_number and
account.balance > :amount
END-EXE
• The open statement for our sample query is as follows:
EXEC SQL open c END-EXE
• The query has a host-language variable (:amount); the
query uses the value of the variable at the time the
open statement is executed.
• An embedded SQL program executes a series of fetch
statements to retrieve tuples of the result.
• The fetch statement requires one host-language
variable for each attribute of the result relation.
EXEC SQL fetch c into :cn,:cc END-EXE
• When no further tuples remain to be processed, the
variable SQLSTATE in the SQLCA is set to '02000'
(meaning "no data").
• We must use the close statement to tell the database
system to delete the temporary relation that held the
result of the query.
EXEC SQL close c END-EXEC
NO SQL Database:

Databases can be divided in 3 types:

• RDBMS (Relational Database Management System)


• OLAP (Online Analytical Processing)
• NoSQL (recently developed database)

NoSQL database doesn't use tables for storing data. It is


generally used to store big data and real-time web
applications.
Advantages of NO SQL Databases:

• Handle large volumes of data at high speed with a scale-


out architecture.
• Store unstructured, semi-structured, or structured data.
• Enable easy updates to schemas and fields.
• Be developer-friendly.
• Take full advantage of the cloud to deliver zero
downtime.

You might also like