Database Management System - CS3492 - Notes - Unit 1 - Relational Databases
Database Management System - CS3492 - Notes - Unit 1 - Relational Databases
1st Semester
Professional English II Discrete Mathematics
Professional English I
Statistics and Numerical
Methods Digital Principles and
Matrices and Calculus
Computer Organization
Engineering Graphics
Engineering Physics
Foundation of Data
Physics for Information
Science
Engineering Chemistry Science
Elective-Management
Professional Elective II
Professional Elective IV
www.Poriyaa
n.in
UNIT 1
RELATIONAL DATABASES
https://play.google.com/store/apps/details? 1
www.Poriyaa
n.in
CS8492 DATABASE MANAGEMENT SYSTEMS
UNIT - 1
INTRODUCTION TO DBMS
INTRODUCTION
Data
Data is a raw material. It can be any character, word, number, date etc.
Database
Database is a collection of inter-related data which is used to retrieve, insert and delete
the data efficiently. For example, consider employee database consists of following columns-
eno, ename and salary.
https://play.google.com/store/apps/details?id=com.poriyaan.poriyaan 2
DEPT. OF
www.Poriyaa
n.in
1. Data Redundancy:
Data redundancy and inconsistency. Since different programmers create the files and
application programs over a long period,the same information may be duplicated in different
files.This leads to data redundancy .
Example: A student is having record in college office and in computer department. Then his ,
telephone number, address will be same in both the departments. This redundancy leads to higher
storage and access cost.
In addition,it may lead to data inconsistency, that is, the various copies of the same data may no
longer agree.
Example :A changed student address may be reflected in the computer department records but
not in the college office.
2. Difficulty in Accessing Data: Accessing data is not convenient and efficient in file
conventional processing system. More responsive data-retrieval systems are required for general
use.
Example: one of the bank officers needs to find out the names of all customers who live within
a particular postal- code area. If there is no application program for this means, the officer has 2
alternatives: 1. Preparing the list manually from the list of all customers. 2. Ask system
programmer to write the necessary application programs.
3. .Data isolation. Because data are scattered in various files, and files may be in different
formats, writing new application programs to retrieve the appropriate data is difficult.
4. Integrity Problems: The data values stored in the database must satisfy certain types of
consistency constraints.
https://play.google.com/store/apps/details? 3
www.Poriyaa
n.in
Example: Suppose the university maintains an account for each department, and records the
balance amount in each ac-count. Suppose also that the university requires that the account
balance of a department may never fall below zero. However, when new constraints are added, it
is difficult to change the programs to enforce them.
6. Atomicity Problems: Any operation on database must be atomic, (i.e.) it must happen
in its entirely or not at all.
Example: If you are buying a ticket from railway and you are in the process of money
transaction. Suddenly, your internet got disconnected then you may or may not have paid for the
ticket. If you have paid, then your ticket will be booked and if not then you will not be charged
anything. That is called consistent state, means you have paid or not.
Example: Consider an operation to debit (withdrawal) an account. The program reads the old
balance, calculates the new balance, and writes new balance back to database. Suppose an
account has a balance of Rs. 5000. Now, a concurrent withdrawal of Rs. 1000 and Rs. 2000 may
leave the balance Rs. 4000 or Rs. 3000 depending upon their completion time rather than the
correct value of Rs. 2000.
8. Security Problems: Database should be accessible to users in limited way. Not every user
of the database system should be able to access all the data.
Example : In a university, payroll personnel need to see only that part of the database that has
financial information. They do not need access to information about academic records. To
overcome these difficulties, the database management system (DBMS) was developed.
https://play.google.com/store/apps/details? 4
www.Poriyaa
n.in
VIEWS OF DATA
Data Abstraction
Database systems are made-up of complex data structures. To ease the user interaction
with database, the developers hide internal irrelevant details from users. This process of hiding
irrelevant details from user is called data abstraction.
view
level
Logical Level
Physical Level
https://play.google.com/store/apps/details? 5
www.Poriyaa
n.in
❖ Database administrators, who must decide what information to keep in the database, use
the logical level of abstraction.
Many high-level programming languages support the notion of a structured type. For
example, we may describe a record as follows:
ID : char (5);
name : char (20);
dept name : char (20);
salary : numeric (8,2);
end;
This code defines a new record type called instructor with four fields. Each field has a
name and a type associated with it. A university organization may have several such
record types, including
department, with fields dept name, building, and budget
course, with fields course id, title, dept name, and credits
student, with fields ID, name, dept name, and tot cred
https://play.google.com/store/apps/details? 6
www.Poriyaa
n.in
At the logical level, each such record is described by a type definition, as in the
previous code segment, and the interrelationship of these record types is defined as
well. Programmers using a programming language work at this level of abstraction.
Similarly, database administrators usually work at this level of abstraction.
At the view level, several views of the database are defined, and a database user
sees some or all of these views. In addition to hiding details of the logical level of the
database, the views also provide a security mechanism to prevent users from accessing
certain parts of the database.
Instance:
Schema:
The overall design of the database is called the database schema.. Schema is of three
types: Physical schema, logical schema and view schema.
Application programs are said to exhibit physical data independence if they do not
depend on the physical schema, and thus need not be rewritten if the physical schema changes.
DATA MODELS
Introduction
Data Model is a collection of conceptual tools for describing data, data relationships, data
semantics and consistency constraints.
https://play.google.com/store/apps/details? 7
www.Poriyaa
n.in
It is a collection of conceptual tools for describing data, data relationships and data
constraints. There are various object-based models like,
a. Entity-Relationship Model
b. Object Oriented Model
a. Entity-Relationship Model
❖ The entity-relationship (E-R) data model uses a collection of basic objects, called
entities, and relationships among these objects.
❖ An entity is a “thing” or “object” in the real world that is distinguishable from
other objects. The entity-relationship model is widely used in database design.
❖ Object-oriented data model that can be seen as extending the E-R model with
notions of encapsulation, methods , and object identity.
❖ The object-relational data model combines features of the object-oriented data
model and relational data model.
The record based model describes the data structures and access techniques of a DBMS.
There are three types of record-based models viz.
a) Relational Model
b) Hierarchical Model
c) Network Model
a) Relational Model.
❖ The relational model uses a collection of tables to represent both data and the
relationships among those data.
❖ Each table has multiple columns, and each column has a unique name.
❖ Tables are also known as relations.
❖ The relational model is an example of a record-based model.
https://play.google.com/store/apps/details? 8
www.Poriyaa
n.in
User user
Client
Network network
application server
database system
database system
Server
Fig.1.3.(a) Two-tier
architeture (b) Three-tier architecture
https://play.google.com/store/apps/details? 9
www.Poriyaa
n.in
Database applications are usually partitioned into two or three parts, as in Figure
1.1. In a two-tier architecture, the application resides at the client machine, where it
invokes database system functionality at the server machine through query language
statements. Application program interface standards like ODBC and JDBC are used for
interaction between the client and the server.
The application server in turn communicates with a database system to access data.
The business logic of the application, which says what actions to carry out under what
conditions, is embedded in the application server, instead of being distributed across
multiple clients. Three-tier applications are more appropriate for large applications, and
for applications that run on the World Wide Web.
Components of DBMS
a) Storage Manager
b) Query Processor
c) Database Users and Administrators
https://play.google.com/store/apps/details? 10
www.Poriyaa
n.in
The storage manager translates the various DML statements into low level file system
commands. Thus the storage manager is responsible for storing, retrieving and updating the data
in the database.
https://play.google.com/store/apps/details? 11
www.Poriyaa
n.in
(1) Authorization and Integrity Manager: which tests for the satisfaction of integrity
constraints and checks the authority of users to access data.
(2) Transaction Manager: which ensures that the database remains in a consistent
state when the system failures and that concurrent transaction executions
proceed without conflicting.
(3) File Manager: which manages the allocation of storage space on disk and data
structures used to store that information’s.
(4) Buffer Manager: which is responsible for fetching data from disk into main
memory.
❖ Data dictionary, which stores meta data about the structure of the database,
in particular schema of the database.
❖ Indices, which can provide fast access to data items. Hashing technique is
used for accessing.
b) Query Processor
DDL Interpreter: which interprets DDL statements (i.e., converts DDL statement
into low level data).
❖ DML Compiler: Which translates DML statements into an low level instructions
that the query evaluation engine understands. Also performs Query optimization.
https://play.google.com/store/apps/details? 12
www.Poriyaa
n.in
c) Database Users
❖ Sophisticated users: Interact with the system through the database query
language.
❖ Naive Users: Interact with the system by invoking one of the permanent
applications.
❖ Database Administrator: A person who has such central control over the system
is called a database administrator (DBA).
https://play.google.com/store/apps/details? 13
www.Poriyaa
n.in
✓ Ensuring that enough free disk space is available for normal operation
A single entry in a table is called a record or row. A record in a table represents set of
related data. For example, the above Employee table has 4 record. Following is an example of
single record.
1 Baskar 34 13000
A table consists of several records (row); each record can be broken into several smaller
entities known as fields. The above employee table consists of four fields Emp_id, Name, Age
and Salary.
In relational table, a column is a set of value of a particular type. The term attribute is
also used to represent a column. For example, in Employee table, Name is a column that
represent names of employee.
https://play.google.com/store/apps/details? 14
www.Poriyaa
n.in
Name
Baskar
Dharshan
Prajan
Pradeep
E. F. Codd’s Rule
These rules were defined by E.F. Codd’s in a paper published in 1985. They specify what a
relational database must support in order to be relational.
Rule 1: The information Rule
“All information in a relational data base is represented explicitly at the logical level and in
exactly one way - by values in tables."
All information including table names, column names and column data types
should be available in some table with in the database.
Data are represented only one way: as values within columns within rows.
“Each and every datum (atomic value) in a relational data base is guaranteed to be
logically accessible by resorting to a combination of table name, primary key value and column
name."
Every value can be accessed by providing table name, column name and key.
All data are uniquely identified and accessible via this identity.
Most RDBMS do not make the definition of the primary key mandatory and are
deficient to that extent
https://play.google.com/store/apps/details? 15
www.Poriyaa
n.in
"Null values (distinct from the empty character string or a string of blank characters and
distinct from zero or any other number) are supported in fully relational DBMS for representing
missing information and inapplicable information in a systematic way, independent of data type."
Separate handling of missing and/or non applicable data.
“The data base description is represented at the logical level in the same way as-ordinary
data, so that authorized users can apply the same relational language to its interrogation as they
apply to the regular data."
Catalog (data dictionary) can be queried by authorized users as part of the database.
A relational system may support several languages and various modes of terminal use (for
example, the fill-in-the-blanks mode). However, there must be at least one language whose
statements are expressible, per some well-defined syntax, as character strings and that is
comprehensive in supporting all the following items
Data Definition
View Definition
Integrity Constraints
All views that are theoretically updatable are also updatable by the system.
Rule 7: High-level insert, update and delete
The capability of handling a base relation or a derived relation as a single operand applies
not only to the retrieval of data but also to the insertion, update and deletion of data.
https://play.google.com/store/apps/details? 16
www.Poriyaa
n.in
"Application programs and terminal activities remain logically unimpaired whenever any
changes are made in either storage representations or access methods."
Changes to the logical level (tables, columns, rows, and so on) must not require a change
to an application based on the structure. Logical data independence is more difficult to achieve
than physical data independence.
“Integrity constraints specific to a particular relational data base must be definable in the
relational data sub-language and storable in the catalog, not in the application programs."
The data manipulation sub language of an RDBMS must enable application programs and
queries to remain logically unchanged whether & whenever data is physically centralized or
distributed.
If the system provides a low-level (record-at-a-time) interface, then that interface cannot
be used to subvert the system, for example, bypassing a relational security or integrity constraint.
All the database access must be controlled through the DBMS so that the integrity of the
database cannot be compromised without the knowledge of the user.
https://play.google.com/store/apps/details? 17
www.Poriyaa
n.in
KEYS
A key allows us to identify a set of attributes and thus distinguishes entities from each
other. Keys also help to uniquely identify relationships, and thus distinguish relationships from
each other.
Different types of keys are:
Super key
Candidate key
Primary key
Foreign key
1. Super key: A superkey is a set of one or more attributes that, taken collectively, allow
us to identify uniquely a tuple in the relation. For example, consider the student relation.
https://play.google.com/store/apps/details? 18
www.Poriyaa
n.in
RELATIONAL ALGEBRA
1.6.1 Introduction
Query language is a language in which user requests information from the database.
Categories
(i) Procedural - Eg., - Relational algebra.
(ii) Non-procedural - Eg., - Relational calculus.
(i) Procedural language: The user instructs the system to perform a sequence
of operations on the database to compute the desired result.
Example: Relational algebra.
(ii) Non-procedural language: The user describes the desired information
without giving a specific procedure for obtaining that information.
Example: Relational calculus.
Relational Algebra
• Procedural language.
• It consists of set of operations that take one or more relations as input and produces
new relation as output.
• The operations can be divided into
❖ Basic operations Select, project, union, rename, set difference & cartesian
product.
❖ Additional operations that can be expressed in terms of basic
operations Set intersection, natural join, division and assignment.
❖ Extended operations Aggregate operations and outer join.
Basic Operations
(a) The select operation ( )
It is used to select a subset of the tuples from a relation that satisfy a selection
condition.
Syntax
Example
Select those tuples of the loan relation where the branch is “Perriridge”.
https://play.google.com/store/apps/details? 19
www.Poriyaa
n.in
Syntax
Example
List the loan-no,amount from the loan relation.
loan-number amount
L-11 900
L-14 1500
L-15 1500
L-16 1300
L-17 1000
L-23 2000
L-93 500
Example
Find those customers who live in “Rye”
customer-name
Curry
Smith
https://play.google.com/store/apps/details? 20
www.Poriyaa
n.in
R S
Example
Find the names of customers who have either an account or a loan or both.
Names of all customers with a loan is
πcustomer-name (borrower)
πcustomer-name (depositor)
customer-name
Adams
Curry
Hayes
Johnson
Jones
Lindsay
Smith
Turner
Williams
Syntax
R–S
Example
customer-name
Johnson
Lindsay
Turner
https://play.google.com/store/apps/details? 21
www.Poriyaa
n.in
Defined as
r s = { tq | t r and q s}
For Example
Relation r
Relation s r s
A B C D E A B C D E
1 10 a 1 10 a
2 10 a 1 10 a
20 b 1 20 b
10 b 1 10 b
2 10 a
2 10 a
2 20 b
2 10 b
returns the result of expression E under the name X, and with the attributes
renamed to A1, A2, A3, ..., An.
For example, consider the Book relation with attributes Title, Author,
Year and Price. The rename operator is used on Book relation as follows.
Additional Operations
(g) Set intersection operation ( )
o Notation used is r s.
https://play.google.com/store/apps/details? 22
www.Poriyaa
n.in
Example
Consider relation r, s
r s rs
A B A B A B
2 2 2
2 3
1
Example
R = (A, B, C, D)
S = (E, B, D)
Result schema = (A, B, C, D,
E) r s is defined as
https://play.google.com/store/apps/details? 23
www.Poriyaa
n.in
r
s
A B C D B D E
1 a 1 a
2 a 3 a
4 b 1 a
1 a 2 b
2 b 3 b
r s
A B C D E
1 a
1 a
1 a
1 a
2 b
r s t / t R S(r) u S(tu r)
For Example:
Relation r, s
https://play.google.com/store/apps/details? 24
www.Poriyaa
n.in
r
s rs
A B B A
1 1
2 2
3
1
1
1
3
4
6
1
2
(j) Assignment Operation ( )
• The assignment operation ( ) provides a convenient way to express complex queries.
• Write query as a sequential program consisting of a series of assignments
followed by an expression where value is displayed as a result of the query.
• Assignment must always be made to a temporary relation variable.
Example: Write r ÷ s as
temp 1 RS r
temp 2
RS temp1 S r
result = temp 1 – temp 2
• The result to the right of the is assigned to the relation variable on the left of
the .
• May use variables in subsequent expressions.
Extended Relational-Algebra Operations
Generalized projection
Outer join
Aggregate functions.
(a) Generalized Projection
• Extends the projection operation by allowing arithmetic functions to be used in the
projection list.
(E). E is any Relational algebra expression.
F1,F2 ..., Fn
• Each of F1, F2, ..., Fn are arithmetic expressions involving constants and attributes
in the schema of E.
https://play.google.com/store/apps/details? 25
www.Poriyaa
n.in
• Given relation credit (customer-name, limit, credit - balance) find how much
more each person can spend:
customer_name , limit_credit_balance (credit)
Relation r
A B C
O/P of sum(c) (r)
7
7 sum(c)
3 27
10
https://play.google.com/store/apps/details? 26
www.Poriyaa
n.in
Inner Join ( )
1.8.3.1 Deletion
In relational algebra, a deletion is expressed by
r r–E
where,
r is a relation and
E is a relational algebra query.
Example
Delete all of Smith’s account records.
depositor depositor - = (depositor )
customer.name = “Smith”
Insertion
https://play.google.com/store/apps/details? 27
www.Poriyaa
n.in
To insert data into a relation, we either a tuple to be inserted or write a query whose result
is a set of tuples to be inserted.
Insertion is expressed by
R rUE
Where,
r is a relation and
E is a relational-algebra expression.
Example
To insert a fact that Smith has $1200 in account A - 973 at the Perryridge branch.
account account U {(A-973, “Perryridge”, 1200)}
depositor depositor U {(“Smith”; A-973)}
Updation
To change a value in a tuple without changing all values in the tuples, the generalized
projection operator is used.
r F1,F2 … Fn
(r)
where each Fi is either the ith attribute of r, if the ith attribute is not updated, or, if the
attribute is to be updated. Fi is an expression, involving only constants and the attributes of r,
which gives the new value for the attribute.
If we want to select some tuples from r and to update only them, we can use the following
expression; here, p denotes the selection condition that chooses which tuples to update:
R F1,F2 … Fn
( (r))U(r
p
- (r))
p
Example
To illustrate, the use of the update operation, suppose that interest payments are being
made, and that all balances are to be increased by 5 percent.
account (account)
account-number, branch-name, balance * 1.05
Now suppose that accounts with balances over $10,000 receive 6 percent interest,
whereas all others receive 5 percent.
account AN, BN, balance * (
balance>10000
1.06 (account))
https://play.google.com/store/apps/details? 28
www.Poriyaa
n.in
SQL FUNDAMENTALS
Structured Query Language (SQL) is the standard common set used to communicate with
the relational database management systems. All tasks related to relational data management—
creating tables, querying the database for information, modifying the data in the database,
deleting them, granting access to users, and so on — can be done using SQL.
Advantages of SQL
❖ SQL is a high level language that provides a greater degree of abstraction than
procedural languages. It is so fashioned that the programmer can specify what data
is needed but need not specify how to retrieve it. SQL is coded without embedded
data-navigational instructions. This will be taken care of by the DBMS.
❖ SQL enables the end-users and systems personnel to deal with a number of
database management systems where it is available. Increased acceptance and
availability of SQL are also in its favor.
❖ Applications written in SQL can be easily ported across systems. Such porting
could be required when the underlying Database Management System needs to be
upgraded or changed.
❖ The language while being simple and easy to learn can handle complex situations.
Parts of SQL
https://play.google.com/store/apps/details? 29
www.Poriyaa
n.in
in the database.
❖ View definition. The SQL DDL includes commands for defining views.
❖ Transaction control. SQL includes commands for specifying the beginning and
ending of transactions.
❖ Embedded SQL and Dynamic SQL. Embedded and dynamic SQL define how
SQL statements can be embedded within general-purpose programming languages,
such as C, C++, Java, PL/I, COBOL, Pascal and Fortran.
❖ Integrity. The SQL DDL includes commands for specifying integrity constraints
that the data stored in the database must satisfy. Updates that violate integrity
constraints are disallowed.
❖ Authorization. The SQL DDL includes commands for specifying access rights to
relations and views.
❖ char(n): A fixed-length character string with user-specified length n. The full form,
character can be used instead.
❖ int: An integer (a finite subset of the integers that is machine dependent). The full
form, integer, is equivalent.
https://play.google.com/store/apps/details? 30
www.Poriyaa
n.in
❖ date: a calender date containing a (four-digit) year, month, and day of the month.
❖ time: the time of day, in hours, minutes and seconds. A variant, time(p), can be
used to specify the number of fractional digits for seconds (the default being 0). It
is also possible to store time zone information along with the time.
date ‘2001-01-24’
time ’09:30:00’
Dates must be specified in the format year followed by month followed by day, as shown.
The seconds field of time or timestamp can have a fractional part, as in the timestamp above.
We can use an expression of the form cast e as t to convert a character string (or string valued
expression) e to the type t, where t is one of date, time, or timestamp. The string must be in the
appropriate format as illustrated at the beginning of this paragraph.
To extract individual fields of a date or time value d, we can use extract (field
from d), where field can be one of year, month, day, hour, minute or second.
It is used to create a table, alter the structure of a table and also drop the table created.
Create Command
https://play.google.com/store/apps/details? 31
www.Poriyaa
n.in
Syntax
Example
Drop Command
Syntax
Example
Truncate Command
Syntax
Example
https://play.google.com/store/apps/details? 32
www.Poriyaa
n.in
Syntax
desc <tablename>;
Example
SQL>desc employee;
Insert Command
It is used to insert a new record in the database.
Syntax
insert into <tablename> values (a list of data values);
Example
SQL>create table employee (ename varchar2(10), eid number (5),
salary number(5));
SQL>insert into employee values(‘ABC’,50,1000);
Update Command
https://play.google.com/store/apps/details? 33
www.Poriyaa
n.in
Grant Command
Syntax
Example
Revoke Command
Syntax
Example
Commit command
Syntax Commit;
Rollback Command
Restores the database to last commited state. It is also use with savepoint command to
https://play.google.com/store/apps/details? 34
www.Poriyaa
n.in
Syntax
rollback to savepoint_name;
Example
rollback to Temp;
Savepoint Command
Used to temporarily save a transaction so that you can rollback to that point whenever
necessary.
Syntax
Savepoint savepoint_name;
Example
Savepoint Temp
The structure of an SQL expression consists of three clauses : select, from and where
The select clause corresponds to the projection operation of the relational algebra. It is
used to list the attributes desired in the result of a query.
The from clause corresponds to the Cartesian product operation of the relational algebra.
It lists the relations to be scanned in the evaluation of the expression.
The where clause corresponds to the selection predicate of the relational algebra. It
consists of a predicate involving attributes of the relations that appear in the from clause.
A SQL has the form
select A1,A2, …..An
where p
Ai - an attribute
https://play.google.com/store/apps/details? 35
www.Poriyaa
n.in
ri - relation
p - predicate
The query is equivalent to the relational algebra expression.
A1,A2,….. An ( p (r1 r2 ……. rm))
Tuple Variables
Tuple variables are defined in the from clause via the use of the as clause.
For example, find the customer names and their loan numbers for all customers having a
loan at some branch in the banking database.
L. loan_no = B. loan_no;
String Operations
SQL includes a string matching operator for comparisons on character strings. Patterns
are described using 2 special characters.
Example: Find the names of customers where the 1st 2 characters are ‘Ba’.
Find the names of customer where the 2nd character is ‘n’ or ‘a’.
Patterns are case sensitive, i.e., upper case characters do not match lowercase
characters, and vice versa.
https://play.google.com/store/apps/details? 36
www.Poriyaa
n.in
(b) Converting the string into upper or lower case upper or lower ( )
Order by Clause
The order by clause causes the tuples in the result of a query to appear in sorted order.
SQL>select *
from employee
order by salary;
SQL>select *
from employee
order by salary desc, eid asc;
Aggregate Functions
Aggregate functions are functions that take a collection of values as input and return a
single value as output.
value
Examples
https://play.google.com/store/apps/details? 37
www.Poriyaa
n.in
account where
https://play.google.com/store/apps/details? 38
www.Poriyaa
n.in
branch-name = “Perryridge”;
customer;
Group by clause is used to group the rows based on certain criteria. Group by is used in
conjunction with aggregate functions like sum, avg, min, max, count, etc.
group by branch_name;
Find the name of all branches where the average account balance is more than $2,000.
Null Values
Find all loan numbers which appear in the loan relation with null values for amount.
https://play.google.com/store/apps/details? 39
www.Poriyaa
n.in
from loan;
Above statement ignores all null amounts. The result is null if there is no non-
null amount.
All aggregate operations except count (*) ignore tuples with null values on
the aggregated attributes.
Nested Subqueries
Set Membership
IN
The IN connective tests for set membership, where the set is a collection of values
produced by a select clause.
https://play.google.com/store/apps/details? 40
www.Poriyaa
n.in
Example: Find all customers who have both an account and a loan at the bank.
https://play.google.com/store/apps/details? 41
www.Poriyaa
n.in
NOT IN
Example: Find all customers who have a loan at the bank but do not have an account at the
bank.
2. Set Comparison
Nested queries are used to compare sets. SQL uses various comparison operators such as
<, >, < =, > =, < >, any, all, and, some, etc. to compare sets.
Example: Find the names of all branches that have assets greater than those of atleast one
branch located in “Chennai”.
SQL also allows < some, < = some, > = some, = some, and < > some
comparisons, = some is identical to in, and < > some is identical to not in. The keyword any is
synonym to some in SQL.
SQL also allows < all, > all, < = all, > = all, = all, and < > all comparisons < > all is
identical to not in.
https://play.google.com/store/apps/details? 42
www.Poriyaa
n.in
Example: Find the names all branches that have an-assets value greater than that of each branch
in “Chennai”.
branch-city = “Chennai”);
SQL includes a feature for testing whether a subquery has any tuples
in its result.
The exists construct returns the value true if the argument subquery
is non-empty.
Example: Find all customers who have both an account and a loan at the bank.
= borrower.customer-name);
Similar to exists we can use not exists also. Find all customers who have an account at all
branches located in “Chennai”.
S. customer-name = T. customer-name));
The unique construct tests whether a subquery has any duplicate tuples in its result.
https://play.google.com/store/apps/details? 43
www.Poriyaa
n.in
Example: Find all customers who have at most one account at the “Chennai branch”.
account.branch_name = “Chennai”);
not unique construct is used for test the existence of duplicate tuples in the same manner.
Complex Queries
Complex queries are often hard or impossible to write as a single SQL block.
There are two ways for composing multiple SQL blocks to express a complex query.
1. Derived relations
SQL allows a subquery expression to be used in the from clause. If we use such an
expression, then we must give the result relation a name, and we can rename the attributes. For
renaming as clause is used.For example, find the average account balance of those branches
where the average account balance is greater than $ 2000.
Here subquery result is named branch-avg with the attributes branch-name and avg-
balance.
https://play.google.com/store/apps/details? 44
www.Poriyaa
n.in
2. With Clause
The with clause provides a way of defining a temporary view, whose definition available
only to the query in which the with clause occurs.
Consider the following query, which selects accounts with the maximum balance. If
there are many accounts with the same maximum balance, all of them are selected.
from account
max_balance.value;
Views
A view is an object that gives the user a logical view of data from an
underlying table or tables (relation or relations).
It is not desirable for all users to see the entire logical model.
• Any relation that is not part of the logical model, but is made visible
to a user as a virtual relation, is called as view.
https://play.google.com/store/apps/details? 45
www.Poriyaa
n.in
(1) Creation of
Views Syntax
Example: Create a view customer_details from customer relation with customer name and
customer-id.
We can assign names for the various columns in the view. This may be entirely different
from what has been used in the main relation.
For example,
Views can also be used for data manipulation i.e., the user can perform insert,
update, and the delete operations on the view.
When you give a view name in the update, insert, or delete statement, the
modification to the data will be passed to the underlying (main) relation.
https://play.google.com/store/apps/details? 46
www.Poriyaa
n.in
4. The select statement used for creating a view should not include distinct, group by
or having clause.
5. Select statement used for creating a view should not include subqueries.
Syntax
Example
1.10.2 Joins
A join is a query using which we can query data more than one table. Joins are the basic
of multi-table query processing in SQL. A join is a query that extracts corresponding rows from
two or more tables, views or snapshots. If the two tables used in the join have the same column
name, then the column names should be prefixed with table name followed by a period.
SELECT statement of a multi-table query must contain a filter condition that specify the
column match. The where clause is used to specify the selection condition and the join condition.
In the where clause the logical operators can also be used.
https://play.google.com/store/apps/details? 47
www.Poriyaa
n.in
Types of joins
1. Inner Join
2. Outer Join
3. Natural Join
1. Inner Join
Inner join returns the matching rows from the tables that are being joined.
i) Student(sname,place)
ii) Student_marks(sname,dept,mark)
sname mark
Prajan 700
Anand 650
Ravi 600
https://play.google.com/store/apps/details? 48
www.Poriyaa
n.in
Example 2:
2. Outer Join
When tables are joined using inner join, rows which contain matching values in the join
predicate are returned. Sometimes you may want both matching and non-matching rows returned
for the tables that are being joined. This kind of operation is known as an outer join.
An outer join is an extended form of the inner join. In this, the rows in one table having
no matching rows in the other table will also appear in the result table with nulls.
The left outer join returns matching rows from the tables being joined and also non-
matching rows from the left table in the result and places null values in the attributes that come
from the right table.
https://play.google.com/store/apps/details? 49
www.Poriyaa
n.in
Example 3
sname mark
Prajan 700
Anand 650
Ravi 600
Kumar null
Left outer join operation is computed as follows:
First compute the result of inner join as before. Then, for every tuple ‘t’ in the left hand
side relation, Student that does not match any tuple in the right-hand –side relation
Student_marks in the inner join , add a tuple ‘r’ to the result of the join: The attributes of tuple ‘r’
that are derived from the left-hand-side relation are filled with from tuple ‘t’, remaining attributes
of ‘r’ are filled with null values as shown in example 3.
The right outer join operation returns matching rows from the tables being joined, and
also non-matching rows from the right table in the table in the result and places null values in the
attributes that comes from the left table.
Example 4
https://play.google.com/store/apps/details? 50
www.Poriyaa
n.in
EMBEDDED SQL
SQL provides a powerful declarative query language. However, access to a database from a
general-purpose programming language is required because,
• Non declarative actions -- such as printing a report, interacting with a user, or sending
the result to a GUI -- cannot be done from within SQL.
The SQL standard defines embedding of SQL as embedded SQL and the language in
which SQL queries are embedded is referred as host language.
An embedded SQL statement is distinguished from the host language statements by
enclosing it between EXEC SQL or EXEC SQL BEGIN and a matching END-EXEC or
EXEC SQL END (or semicolon)
• Syntax may vary with language
• Shared variables (used in both languages) usually prefixed with a colon (:) in SQL
Example 1
/* Variable Declaration in Language C */
Variables inside DECLARE are shared and can appear (while prefixed by a colon) in
SQL statements
https://play.google.com/store/apps/details? 51
www.Poriyaa
n.in
int loop;
Example 2
loop = 1;
while (loop) {
EXEC SQL
loop); END-EXEC
Example 3
https://play.google.com/store/apps/details? 52
www.Poriyaa
n.in
Note that all C-language variables used in SQL statements are declared in the DECLARE
SECTION.
Note that all SQL statements begin with the syntax EXEC SQL and terminate with a
semicolon.
#include<stdio.h>
#include<string.h>
EXEC SQL BEGIN DECLARE SECTION;
long station_id;
long mon;
float temp;
float rain;
char city_name[21];
long SQLCODE;
EXEC SQL END DECLARE SECTION;
main()
{
/* the CONNECT statement, if needed, goes here
*/ strcpy(city_name,"Chennai");
EXEC SQL SELECT ID INTO
:station_id FROM STATION
WHERE CITY = :city_name;
if (SQLCODE == 100)
{
printf("There is no station for city %s\n",city_name);
exit(0);
}
printf("For the city %s, Station ID is %ld\n",city_name,station_id);
printf("And here is the weather data:\n");
https://play.google.com/store/apps/details? 53
www.Poriyaa
n.in
Output
For the city Chennai, Station ID is
44 And here is the weather data:
month = 1, temperature = 27.299999, rainfall = 0.180000
month = 7, temperature = 74.800003, rainfall = 2.110000
end of list
DYNAMIC SQL
Unlike static SQL, which remains the same in each execution, dynamic SQL enables you
to build SQL statements as character strings at runtime. The strings contain the text of a SQL
statement or PL/SQL block and can also contain placeholders for bind arguments.
You can create general purpose, flexible applications with dynamic SQL because the full
text of a SQL statement may be unknown at compilation. You can use dynamic SQL in several
different development environments, including PL/SQL, Pro*C/C++, and Java.
https://play.google.com/store/apps/details? 54
www.Poriyaa
n.in
For an example of an application that uses dynamic SQL, suppose that a reporting
https://play.google.com/store/apps/details? 55
www.Poriyaa
n.in
application in a data warehouse environment does not know a table name until runtime. These
tables are named according to the starting month and year of the quarter, for example,
inv_01_2003, inv_04_2003, inv_07_2003, inv_10_2003, inv_01_2004, and so on. You can use
dynamic SQL in your reporting application to specify the table name at runtime.
In a different example, suppose that you want to run a complex query with a user-
selectable sort order. Instead of coding the query twice with a different ORDER BY clause in
each query, you can construct the query dynamically to include a specified ORDER BY clause.
For the sake of consistency, this chapter discusses dynamic SQL mainly from the
perspective of PL/SQL. To process most dynamic SQL statements, you use the EXECUTE
IMMEDIATE statement. To process a multi-row query in a PL/SQL procedure, you use the
OPEN-FOR, FETCH, and CLOSE statements.
Oracle Database enables you to implement dynamic SQL in a PL/SQL application in the
following ways:
• Using native dynamic SQL, which involves placing dynamic SQL statements directly
into PL/SQL blocks
• Calling procedures in the DBMS_SQL package
Although this chapter discusses PL/SQL support for dynamic SQL, you can call dynamic
SQL from other languages:
• If you use C/C++, you can call dynamic SQL with the Oracle Call Interface (OCI), or
you can use the Pro*C/C++ precompiler to add dynamic SQL extensions to your C
code.
• If you use COBOL, you can use the Pro*COBOL precompiler to add dynamic SQL
extensions to your COBOL code.
• If you use Java, you can develop applications that use dynamic SQL with JDBC.
Dynamic SQL and static SQL both have advantages and disadvantages. The full text of
https://play.google.com/store/apps/details? 56
www.Poriyaa
n.in
static SQL statements is known at compilation, which provides the following benefits:
• Successful compilation verifies that the SQL statements reference valid database
objects and that the necessary privileges are in place to access the objects.
• Performance of static SQL is generally better than dynamic SQL.
Despite these advantages, static SQL has limitations that can be overcome with dynamic
SQL, as in the following cases:
• We do not know the full text of the SQL statements that must be executed in a
PL/SQL procedure. These SQL statements may depend on user input or on processing
work performed by the program.
• We want to execute DDL statements and other SQL statements that are not supported
in purely static SQL programs.
• We want to write a program that can handle changes in data definitions without the
need to recompile. Dynamic SQL is more flexible than static SQL because it enables
you to write reusable code that can be adapted for different environments.
Only dynamic SQL can execute the following types of statements within PL/SQL
program units:
The following native dynamic SQL example uses a SELECT statement with the TABLE
clause.
https://play.google.com/store/apps/details? 57
www.Poriyaa
n.in
10,
t_emplist
t_emp(1, 'Pradeep'),
t_emp(2, 'Kumar')
);
-- Write a PL/SQL block that queries table dept_new and nested table emps
-- SELECT ... FROM ... TABLE is not allowed in static SQL in PL/SQL
DECLARE
v_deptid NUMBER;
v_ename VARCHAR2(20);
BEGIN
END;
https://play.google.com/store/apps/details? 58
Database Management System
Elective-Management
Professional Elective II
Professional Elective IV