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

Dbms Unit

Uploaded by

2020pitcse278
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Dbms Unit

Uploaded by

2020pitcse278
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

CS8492-DATABASE MANAGEMENT SYSTEM

UNIT I
INTRODUCTION TO DBMS
Purpose of Database System-Views of Data -Data models – Database System Architecture-
Introduction to relational Databases-Relational Model-Keys-Relational Algebra-SQL
Fundamentals-Advanced SQL Futures-Embedded SQL-Dynamic SQL.

INTRODUCTION

A Database is a collection of related data organized in a way that data can be easily accessed,
managed and updated. Any piece of information can be a data, for example name of your school.
Database is actualy a place where related piece of information is stored and various operations can
be performed on it.

Database Management System (DBMS): The software which is used to manage database is
called Database Management System (DBMS). For Example, MySQL, Oracle etc. are popular
commercial DBMS used in different applications.

DBMS allows users the following tasks:

Data Definition: It helps in creation, modification and removal of definitions that define the organization of
data in database.
Data Updation: It helps in insertion, modification and deletion of the actual data in the database.

Data Retrieval: It helps in retrieval of data from the database which can be used by applications for various
purposes.
User Administration: It helps in registering and monitoring users, enforcing data security, monitoring
performance, maintaining data integrity, dealing with concurrency control and recovering information
corrupted by unexpected failure.

Componenets of Database System

The database system can be divided into four components.

II/IV SEM Page 1


CS8492-DATABASE MANAGEMENT SYSTEM

Users: Users may be of various type such as DB administrator, System developer and End
users.
Database application : Database application may be Personal, Departmental, Enterprise and
Internal
DBMS: Software that allow users to define, create and manages database access, Ex: MySql,
Oracle etc.
Database: Collection of logical data.

Functions of DBMS

Provides data Independence


Concurrency Control
Provides Recovery services
Provides Utility services
Provides a clear and logical view of the process that manipulates data.

Advantages of DBMS

Segregation of applicaion program.


Minimal data duplication.
Easy retrieval of data.
Reduced development time and maintainance need.

Disadvantages of DBMS

Complexity
Costly
Large in size

Database Applications:

1. Banking: all transactions


2. Airlines: reservations, schedules
3. Universities: registration, grades
4. Sales: customers, products, purchases
5. Online retailers: order tracking, customized recommendations
6. Manufacturing: production, inventory, orders, supply chain
7. Human resources: employee records, salaries, tax deductions

Difference between File system & DBMS File System


1. File system is a collection of data. Any management with the file system, user has to
write the procedures
2. File system gives the details of the data representation and Storage of data.
3. In File system storing and retrieving of data cannot be done efficiently.
4. Concurrent access to the data in the file system has many problems like
a. Reading the file while other deleting some information, updating some information
5. File system doesn’t provide crash recovery mechanism.
Eg. While we are entering some data into the file if System crashes then content of the
file is lost.

II/IV SEM Page 2


CS8492-DATABASE MANAGEMENT SYSTEM

6. Protecting a file under file system is very difficult.

DBMS
1. DBMS is a collection of data and user is not required to write the procedures for Managing
the database.
2. DBMS provides an abstract view of data that hides the details.
3. DBMS is efficient to use since there are wide varieties of sophisticated techniques to store
and retrieve the data.
4. DBMS takes care of Concurrent access using some form of locking.
5. DBMS has crash recovery mechanism, DBMS protects user from the effects of system
failures.
6. DBMS has a good protection mechanism.
DBMS = Database Management System
RDBMS = Relational Database Management System

DBMS Utilities
 A data loading utility:
Which allows easy loading of data from the external format without writing programs.
 A backup utility:
Which allows to make copies of the database periodically to help in cases of crashes and disasters.
 Recovery utility:
Which allows to reconstruct the correct state of database from the backup and history of
transactions.
 Monitoring tools:
Which monitors the performance so that internal schema can be changed and database access can
be optimized.

Characteristics of Database System


Stores any kind of data
A database management system should be able to store any kind of data. It should not be restricted
to the employee name, salary and address. Any kind of data that exists in the real world can be
stored in DBMS because we need to work with all kinds of data that is present around us.

Support ACID Properties


Any DBMS is able to support ACID (Accuracy, Completeness, Isolation, and Durability)
properties. It is made sure is every DBMS that the real purpose of data should not be lost while
performing transactions like delete, insert an update. Let us take an example; if an employee name
is updated then it should make sure that there is no duplicate data and no mismatch of student
information.

Represents complex relationship between data


Data stored in a database is connected with each other and a relationship is made in between data.
DBMS should be able to represent the complex relationship between data to make the efficient and
accurate use of data.

Backup and recovery


There are many chances of failure of whole database. At that time no one will be able to get the
database back and for sure company will be in a big loss. The only solution is to take backup of
database and whenever it is needed, it can be stored back. All the databases must have this
characteristic.

II/IV SEM Page 3


CS8492-DATABASE MANAGEMENT SYSTEM

Structures and described data


A database should not contains only the data but also all the structures and definitions of the data.
This data represent itself that what actions should be taken on it. These descriptions include the
structure, types and format of data and relationship between them.

Data integrity
This is one of the most important characteristics of database management system. Integrity ensures
the quality and reliability of database system. It protects the unauthorized access of database and
makes it more secure. It brings only the consistence and accurate data into the database.

Concurrent use of database


There are many chances that many users will be accessing the data at the same time. They may
require altering the database system concurrently. At that time, DBMS supports them to
concurrently use the database without any problem.

PURPOSE OF DATABASE SYSTEM:


Database management systems were developed to handle the following difficulties of
typical file-processing systems supported by conventional operating systems.
(i) Data redundancy and Consistency
(ii) Self-Describing Nature (of Database System)
(iii) Data isolation or Abstraction
(iv) Integrity
(v) Atomicity
(vi) Concurrent Access or sharing of Data
(vii) Security
(viii) Support for multiple views of Data

(i) Data redundancy and Consistency:


In file System, each user maintains separate files and programs to manipulate these files
because each requires some data not available from other user‘s files. This redundancy in defining
and storage of data results in
 Wasted storage space,
 Redundant efforts to maintain common update, higher storage and access
cost and Leads to inconsistency of data (ie.,) various copies of same data
may not agree.

In Database approach, a single repository of data is maintained that is maintained that is


defined once and then accessed by various users. Thus redundancy is controlled and it is
consistent.

(ii) Self-Describing Nature of Database System


II/IV SEM Page 4
CS8492-DATABASE MANAGEMENT SYSTEM

In File System, the structure of the data file is embedded in the access programs.
A database system contains not only the database itself but also a complete definition or
description of database structure and constraints. This definition is stored in System catalog which
contains information such as structure of each file, type and storage format of each data item and
various constraints on the data. Information stored in the catalog is called Meta-Data.
DBMS is not written for specific applications, hence it must refer to catalog to
know structure of file etc., and hence it can work equally well with any number of database
applications.
(iii) Data Isolation or Abstraction:
Conventional File processing systems do not allow data to be retrieved in
convenient and efficient manner. More responsive data retrieval systems are required for general
use.
The structure of the data file is embedded in the access programs. So any changes to
the structure of a file may require changing all programs that access this file. Because data are
scattered in various files and files may be in different formats, writing new application programs to
retrieve appropriate data is difficult.
But the DBMS access programs do not require such changes in most cases. The
structure of data files is stored in DBMS catalog separately from the access programs. This
property is known as program data independence.
Operations are separately specified and can be changed without affecting the
interface. User application programs can operate on data by invoking these operations regardless
of how they are implemented. This property is known as program operation independence.
Program data independence and program operation independence are together known as data
independence.
(iv) Enforcing Integrity Constraints:
The data values must satisfy certain types of consistency constraints.
In File System, Developers enforce constraints by adding appropriate code in application
program. When new constraints are added, it is difficult to change the programs to enforce them.
In data base system, DBMS provide capabilities for defining and enforcing constraints. The
constraints are maintained in system catalog. Therefore application programs work independently
with addition or modification of constraints. Hence integrity problems are avoided.
(v) Atomicity:
A Computer system is subjected to failure. If failure occurs, the data has to be
restored to the consistent state that existed prior to failure. The transactions must be atomic – it
must happen in entirety or not at all.
II/IV SEM Page 5
CS8492-DATABASE MANAGEMENT SYSTEM

It is difficult to ensure atomicity in File processing System.


In DB approach, the DBMS ensures atomicity using the Transaction manager
inbuilt in it. DBMS supports online transaction processing and recovery techniques to maintain
atomicity.
(vi) Concurrent Access or sharing of Data:
When multiple users update the data simultaneously, it may result in inconsistent
data. The system must maintain supervision which is difficult because data may be accessed by
many different application programs that may have not been coordinated previously.
The database (DBMS) include concurrency control software to ensure that several
programs /users trying to update the same data do so in controlled manner, so that the result of
update is correct.
(vii) Security:
Every user of the database system should not be able to access the data.
But since the application programs are added to the system in an adhoc manner, enforcing
such security constraints is difficult in file system.
DBMS provide security and authorization subsystem, which the DBA uses to create
accounts and to specify account restrictions.
(viii) Support for multiple views of Data:
Database approach support multiple views of data. A database has many users each of
whom may require a different view of the database. View may be a subset of database or virtual
data retrieved from database which is not explicitly stored. DBMS provide multiple views of the
data or DB.Different application programs are to be written for different views of data.

VIEWS OF DATA/DATA ABSTRACTION:


A major purpose of a database system is to provide users with an abstract view of data. Ie.,
the system hides certain details of how the data are stored and maintained.
Three Schema Architecture:
Separates the user applications and physical database. Schemas can be defined in three
levels:
(i) Internal Level:
 It has an internal schema which describes physical storage structure of the database.
 How the data are actually stored uses physical model
 describes the complete details of data storage and access paths for the database.e.g.,
customer

II/IV SEM Page 6


CS8492-DATABASE MANAGEMENT SYSTEM

(ii) Conceptual Level:


 It has an conceptual schema which describes the structure of whole database

 What data are stored and what relationships exist among data.
 Uses high level or implementational data model.
 Hides the details of physical storage structures and describes
datatypes, relationships, operations and constraints.
e.g:
type customer = record
customer_id : string;
customer_name : string;
customer_street : string;
customer_city : string;
end;
(iii) External or View Level:
 includes a number of external schemas or views.
 Each external schema describes the part of the database and hides the rest.
 Uses high level or implementation data model.
such as an employee’s salary.

DATABASE MODEL
A Database model defines the logical design of data. The model describes,
 Data
 Data Relationship
 Data Semantics
 Data Constraints

II/IV SEM Page 7


CS8492-DATABASE MANAGEMENT SYSTEM

It provides a way to describe the design of a database at the physical, logical and view
level.
Categories of data model
1. Record-based data models
 Hierarchical Model
 Network Model
 Relational Model

2. Object-based data models


 Entity-Relational Model
 Object-oriented Model
 Semantic Model
3. Physical-data models.
The first two are used to describe data at the conceptual and external levels, the latter is used to
describe data at the internal level.

1. Record-based data models.


The database consists of a number of fixed format records possibly of different types, each
typically of a fixed length.
There are three types of record-based logical data model,

1 Hierarchical Model
2 Network Model
3 Relational Model

Hierarchical Model
In this model each entity has only one parent but can have several children . At the top of hierarchy
there is only one entity which is called Root.

II/IV SEM Page 8


CS8492-DATABASE MANAGEMENT SYSTEM

Advantages:

 Promotes data sharing


 Parent / child relationship
 It is efficient with 1:M relationship
Disadvantage:

 Complex Implementation requires knowledge of physical storage characteristics.


 Change in structure requires changes in all application program.
 There is lack of standard.
 No multiparent or M:N relationship

Network Model

In the network model, entities are organized in a graph, in which some entities can be accessed
through several path

II/IV SEM Page 9


CS8492-DATABASE MANAGEMENT SYSTEM

The main difference of the network model from the hierarchical model is its ability to
handle many-to-many(N:N) relationships or in other words, it allow a record to have more than one
parent.
Example: Network DBMS
Advantage:

 It Handles more relationship types, such as M:N and multiparent.


 Data access is more flexible
 There is conformance to standards
Disadvantage

 System complexity limits efficiency


 Complex implementation, application development & management
 Structural changes require changes in all application program.

Relational Model

In this model, data is organised in two-dimesional tables called relations. The tables or relation are
related to each other.

Example: DB2, ORACLE, MS-SQL Server.

Advantage:

 Structural independence in promoted by the use of independent tables.


 Changes in a table’s structure do not affect data access or application programs.
 Improves conceptual simplicity.

II/IV SEM Page 10


CS8492-DATABASE MANAGEMENT SYSTEM

 Easier Design, Implementation & Management


Disadvantage:
 The RDBMS require substantial hardware and software overhead.
 Ease design can lead to bad design.

DATABASE SYSTEM ARCHITECTURE


The functional component of DBMS architecture is categorized into three pars:
1. Database user and Administrator
2. Query Processor
3. Storage Manager

1. Database Users and Database Administrator:


Users are differentiated by the way they expect to interact with the system

 Application programmers – interact with system through DML calls

 Sophisticated users – form requests in a database query language

 Specialized users – write specialized database applications that do not fit into the
traditional data processing framework

 Naive users – invoke one of the permanent application programs that have been
written previously

 E.g. people accessing database over the web, bank tellers, clerical staff.

Database administrator's duties include:

Coordinates all the activities of the database system

o Schema definition
o Storage structure and access method definition
o Schema and physical organization modification
o Granting user authority to access the database
o Routine maintenance.

2. The Query Processor


 DDL interpreter

 DML compiler

 Query evaluation engine.

3. STORAGE MANAGER
Storage manager is a program module that provides the interface between the low-level data stored
in the database and the application programs and queries submitted to the system.
The storage manager is responsible to the following tasks:
 Interaction with the file manager
 Efficient storing, retrieving and updating of data
II/IV SEM Page 11
CS8492-DATABASE MANAGEMENT SYSTEM

The storage manager components include:


 Authorization and integrity manager
 Transaction manager
 File manager
 Buffer manager
Transaction-management component ensures that the database remains in a consistent (correct)
state despite system failures (e.g., power failures and operating system crashes) and transaction
failures.

 Atomicity、consistency、isolation 、durability

 Concurrency-control manager controls the interaction among the concurrent transactions,


to ensure the consistency of the database.

 Failure recovery

II/IV SEM Page 12


CS8492-DATABASE MANAGEMENT SYSTEM

INTRODUCTION TO RELATIONAL DATABASES

RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and
for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft
Access.
A Relational database management system (RDBMS) is a database management system (DBMS)
that is based on the relational model as introduced by E. F. Codd.

What is a table?
The data in an RDBMS is stored in database objects which are called as tables. This table is
basically a collection of related data entries and it consists of numerous columns and rows.
Remember, a table is the most common and simplest form of data storage in a relational database.
The following program is an example of a CUSTOMERS table −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

What is a field?
Every table is broken up into smaller entities called fields. The fields in the CUSTOMERS table
consist of ID, NAME, AGE, ADDRESS and SALARY.
A field is a column in a table that is designed to maintain specific information about every record
in the table.

What is a Record or a Row?


A record is also called as a row of data is each individual entry that exists in a table.
For example, there are 7 records in the above CUSTOMERS table. Following is a single row of
data or record in the CUSTOMERS table −
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
+----+----------+-----+-----------+----------+
A record is a horizontal entity in a table.

What is a column?
A column is a vertical entity in a table that contains all information associated with a specific
field in a table.
For example, a column in the CUSTOMERS table is ADDRESS, which represents location
description and would be as shown below

II/IV SEM Page 13


CS8492-DATABASE MANAGEMENT SYSTEM

+-----------+
| ADDRESS |
+-----------+
| Ahmedabad |
| Delhi |
| Kota |
| Mumbai |
| Bhopal |
| MP |
| Indore |
+----+------+

What is a NULL value?


A NULL value in a table is a value in a field that appears to be blank, which means a field with a
NULL value is a field with no value.
It is very important to understand that a NULL value is different than a zero value or a field that
contains spaces. A field with a NULL value is the one that has been left blank during a record
creation.

SQL Constraints
Constraints are the rules enforced on data columns on a table. These are used to limit the type of
data that can go into a table. This ensures the accuracy and reliability of the data in the database.
Constraints can either be column level or table level. Column level constraints are applied only to
one column whereas, table level constraints are applied to the entire table.
Following are some of the most commonly used constraints available in SQL −

 NOT NULL Constraint − Ensures that a column cannot have a NULL value.
 DEFAULT Constraint − Provides a default value for a column when none is specified.
 UNIQUE Constraint − Ensures that all the values in a column are different.
 PRIMARY Key − Uniquely identifies each row/record in a database table.
 FOREIGN Key − Uniquely identifies a row/record in any another database table.
 CHECK Constraint − The CHECK constraint ensures that all values in a column satisfy
certain conditions.
 INDEX − Used to create and retrieve data from the database very quickly.

RELATIONAL MODEL

The relational model represents the database as a collection of relations. A relation is nothing but
a table of values. Every row in the table represents a collection of related data values. These rows
in the table denote a real-world entity or relationship.
The table name and column names are helpful to interpret the meaning of values in each row. The
data are represented as a set of relations. In the relational model, data are stored as tables.
However, the physical storage of the data is independent of the way the data are logically
organized.
Some popular Relational Database management systems are:

 DB2 and Informix Dynamic Server - IBM


 Oracle and RDB – Oracle
 SQL Server and Access - Microsoft

II/IV SEM Page 14


CS8492-DATABASE MANAGEMENT SYSTEM

Relational Model Concepts

1. Attribute: Each column in a Table. Attributes are the properties which define a relation.
e.g., Student_Rollno, NAME,etc.
2. Tables – In the Relational model the, relations are saved in the table format. It is stored
along with its entities. A table has two properties rows and columns. Rows represent
records and columns represent attributes.
3. Tuple – It is nothing but a single row of a table, which contains a single record.
4. Relation Schema: A relation schema represents the name of the relation with its
attributes.
5. Degree: The total number of attributes which in the relation is called the degree of the
relation.
6. Cardinality: Total number of rows present in the Table.
7. Column: The column represents the set of values for a specific attribute.
8. Relation instance – Relation instance is a finite set of tuples in the RDBMS system.
Relation instances never have duplicate tuples.
9. Relation key - Every row has one, two or multiple attributes, which is called relation key.
10. Attribute domain – Every attribute has some pre-defined value and scope which is
known as attribute domain

Relational Integrity constraints


Relational Integrity constraints is referred to conditions which must be present for a valid relation.
These integrity constraints are derived from the rules in the mini-world that the database
represents.
There are many types of integrity constraints. Constraints on the Relational database management
system is mostly divided into three main categories are:

1. Domain constraints
2. Key constraints
3. Referential integrity constraints

Domain Constraints
Domain constraints can be violated if an attribute value is not appearing in the corresponding
domain or it is not of the appropriate data type.
Domain constraints specify that within each tuple, and the value of each attribute must be unique.
This is specified as data types which include standard data types integers, real numbers,
characters, Booleans, variable length strings, etc.
II/IV SEM Page 15
CS8492-DATABASE MANAGEMENT SYSTEM

Example:
Create DOMAIN CustomerName
CHECK (value not NULL)
The example shown demonstrates creating a domain constraint such that CustomerName is not
NULL

Key constraints
An attribute that can uniquely identify a tuple in a relation is called the key of the table. The value
of the attribute for different tuples in the relation has to be unique.
Example:
In the given table, CustomerID is a key attribute of Customer Table. It is most likely to have a
single key for one customer, CustomerID =1 is only for the CustomerName =" Google".
CustomerID CustomerName Status
1 Google Active
2 Amazon Active
3 Apple Inactive

Referential integrity constraints


Referential integrity constraints is base on the concept of Foreign Keys. A foreign key is an
important attribute of a relation which should be referred to in other relationships. Referential
integrity constraint state happens where relation refers to a key attribute of a different or same
relation. However, that key element must exist in the table.
Example:

In the above example, we have 2 relations, Customer and Billing.


Tuple for CustomerID =1 is referenced twice in the relation Billing. So we know
CustomerName=Google has billing amount $300

Operations in Relational Model


Four basic update operations performed on relational database model are
Insert, update, delete and select.

 Insert is used to insert data into the relation


 Delete is used to delete tuples from the table.
II/IV SEM Page 16
CS8492-DATABASE MANAGEMENT SYSTEM

 Modify allows you to change the values of some attributes in existing tuples.
 Select allows you to choose a specific range of data.

Whenever one of these operations are applied, integrity constraints specified on the relational
database schema must never be violated.

Inset Operation
The insert operation gives values of the attribute for a new tuple which should be inserted into a
relation.

Update Operation
You can see that in the below-given relation table CustomerName= 'Apple' is updated from
Inactive to Active.

Delete Operation
To specify deletion, a condition on the attributes of the relation selects the tuple to be deleted.

In the above-given example, CustomerName= "Apple" is deleted from the table.


The Delete operation could violate referential integrity if the tuple which is deleted is referenced
by foreign keys from other tuples in the same database.

Select Operation

In the above-given example, CustomerName="Amazon" is selected


Note:For creating a Relational Model

 Data need to be represented as a collection of relations


 Each relation should be depicted clearly in the table

II/IV SEM Page 17


CS8492-DATABASE MANAGEMENT SYSTEM

 Rows should contain data about instances of an entity


 Columns must contain data about attributes of the entity
 Cells of the table should hold a single value
 Each column should be given a unique name
 No two rows can be identical
 The values of an attribute should be from the same domain

Advantages of using Relational model

 Simplicity: A relational data model is simpler than the hierarchical and network model.
 Structural Independence: The relational database is only concerned with data and not
with a structure. This can improve the performance of the model.
 Easy to use: The relational model is easy as tables consisting of rows and columns is quite
natural and simple to understand
 Query capability: It makes possible for a high-level query language like SQL to avoid
complex database navigation.
 Data independence: The structure of a database can be changed without having to change
any application.
 Scalable: Regarding a number of records, or rows, and the number of fields, a database
should be enlarged to enhance its usability.

Disadvantages of using Relational model

 Few relational databases have limits on field lengths which can't be exceeded.
 Relational databases can sometimes become complex as the amount of data grows, and the
relations between pieces of data become more complicated.
 Complex relational database systems may lead to isolated databases where the information
cannot be shared from one system to another.

KEYS

What is key

Keys are very important part of Relational database model. They are used to establish and identify
relationships between tables and also to uniquely identify any record or row of data inside a table.

A Key can be a single attribute or a group of attributes, where the combination may act as a key.

Why we need a Key?


In real world applications, number of tables required for storing the data is huge, and the different
tables are related to each other as well.
Also, tables store a lot of data in them. Tables generally extends to thousands of records stored in
them, unsorted and unorganized.
Now to fetch any particular record from such dataset, you will have to apply some conditions, but
what if there is duplicate data present and every time you try to fetch some data by applying
certain condition, you get the wrong data. How many trials before you get the right data?
To avoid all this, Keys are defined to easily identify any row of data in a table.

Types of keys in DBMS


Primary Key – A primary is a column or set of columns in a table that uniquely identifies tuples
(rows) in that table.

II/IV SEM Page 18


CS8492-DATABASE MANAGEMENT SYSTEM

Super Key – A super key is a set of one of more columns (attributes) to uniquely identify rows in
a table.
Candidate Key – A super key with no redundant attribute is known as candidate key
Alternate Key – Out of all candidate keys, only one gets selected as primary key, remaining keys
are known as alternate or secondary keys.
Composite Key – A key that consists of more than one attribute to uniquely identify rows (also
known as records & tuples) in a table is called composite key.
Foreign Key – Foreign keys are the columns of a table that points to the primary key of another
table. They act as a cross-reference between tables.
Example:

Let's try to understand about all the keys using a simple example.

student_id name phone age


1 Akon 9876723452 17
2 Akon 9991165674 19
3 Bkon 7898756543 18
4 Ckon 8987867898 19
5 Dkon 9990080080 17

Let's take a simple Student table, with fields student_id, name, phone and age.

Super Key

In the table defined above super key would include student_id, (student_id, name), phone etc.

Confused? The first one is pretty simple as student_id is unique for every row of data, hence it
can be used to identity each row uniquely.

Next comes, (student_id, name), now name of two students can be same, but their student_id can't
be same hence this combination can also be a key.

Similarly, phone number for every student will be unique, hence again, phone can also be a key.

So they all are super keys.

Candidate Key

Candidate keys are defined as the minimal set of fields which can uniquely identify each record in
a table. It is an attribute or a set of attributes that can act as a Primary Key for a table to uniquely
identify each record in that table. There can be more than one candidate key.

In our example, student_id and phone both are candidate keys for table Student.

 A candiate key can never be NULL or empty. And its value should be unique.
 There can be more than one candidate keys for a table.
 A candidate key can be a combination of more than one columns(attributes).

II/IV SEM Page 19


CS8492-DATABASE MANAGEMENT SYSTEM

Primary Key
Primary key is a candidate key that is most appropriate to become the main key for any table. It is
a key that can uniquely identify each record in a table.

For the table Student we can make the student_id column as the primary key.

Composite Key
Key that consists of two or more attributes that uniquely identify any record in a table is called
Composite key. But the attributes which together form the Composite key are not a key
independentely or individually.

In the above picture we have a Score table which stores the marks scored by a student in a
particular subject.
In this table student_id and subject_id together will form the primary key, hence it is a composite
key.

Secondary or Alternative key


The candidate key which are not selected as primary key are known as secondary keys or
alternative keys.

Non-key Attributes
Non-key attributes are the attributes or fields of a table, other than candidate key attributes/fields
in a table.

Non-prime Attributes
Non-prime Attributes are attributes other than Primary Key attribute(s)..

II/IV SEM Page 20


CS8492-DATABASE MANAGEMENT SYSTEM

RELATIONAL ALGEBRA

Relational algebra is a procedural query language, which consists of basic set of relational
model operations. These operations enable the user to specify basic retrieval requests. It takes one
or more relations as input and result of retrieval is a relation.
The fundamental operations of relational algebra are as follows −

 Select
 Project
 Union
 Set different
 Cartesian product
 Rename

We will discuss all these operations in the following sections.

Select Operation (σ)


It selects tuples that satisfy the given predicate from a relation.
Notation − σp(r)
Where σ stands for selection predicate and r stands for relation. p is prepositional logic formula
which may use connectors like and, or, and not. These terms may use relational operators like −
=, ≠, ≥, <, >, ≤.
For example −
σsubject = "database"(Books)
Output − Selects tuples from books where subject is 'database'.
Σsubject = "database" and price = "450"(Books)
Output − Selects tuples from books where subject is 'database' and 'price' is 450.
σsubject = "database" and price = "450" or year > "2010"(Books)
Output − Selects tuples from books where subject is 'database' and 'price' is 450 or those books
published after 2010.

Project Operation (∏)


It projects column(s) that satisfy a given predicate.
Notation − ∏A1, A2, An (r)
Where A1, A2 , An are attribute names of relation r.
Duplicate rows are automatically eliminated, as relation is a set.
For example −
∏subject, author (Books)
Selects and projects columns named as subject and author from the relation Books.

Union Operation (∪)


It performs binary union between two given relations and is defined as −
r ∪ s = { t | t ∈ r or t ∈ s}
Notation − r U s
Where r and s are either database relations or relation result set (temporary relation).

II/IV SEM Page 21


CS8492-DATABASE MANAGEMENT SYSTEM

For a union operation to be valid, the following conditions must hold −

 r, and s must have the same number of attributes.


 Attribute domains must be compatible.
 Duplicate tuples are automatically eliminated.

∏ author (Books) ∪ ∏ author (Articles)


Output − Projects the names of the authors who have either written a book or an article or both.

Set Difference (−)


The result of set difference operation is tuples, which are present in one relation but are not in the
second relation.
Notation − r − s
Finds all the tuples that are present in r but not in s.
∏ author (Books) − ∏ author (Articles)
Output − Provides the name of authors who have written books but not articles.

Cartesian Product (Χ)


Combines information of two different relations into one.
Notation − r Χ s
Where r and s are relations and their output will be defined as −
r Χ s = { q t | q ∈ r and t ∈ s}
σauthor = 'tutorialspoint'(Books Χ Articles)
Output − Yields a relation, which shows all the books and articles written by tutorialspoint.

Rename Operation (ρ)


The results of relational algebra are also relations but without any name. The rename operation
allows us to rename the output relation. 'rename' operation is denoted with small Greek letter rho
ρ.
Notation − ρ x (E)
Where the result of expression E is saved with name of x.

SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a related column
between them.
JOIN Keyword is used in SQL queries for joining two or more tables. Minimum required
condition for joining table, is (n-1) where n, is number of tables.
Why SQL JOIN is used?
If you want to access more than one table through a select statement.
If you want to combine two or more table then SQL JOIN statement is used .it combines rows of
that tables in one table and one can retrieve the information by a SELECT statement.
The joining of two or more tables is based on common field between them.
SQL INNER JOIN also known as simple join is the most common type of join.

Different Types of SQL JOINs


Here are the different types of the JOINs in SQL:

II/IV SEM Page 22


CS8492-DATABASE MANAGEMENT SYSTEM

 (INNER) JOIN: Returns records that have matching values in both tables
 LEFT (OUTER) JOIN: Return all records from the left table, and the matched records
from the right table
 RIGHT (OUTER) JOIN: Return all records from the right table, and the matched
records from the left table
 FULL (OUTER) JOIN: Return all records when there is a match in either left or right
table

Example:
Inner Join

1.Staff table

ID Staff_NAME Staff_AGE STAFF_ADDRESS Monthley_Package


1 ARYAN 22 MUMBAI 18000
2 SUSHIL 32 DELHI 20000
3 MONTY 25 MOHALI 22000
4 AMIT 20 ALLAHABAD 12000

2.Payment table

Payment_ID DATE Staff_ID AMOUNT


101 30/12/2009 1 3000.00
102 22/02/2010 3 2500.00
103 23/02/2010 4 3500.00

So if you follow this JOIN statement to join these two tables ?

1. SELECT Staff_ID, Staff_NAME, Staff_AGE, AMOUNT


2. FROM STAFF s, PAYMENT p
3. WHERE s.ID =p.STAFF_ID;

This will produce the result like this:


II/IV SEM Page 23
CS8492-DATABASE MANAGEMENT SYSTEM

STAFF_ID NAME Staff_AGE AMOUNT


3 MONTY 25 2500
1 ARYAN 22 3000
4 AMIT 25 3500
1 ARYAN 22 3000

SQL OUTER JOIN


In the SQL outer JOIN all the content of the both tables are integrated together either they are
matched or not.
If you take an example of employee table
Outer join of two types:
1.Left outer join (also known as left join): this join returns all the rows from left table combine
with the matching rows of the right table. If you get no matching in the right table it returns
NULL values.
2.Right outer join (also known as right join): this join returns all the rows from right table are
combined with the matching rows of left table .If you get no column matching in the left table .it
returns null value.

SQL LEFT JOIN


The SQL left join returns all the values from the left table and it also includes matching values
from right table, if there are no matching join value it returns NULL.
BASIC SYNTAX FOR LEFT JOIN:

1. SELECT table1.column1, table2.column2....


2. FROM table1
3. LEFTJOIN table2
4. ON table1.column_field = table2.column_field;

let us take two tables in this example to elaborate all the things:
CUSTOMER TABLE:

ID NAME AGE SALARY


1 ARYAN 51 56000
2 AROHI 21 25000
3 VINEET 24 31000
4 AJEET 23 32000
5 RAVI 23 42000
This is second table
ORDER TABLE:

O_ID DATE CUSTOMER_ID AMOUNT


001 20-01-2012 2 3000
002 12-02-2012 2 2000

II/IV SEM Page 24


CS8492-DATABASE MANAGEMENT SYSTEM

003 22-03-2012 3 4000


004 11-04-2012 4 5000
join these two tables with LEFT JOIN:

1. SQL SELECT ID, NAME, AMOUNT,DATE


2. FROM CUSTOMER
3. LEFT JOIN ORDER
4. ON CUSTOMER.ID = ORDER.CUSTOMER_ID;

This will produce the following result:

ID NAME AMOUNT DATE


1 ARYAN NULL NULL
2 AROHI 3000 20-01-2012
2 AROHI 2000 12-02-2012
3 VINEET 4000 22-03-2012
4 AJEET 5000 11-04-2012
5 RAVI NULL NULL

SQL RIGHT JOIN


The SQL right join returns all the values from the rows of right table. It also includes the matched
values from left table but if there is no matching in both tables, it returns NULL.
Basic syntax for right join:

1. SELECT table1.column1, table2.column2.....


2. FROM table1
3. RIGHT JOIN table2
4. ON table1.column_field = table2.column_field;

let us take an example with 2 tables table1 is CUSTOMERS table and table2 is ORDERS table.
CUSTOMER TABLE:

ID NAME AGE SALARY


1 ARYAN 51 56000
2 AROHI 21 25000
3 VINEET 24 31000
4 AJEET 23 32000
5 RAVI 23 42000
and this is the second table:
ORDER TABLE:

DATE O_ID CUSTOMER_ID AMOUNT


20-01-2012 001 2 3000
12-02-2012 002 2 2000
22-03-2012 003 3 4000
11-04-2012 004 4 5000

II/IV SEM Page 25


CS8492-DATABASE MANAGEMENT SYSTEM

Here we will join these two tables with SQL RIGHT JOIN:

1. SQL> SELECT ID,NAME,AMOUNT,DATE


2. FROM CUSTOMER
3. RIGHT JOIN ORDER
4. ON CUSTOMER.ID = ORDER.CUSTOMER_ID;

ID NAME AMOUNT DATE


2 AROHI 3000 20-01-2012
2 AROHI 2000 12-02-2012
3 VINEET 4000 22-03-2012
4 AJEET 5000 11-04-2012

SQL FULL JOIN


The SQL full join is the result of combination of both left and right outer join and the join tables
have all the records from both tables. It puts NULL on the place of matches not found.
SQL full outer join and SQL join are same. generally it is known as SQL FULL JOIN.

SQL full outer join:


What is SQL full outer join?
SQL full outer join is used to combine the result of both left and right outer join and returns all
rows (don?t care its matched or unmatched) from the both participating tables.
Syntax for full outer join:

1. SELECT *
2. FROM table1
3. FULL OUTER JOIN table2
4. ON table1.column_name = table2.column_name;

Note:here table1 and table2 are the name of the tables participating in joining and column_name
is the column of the participating tables.
Let us take two tables to demonstrate full outer join:
table_A

A M
1 m
2 n
4 o
table_B

A N
2 p
3 q
5 r

Resulting table
II/IV SEM Page 26
CS8492-DATABASE MANAGEMENT SYSTEM

A M A N
2 n 2 p
1 m - -
4 o - -
- - 3 q
- - 5 r
Because this is a full outer join so all rows (both matching and non-matching) from both tables
are included in the output. Here only one row of output displays values in all columns because
there is only one match between table_A and table_B.

SQL Cross Join


When each row of first table is combined with each row from the second table, known as
Cartesian join or cross join. In general words we can say that SQL CROSS JOIN returns the
Cartesian product of the sets of rows from the joined table.
CROSS JOIN in two ways:

1. Using the JOIN syntax.


2. the table in the FROM clause without using a WHERE clause.

SYNTAX of SQL Cross Join

1. SELECT * FROM [TABLE1] CROSS JOIN [TABLE2]


2. OR
3. SELECT * FROM [ TABLE1] , [TABLE2]

Let us take an example of two tables,


Table1 - MatchScore

Player Department_id Goals


Franklin 1 2
Alan 1 3
Priyanka 2 2
Rajesh 3 5
Table2 - Departments

Department_id Department_name
1 IT
2 HR
3 Marketing
SQL Statement:

1. SELECT * FROM MatchScore CROSS JOIN Departments

After executing this query , you will find the following result:

Player Department_id Goals Depatment_id Department_name


Franklin 1 2 1 IT
II/IV SEM Page 27
CS8492-DATABASE MANAGEMENT SYSTEM

Alan 1 3 1 IT
Priyanka 2 2 1 IT
Rajesh 3 5 1 IT
Franklin 1 2 2 HR
Alan 1 3 2 HR
Priyanka 2 2 2 HR
Rajesh 3 5 2 HR
Franklin 1 2 3 Marketing
Alan 1 3 3 Marketing
Priyanka 2 2 3 Marketing
Rajesh 3 5 3 Marketing

SQL FUNDAMENTALS
SQL is a programming language for Relational Databases. It is designed over relational algebra
and tuple relational calculus. SQL comes as a package with all major distributions of RDBMS.
SQL comprises both data definition and data manipulation languages. Using the data definition
properties of SQL, one can design and modify database schema, whereas data manipulation
properties allows SQL to store and retrieve data from database.

Data Definition Language


SQL uses the following set of commands to define database schema −

CREATE
Creates new databases, tables and views from RDBMS.
For example −
Create database tutorialspoint;
Create table article;
Create view for_students;

DROP
Drops commands, views, tables, and databases from RDBMS.
For example−
Drop object_type object_name;
Drop database tutorialspoint;
Drop table article;
Drop view for_students;

ALTER
Modifies database schema.
Alter object_type object name parameters;
For example−
Alter table article add subject varchar;
This command adds an attribute in the relation article with the name subject of string type.

II/IV SEM Page 28


CS8492-DATABASE MANAGEMENT SYSTEM

Data Manipulation Language


SQL is equipped with data manipulation language (DML). DML modifies the database instance
by inserting, updating and deleting its data. DML is responsible for all froms data modification in
a database. SQL contains the following set of commands in its DML section −

 SELECT/FROM/WHERE
 INSERT INTO/VALUES
 UPDATE/SET/WHERE
 DELETE FROM/WHERE

These basic constructs allow database programmers and users to enter data and information into
the database and retrieve efficiently using a number of filter options.

SELECT/FROM/WHERE

 SELECT − This is one of the fundamental query command of SQL. It is similar to the
projection operation of relational algebra. It selects the attributes based on the condition
described by WHERE clause.
 FROM − This clause takes a relation name as an argument from which attributes are to be
selected/projected. In case more than one relation names are given, this clause corresponds
to Cartesian product.
 WHERE − This clause defines predicate or conditions, which must match in order to
qualify the attributes to be projected.

For example −
Select author_name
From book_author
Where age > 50;
This command will yield the names of authors from the relation book_author whose age is
greater than 50.

INSERT INTO/VALUES
This command is used for inserting values into the rows of a table (relation).
Syntax−
INSERT INTO table (column1 [, column2, column3 ... ]) VALUES (value1 [, value2, value3 ... ])
Or
INSERT INTO table VALUES (value1, [value2, ... ])
For example −
INSERT INTO tutorialspoint (Author, Subject) VALUES ("anonymous", "computers");

UPDATE/SET/WHERE
This command is used for updating or modifying the values of columns in a table (relation).
Syntax −
UPDATE table_name SET column_name = value [, column_name = value ...] [WHERE
condition]
For example −
UPDATE tutorialspoint SET Author="webmaster" WHERE Author="anonymous";

II/IV SEM Page 29


CS8492-DATABASE MANAGEMENT SYSTEM

DELETE/FROM/WHERE
This command is used for removing one or more rows from a table (relation).
Syntax −
DELETE FROM table_name [WHERE condition];
For example −
DELETE FROM tutorialspoints
WHERE Author="unknown";

EMBEDDED SQL

1. SQL provides a powerful declarative query language. However, access to a database from
a general-purpose programming language is required because,
o SQL is not as powerful as a general-purpose programming language. There are
queries that cannot be expressed in SQL, but can be programmed in C, Fortran,
Pascal, Cobol, etc.
o Nondeclarative actions -- such as printing a report, interacting with a user, or
sending the result to a GUI -- cannot be done from within SQL.
2. The SQL standard defines embedding of SQL as embedded SQL and the language in
which SQL queries are embedded is referred as host language.
3. The result of the query is made available to the program one tuple (record) at a time.

To identify embedded SQL requests to the preprocessor, we use EXEC SQL statement:
EXEC SQL embedded SQL statement END-EXEC
Note: A semi-colon is used instead of END-EXEC when SQL is embedded in C or Pascal.
5. Embedded SQL statements: declare cursor, open, and fetch statements.
EXEC SQL

declare c cursor for

select cname, ccity

from deposit, customer

where deposit.cname = customer.cname


and deposit.balance > :amount

END-EXEC
where amount is a host-language variable.
EXEC SQL open c END-EXEC

This statement causes the DB system to execute the query and to save the results within a
temporary relation.
A series of fetch statement are executed to make tuples of the results available to the program.
EXEC SQL fetch c into :cn, :cc END-EXEC

The program can then manipulate the variable cn and cc using the features of the host
programming language.
A single fetch request returns only one tuple. We need to use a while loop (or equivalent) to
process each tuple of the result until no further tuples (when a variable in the SQLCA is set).
We need to use close statement to tell the DB system to delete the temporary relation that held the
result of the query.

II/IV SEM Page 30


CS8492-DATABASE MANAGEMENT SYSTEM

EXEC SQL close c END-EXEC


6. Embedded SQL can execute any valid update, insert, or delete statements.
7.Dynamic SQL component allows programs to construct and submit SQL queries are run time
8. SQL-92 also contains a module language, which allows procedures to be defined in SQL.

SQL statements can be embedded into an application program in two different ways:

 Call Level Interface (CLI): The application program is written entirely in the host language. SQL
statements are simply strings in the host language that are passed as arguments to host language
procedures or functions from a SQL library.

 Statement Level Interface (SLI): The application program is composed of a mixture of host
language statements and SQL statements and directives

Call Level Interface


The application program is written entirely in host language (no precompiler)

 Example interfaces: JDBC, ODBC

SQL statements are composed of Java or C++ strings constructed and concatenated at run time
using host language.

 Similar to dynamic SQL

The application uses strings or string variables as arguments of library routines that communicate
with DBMS

 e.g. executeQuery("SQL query statement")

Statement Level Interface


SQL statements and directives in the application have a special syntax that sets them off from
host language constructs.
e.g., EXEC SQL SQL_statement
or # SQL_statement
A precompiler scans the program and translates SQL statements into calls to host language library
procedures that communicate directly with DBMS.
The host language compiler then compiles program.
SQL constructs in an application take two forms:

 Standard SQL statements (static or embedded SQL): Useful when the SQL portion of
program is known at compile time
 Directives (dynamic SQL): Useful when SQL portion of program not known at compile
time. Application constructs SQL statements at run time as values of host language
variables that are manipulated by directives. Try to minimize the use of dynamic SQL
because of performance.

Static SQL
You normally have a declaration section for host/SQL communication.
…some host language code…….

II/IV SEM Page 31


CS8492-DATABASE MANAGEMENT SYSTEM

EXEC SQL BEGIN DECLARE SECTION;


unsigned long num_enrolled; //host language variable
char crs_code; //host language variable
char SQLSTATE [6]; //returned status code--must be provided
EXEC SQL END DECLARE SECTION;
…some more host language code…….
EXEC SQL SELECT C.NumEnrolled
INTO :num_enrolled
FROM Course C
WHERE C.CrsCode = :crs_code;
…and even more host language code…….
Note the use of the colon for host variable references embedded into the (WHERE) and for the
result (INTO) parameters.

An Embedded SQL Example in C


SQL statements can be embedded in any general purpose programming language, still we just
take an example in C language,

Increase the salary of teacher by 10% who are B.Tech


update teacher set salary=1.1*salary where qualification=’B.Tech’;

The embedded SQL program for above written SQL statement will be:

main()
{
exec sql include sqlca;
exec sql declare table teacher (tid char(6) not null,tname char(20),sex char(1),age
number(3),qualification char(7),salary number(7),city varchar(15));
//Display a message to user
printf("updating teacher salary who are B.Techn");
//this code executes the SQL statement
exec sql update teacher set salary=1.1*salary where qualification='B.Tech';
printf(update done");

exit();
}
Explanation
Although the above shown program is very easy to understand,
still we would like to discuss some very basic features of embedded SQL.

1. The embedded SQL statement can be written in any case (lower


or upper). Although we should follow the convention of that programming
language in which we are embedding the SQL statements. For e.g., COBOL and
FORTRAN are written in upper case so, the SQL statements are also written in
upper case, while in C, the SQL statements are written in lower case as shown
in above program.
2. Each embedded SQL statement begins with an introducer which
indicates that it is a SQL statement. For most of the programming language EXEC
SQL is used as an introducer.

II/IV SEM Page 32


CS8492-DATABASE MANAGEMENT SYSTEM

3. Each embedded SQL statement ends with a terminator. There


can be different terminators for different programming languages. For example,
there is END EXEC for COBOL and a semicolon (;) for C.
4. The DECLARE TABLE statement is used to declare a table. With
the use of DECLARE TABLE statement our program specifies the column and data
type explicitly.
5. When we type SQL statement, we may make an error. This error
is displayed by the interactive SQL program and we are prompted to type a new statement.
There can be two types of errors: compile time and runtime.

Application of Embedded SQL-Buffer Mismatch

Problem: SQL deals with tables (of arbitrary size); host language program deals with fixed size
buffers or variables and arrays. How is the application to allocate storage for the result of a
SELECT statement since the result can be a set of tuples? with unpredictable size?

Solution: Fetch a single row at a time. The space for a single row (number and type of out
parameters) can be well defined from the schema and allocated within the application.

Problem: We still need to be able to track the individual rows within a selected result set.

Solution: Use a pointer mechanism to track the "current" row from the result set . This is usually
called a cursor.

The result set can be thought of as a collection or a list and we want to iterate through the
collection simply in a sequential manner.

DYNAMIC SQL

Dynamic SQL is a programming technique that enables you to build SQL statements dynamically
at runtime.. For example, dynamic SQL lets you create a procedure that operates on a table whose
name is not known until runtime.

Since dynamic SQL builds a query at run time, as a first step we need to capture all the inputs
from the user. It will be stored in a string variable. Depending on the inputs received from the
user, string variable is appended with inputs and SQL keywords. These SQL like string
statements are then converted into SQL query. This is done by using PREPARE statement.

For example, below is the small snippet from dynamic SQL. Here sql_stmt is a character variable,
which holds inputs from the users along with SQL commands. But is cannot be considered as
SQL query as it is still a sting value. It needs to be converted into a proper SQL query which is
done at the last line using PREPARE statement. Here sql_query is also a string variable, but it
holds the string as a SQL query.

sql_stmt = "SELECT STD_ID FROM STUDENT ";


if (strcmp(STD_NAME, '') != 0){
sql_stmt = sql_stmt || " WHERE STD_NAME = :STD_NAME";
}
else if (CLASS_ID > 0){
sql_stmt = sql_stmt || " WHERE CLASS_ID = :CLASS_ID";
}
if (strcmp(STD_NAME, '') !=0 && CLASS_ID >0)
sql_stmt = sql_stmt || " AND CLASS_ID = :CLASS_ID";

II/IV SEM Page 33


CS8492-DATABASE MANAGEMENT SYSTEM

EXEC SQL PREPARE sql_query FROM :sql_stmt;

This statement is used to compile and execute the SQL statements prepared in DB.

EXEC SQL EXECUTE sql_query;

EXECUTE IMMEDIATE

This statement is used to prepare SQL statement as well as execute the SQL statements in DB. It
performs the task of PREPARE and EXECUTE in a single line.

EXEC SQL EXECUTE IMMEDIATE :sql_stmt;

A simple program that illustrates dynamic SQL is given below


#include
#include

int main(){
EXEC SQL INCLUDE SQLCA;

EXEC SQL BEGIN DECLARE SECTION;


int STD_ID;
char *STD_NAME;
int CLASS_ID;
char *sql_stmt;
char *sql_query;
EXEC SQL END DECLARE SECTION;

EXEC WHENEVER NOT FOUND GOTO error_msg1;


EXEC WHENEVER SQLERROR GOTO error_msg2;

printf("Enter the Student name:");


scanf("%s", STD_Name);

printf("Enter the Class ID:");


scanf("%d", &CLASS_ID);

sql_stmt = "SELECT STD_ID FROM STUDENT ";


if (strcmp(STD_NAME, '') != 0)
sql_stmt = sql_stmt || " WHERE STD_NAME = :STD_NAME";
else if (CLASS_ID > 0)
sql_stmt = sql_stmt || " WHERE CLASS_ID = :CLASS_ID";
if (strcmp(STD_NAME, '') !=0 && CLASS_ID >0)
sql_stmt = sql_stmt || " AND CLASS_ID = :CLASS_ID";

EXEC SQL PREPARE sql_query FROM :sql_stmt;


EXEC SQL EXECUTE sql_query;

printf("STUDENT ID:%d", STD_ID);


exit(0);

error_msg1:
printf("Student Id %d is not found", STD_ID);
printf("ERROR:%ld", sqlca->sqlcode);
printf("ERROR State:%s", sqlca->sqlstate);
exit(0);

error_msg2:
printf("Error has occurred!");
printf("ERROR:%ld", sqlca->sqlcode);
printf("ERROR State:%s", sqlca->sqlstate);
exit(0);

II/IV SEM Page 34


CS8492-DATABASE MANAGEMENT SYSTEM

Methods of Accessing Dynamic SQL


There are four different methods of using Dynamic SQL. These methods of dynamic SQL are
based on the number of host variables and known/unknown list of SELECT list.

Different host languages supported using embedded SQL are listed below. It also shows which
version of Oracle supports embedding SQL.

Differences between Static or Embedded and Dynamic or Interactive SQL:

Static (Embedded) SQL Dynamic (Interactive) SQL


In Static SQL, how database will be accessed
In Dynamic SQL, how database will be
is predetermined in the embedded SQL
accessed is determined at run time.
statement.
It is more swift and efficient. It is less swift and efficient.
SQL statements are compiled at compile
SQL statements are compiled at run time.
time.
Parsing, Validation, Optimization and Parsing, Validation, Optimization and
Generation of application plan are done at Generation of application plan are done at
compile time. run time.
It is generally used for situations where data It is generally used for situations where
is distributed uniformly. data is distributed non uniformly.
EXECUTE IMMEDIATE, EXECUTE and EXECUTE IMMEDIATE, EXECUTE and
PREPARE statements are not used. PREPARE statements are used.
It is less flexible. It is more flexible.

II/IV SEM Page 35


CS8492-DATABASE MANAGEMENT SYSTEM

TWO MARKS

1. What is database?
A database is a basic electronic storage with collection of interrelated data,
organized to provide efficient retrieval. Databases are organized by fields, records and
files or tables.

2. What is DBMS? (NOV 2008)


A database management system (DBMS) is a software package designed
to define, manipulate, retrieve and manage data in a database.

3. List out some representative application of databases (DEC 2007)


Databases are widely used. Here are some representative applications.
 Banking
 Airlines
 Universities
 Credit card transactions
 Telecommunication
 Finance
 Sales
 On-line retailers
 Manufacturing
 Human resources

4. What is the purpose of data base system? (NOV 2014)


The primary goal of a DBMS is to provide an environment that is both
convenient and efficient for people to storing and retrieving information.

5. What are problems caused by redundancy?(Nov/Dec-2017)


 The first is that storing values multiple times wastes space.
 The second problem is that when a field value changes, multiple
occurrences need to be updated.
 The third problem occurs if we forget to change the values in any of
the records. The database would then have inconsistent data.

6. Describe the three levels of data abstraction? (Nov/Dec-2017)


There are three levels of abstraction:
 Physical level
 Logical level
 View level

7. What is a physical level?


The lowest level of abstraction describes how data are stored.

II/IV SEM Page 36


CS8492-DATABASE MANAGEMENT SYSTEM

8. What is a logical level?


The next higher level of abstraction, describes what data are stored in
database and what relationship among those data.

9. What is a view level?


The highest level of abstraction describes only part of entire database.

10. What is a schema? (MAY 2007)


The structure of a database system, described in a formal language supported by
the database management system (DBMS), In a relational database, the schema defines
the tables, the fields in each table, and the relationships between fields and tables.
Schemas are generally stored in a data dictionary.

11. What are the different types of schemas?


 Physical Schema
 Logical Schema
 External Schema
12. What is an instance? (R)
The collection of information stored in the database at a particular
moment is called an instance of the database.
13. What do u mean by data model? (MAY 2011)
Data Model can be defined as an integrated collection of concepts for
describing and manipulating data, relationships between data, and constraints on
the data in an organization.

14. What are the different data models? (MAY 2012)


 Relational Data Model
 The Entity-Relationship Data Model
 Object-Based Data Model
 Semi structured Data Model

15. What is a relational model? (MAY 2010)


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 Value.

16. What is an entity-relationship model? (MAY 2008)


This data model is based on real world that consists of basic objects called
entities and of relationship among these objects. Entities are described in a database
by a set of attributes.

17. What is object based data model?


This model is based on collection of objects. An object contains values stored
in instance variables with in the object. An object also contains bodies of code that
operate on the object. These bodies of code are called methods. Objects that contain
same types of values and the same methods are grouped together into classes.
II/IV SEM Page 37
CS8492-DATABASE MANAGEMENT SYSTEM

18. What is a semi structured data model?


The semi structured data model permits the specification of data where
individual data items of the same type may have different sets of attributes.

19. What is Meta data? (MAY 2008)


Data dictionary contains Metadata-that is, data about data.

20. What is the use of data dictionary?


The DDL gets input as some instructions (statements) and generates some
output. The output of the DDL is placed in the data dictionary.

21. Define Relational Database.


A relational database is based on the relational model and uses a collection of
tables to represent both data and the relationships among those data. It also includes a
DML and DDL.

22. What is data base design ?


Database design mainly involves the design of the database schema. The
design of a complete database application environment that meets the needs of
the enterprise being modeled requires attention to a broder set of issues.

23. What is physical data independence?


Physical data independence deals with hiding the details of the storage
structure from user applications. The application should not be involved with
these issues, since there is no difference in the operation carried out against the
data.

24. What are different access types in DML?


The types of access are
 Retrieval of information stored in the database
 Insertion of new information into the database
 Deletion of information from the database
 Modification of information stored in the database

25. What is a procedural DML?


Procedural DMLs require a user to specify what data are needed and how to get
those data.

26. What is declarative DML?


Declarative DMLs also referred to as nonprocedural DMLs require a user
to specify what data are needed without specifying how to get those data.

27. Define Assertions


An assertion is any condition that the database must always satisfy.

II/IV SEM Page 38


CS8492-DATABASE MANAGEMENT SYSTEM

28. What is storage manager?


A storage manager is a program module that provides the interface
between the low level data stored in the database and the application programs and
queries submitted to the system.

29. What are the components of storage manager?


 Authorization and integrity manager
 Transaction manager
 File manager
 Buffer manager
30. List out the data structure used to implement the storage manager.
 Data files
 Data dictionary
 Indices

31. What is the use of embedded SQL? (MAY 2012) (NOV 2014)
A fundamental principle underlying embedded SQL, which we call the
dual-mode principle, is that any SQL statement that can be used interactively
can also be embedded in an application program.

32. Write short note on OPEN, FETCH and CLOSE statements.


OPEN:
EXEC SQL OPEN < Cursor name>;
Opens the specified cursor. A set of rows is thus identified and becomes the
current active set for the cursor.
FETCH:
EXEC SQL FETCH <Cursor name>
INTO <host variable
reference commalist>; Advances the
specified cursor to the next row in the
active set.
CLOSE:

EXEC SQL CLOSE <Cursor name>;


Closes the specified cursor. The cursor now has no current active set.

33. Discuss about dynamic SQL. (NOV 2014)


Dynamic SQL is a part of embedded SQL. It consists of a set of
―dynamic statements‖- which themselves are compiled ahead of time-
whose purpose is precisely to support the compilation and execution of
regular SQL statements that are constructed at run time.

34. What is a candidate key?


Let K be a set of attributes of relvar R. Then K is a candidate key for R
if and only if it has both of the following properties: Uniqueness and
Irreducibility

II/IV SEM Page 39


CS8492-DATABASE MANAGEMENT SYSTEM

35. What is a primary key?


It is possible for a given relation to have two or more candidate keys. In such a
case, the relational model has historically required that exactly one of those
keys be chosen as the primary key
36. What is an alternate key?
It is possible for a given relation to have two or more candidate keys. In such
a case, the relational model has historically required that exactly one of those
keys be chosen as the primary key and the others are then called alternate
keys.

37. What is a foreign key?


A foreign key is a set of attributes of some relvar R2 whose values are
required to match values of some candidate key of some relvar R1.

38. Distinguish between Key and Super Key? (Apr/May-2017)

Key A key is a single or combination of multiple fields. Its purpose is to access


or retrieve

data rows from table according to the requirement.

A superkey is a combination of attributes that can be uniquely used to identify a


database record. A table might have many superkeys.
PART B(13/15 Mark)

1. Explain the system structure of a database system with neat block diagram. (DEC
2007), (MAY 2010) (MAY 2012)

2. What is a data model? Explain various data model for describing the design of a
database at the logical level. (APRIL 2008), (MAY 2010)

3. What is Embedded SQL and explain with example? (NOV 2016)

4. Consider the following relations for a company database Application.(MAY 2009)

Employee (Eno, Name, Sex, DOB, Doj, Designation, Basic_Pay, Dept_No)

Department (DeptNo,Name)

Project (ProjNo, Name, Dept_No)

Works for (Eno,ProjNo,Date, Hours)


The attributes specified for each relation is self-explanatory. However the
business rules are stated as follows. A department can control a project.
An employee can work on any number of projects on a day. However an
employee cannot work more than once on a project he/she worked on that
day. The primary key are underlined.
(i). Identify the forging keys, Develop DDL to implement the above schema.

(i) Develop an SQL query to list the department number and


the number of Employee in each department.
II/IV SEM Page 40
CS8492-DATABASE MANAGEMENT SYSTEM

(ii)Develop a View that will keep track of the department number, the number
of employees in the department, and the total basic pay expenditure for each
department.

(iii)Develop an SQL query to list the details of employees who have worked in
more than three projects on a day.
5. Create an EMPLOYEE table and write the steps for various functions in an
SQL Like add, update, delete, save and join the various attributes of an
EMPLOYEE Table.(MAY-2007)

6. Consider a student registration database comprising of the given below table


schema.(Nov/Dec2015)
Student File

Student number Student name Address Telephone

Course File

Course Number Description Hours Professor Number

Professor File

Professor Number Name Office

Registration File

Student Number Course Number Date

Consider a suitable example of tuples/records for the above mentioned


tables and write DML statements (SQL) to answer for the queries listed
below:
(iii) What teaches a specific course and where is his/her office?

(iv) For a specific student number, in which courses is the student


registered and what is his/her name?

(v) Who are he professors for a specific student?

(vi) Who are he students registered in a specific course?

II/IV SEM Page 41


CS8492-DATABASE MANAGEMENT SYSTEM

7. Consider the relation schema given in fig1.Design and draw an ER diagram


that capture the information of this schema.(5)(Apr/May-2017)
Employee(empno,name,office,age)
Books(isbn,title,authors,publisher)
Loan (empno, isbn,date)
Write the following queries in relational algebra and SQL.
(i)Find the names of employees who have borrowed a book published
by McGraw-Hill.(5)
(ii)Find the names of employees who have borrowed all books published by
McGraw-Hill(5)

8. (i)State and explain the command DDL,DML,DCL with suitable example(7).


(ii) Justify the need of embedded SQL.Consider the relation
Student (student no, name, mark and grade).Write the embedded SQL statement
in C language to retrieve all the students records whose mark than 90. (6) (Nov/Dec-2017)

9. Explain about Purpose of Database System in database.

---------------------------------------------------------------------------------------

II/IV SEM Page 42

You might also like