Professional Documents
Culture Documents
Fiinal-Ece - Notes
Fiinal-Ece - Notes
UNIT – I
INTRODUCTION
Overview:
A Database is a collection of related data organised 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 actually a place where related piece of information is stored and various operations
can be performed on it.
What is Data?
Data is a collection of a distinct small unit of information. It can be used in a variety of forms like
text, numbers, media, bytes, etc. it can be stored in pieces of paper or electronic memory, etc.
Word ‘Data’ is originated from the word 'datum' that means 'single piece of information.' It is
plural of the word datum.
In computing, Data is information that can be translated into a form for efficient movement and
processing. Data is interchangeable.
A DBMS is software that allows creation, definition and manipulation of database, allowing users
to store, process and analyse data easily. DBMS provides us with an interface or a tool, to
perform various operations like creating database, storing data in it, updating data, creating
tables in the database and a lot more.
DBMS also provides protection and security to the databases. It also maintains data consistency
in case of multiple users.
Here are some examples of popular DBMS used these days:
MySql
Oracle
SQL Server
IBM DB2
PostgreSQL
Amazon SimpleDB (cloud based) etc.
Data Definition: It is used for creation, modification, and removal of definition that
defines the organization of data in the database.
Data Updation: It is used for the insertion, modification, and deletion of the actual data
in the database.
Data Retrieval: It is used to retrieve the data from the database which can be used by
applications for various purposes.
User Administration: It is used for registering and monitoring users, maintain data
integrity, enforcing data security, dealing with concurrency control, monitoring
performance and recovering information corrupted by unexpected failure.
It uses a digital repository established on a server to store and manage the information.
It can provide a clear and logical view of the process that manipulates data.
DBMS contains automatic backup and recovery procedures.
It contains ACID properties which maintain data in a healthy state in case of failure.
It can reduce the complex relationship between data.
It is used to support manipulation and processing of data.
It is used to provide security of data.
It can view the database from different viewpoints according to the requirements of the
user.
Controls database redundancy: It can control data redundancy because it stores all the
data in one single database file and that recorded data is placed in the database.
Data sharing: In DBMS, the authorized users of an organization can share the data among
multiple users.
Easily Maintenance: It can be easily maintainable due to the centralized nature of the
database system.
Reduce time: It reduces development time and maintenance need.
Backup: It provides backup and recovery subsystems which create automatic backup of
data from hardware and software failures and restores the data if required.
multiple user interface: It provides different types of user interfaces like graphical user
interfaces, application program interfaces
Telecom: There is a database to keeps track of the information regarding calls made,
network usage, customer details etc. Without the database systems it is hard to maintain
that huge amount of data that keeps updating every millisecond.
Industry: Where it is a manufacturing unit, warehouse or distribution centre, each one
needs a database to keep the records of ins and outs. For example distribution centre
should keep a track of the product units that supplied into the centre as well as the
products that got delivered out from the distribution centre on each day; this is where
DBMS comes into picture.
Banking System: For storing customer info, tracking day to day credit and debit
transactions, generating bank statements etc. All this work has been done with the help of
Database management systems.
Sales: To store customer information, production information and invoice details.
Airlines: To travel though airlines, we make early reservations; this reservation
information along with flight schedule is stored in database.
Education sector: Database systems are frequently used in schools and colleges to store
and retrieve the data regarding student details, staff details, course details, exam details,
payroll data, attendance details, fees details etc. There is a hell lot amount of inter-related
data that needs to be stored and retrieved in an efficient manner.
Online shopping: You must be aware of the online shopping websites such as Amazon,
Flipkart etc. These sites store the product information, your addresses and preferences,
credit details and provide you the relevant list of products based on your query. All this
involves a Database management system.
Data redundancy: Data redundancy refers to the duplication of data, lets say we are
managing the data of a college where a student is enrolled for two courses, the same
student details in such case will be stored twice, which will take more storage than
needed. Data redundancy often leads to higher storage costs and poor access time.
Data inconsistency: Data redundancy leads to data inconsistency, let’s take the same
example that we have taken above, a student is enrolled for two courses and we have
student address stored twice, now let’s say student requests to change his address, if the
address is changed at one place and not on all the records then this can lead to data
inconsistency.
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.
Dependency on application programs: Changing files would lead to change in application
programs.
Atomicity issues: Atomicity of a transaction refers to “All or nothing”, which means either
all the operations in a transaction executes or none.
Data Security: Data should be secured from unauthorised access, for example a student
in a college should not be able to see the payroll details of the teachers, such kind of
security constraints are difficult to apply in file processing systems.
Key-value storage: It is the simplest type of database storage where it stores every single item as
a key (or attribute name) holding its value, together.
Document-oriented Database: A type of database used to store data as JSON-like document. It
helps developers in storing data by using the same document-model format as used in the
application code.
Graph Databases: It is used for storing vast amounts of data in a graph-like structure. Most
commonly, social networking websites use the graph database.
Wide-column stores: It is similar to the data represented in relational databases. Here, data is
stored in large columns together, instead of storing in rows.
The type of database that uses the object-based data model approach for storing data in the
database system. The data is represented and stored as objects which are similar to the objects
used in the object-oriented programming language.
Data get stored in the form of records that are connected via links. Each child record in the tree
will contain only one parent. On the other hand, each parent record can have multiple child
records.
It is the database that typically follows the network data model. Here, the representation of data
is in the form of nodes connected via links between them. Unlike the hierarchical database, it
allows each record to have multiple children and parent nodes to form a generalized graph
structure.
1.10 Structure of Database Management System:
DML Compiler –
It processes the DML statements into low level instruction (machine language), so that
they can be executed.
DDL Interpreter –
It processes the DDL statements into a set of table containing Meta data (data about
data).
Authorization Manager:
It ensures role-based access control, i.e,. checks whether the particular person is
privileged to perform the requested operation or not.
Integrity Manager:
It checks the integrity constraints when the database is modified.
Transaction Manager:
It controls concurrent access by performing the operations in a scheduled way that it
receives the transaction. Thus, it ensures that the database remains in the consistent
state before and after the execution of transaction.
File Manager:
It manages the file space and the data structure used to represent information in the
database.
Buffer Manager:
It is responsible for cache memory and the transfer of data between the secondary
storage and main memory.
Data Files –
It stores the data.
Data Dictionary –
It contains the information about the structure of any database object. It is the repository
of information that governs the metadata.
Indices –
It provides faster retrieval of data item.
In this type of architecture, the database is readily available on the client machine; any request
made by client doesn’t require a network connection to perform the action on the database.
For example, let’s say you want to fetch the records of employee from the database and the
database is available on your computer system, so the request to fetch employee details will be
done by your computer and the records will be fetched from the database by your computer as
well. This type of system is generally referred as local database system.
External Level
Conceptual level describes the structure of the whole database for a group of users.
It is also called as the data model.
Conceptual schema is a representation of the entire content of the database.
This schema contains all the information to build relevant external records.
It hides the internal details of physical storage.
External level is related to the data which is viewed by individual end users.
This level includes a no. of user views or external schemas.
This level is closest to the user.
External view describes the segment of the database that is required for a particular user
group and hides the rest of the database from that user group.
1) Relational Data Model: This type of model designs the data in the form of rows and columns
within a table. Thus, a relational model uses tables for representing data and in-between
relationships. Tables are also called relations. This model was initially described by Edgar F. Codd,
in 1969. The relational data model is the widely used model which is primarily used by
commercial data processing applications.
4) Semi structured Data Model: This type of data model is different from the other three data
models (explained above). The semi structured data model allows the data specifications at
places where the individual data items of the same type may have different attributes sets. The
Extensible Markup Language, also known as XML, is widely used for representing the semi
structured data. Although XML was initially designed for including the mark up information to
the text document, it gains importance because of its application in the exchange of data.
DBMS (Database Management System) acts as an interface between the user and the database.
The user requests the DBMS to perform various operations such as insert, delete, update and
retrieval on the database. The components of DBMS perform these requested operations on the
database and provide necessary data to the users.
The components of DBMS can be divided into two parts: Functions and Services
The DML commands such as insert, update, delete, retrieve from the application
program are sent to the DML compiler for compilation into object code for
database access.
The object code is then optimized in the best way to execute a query by the query
optimizer and then send to the data manager.
The Data Manager is the central software component of the DBMS also knows as
Database Control System.
1 Data Dictionary:
Data Dictionary, which stores metadata about the database, in particular the
schema of the database.
Names of the tables, names of attributes of each table, length of attributes, and
number of rows in each table.
Detailed information on physical database design such as storage structure, access
paths, files and record sizes.
Usage statistics such as frequency of query and transactions.
Data dictionary is used to actually control the data integrity, database operation
and accuracy. It may be used as a important part of the DBMS
The DML complier converts the high level Queries into low level file access
commands known as compiled DML.
4 End Users:
1. The second class of users then is end user, who interacts with system from online
workstation or terminals.
2. Use the interface provided as an integral part of the database system software.
3. User can request, in form of query, to access database either directly by using
particular language, such as SQL, or by using some pre-developed application
interface.
4. Such request are sent to query evaluation engine via DML pre-compiler and DML
compiler
5. The query evaluation engine accepts the query and analyses it.
6. It finds the suitable way to execute the compiled SQL statements of the query.
7. Finally, the compiled SQL statements are executed to perform the specified
operation
1. Authorization Manager
2. Integrity Manager
3. Transaction Manager
4. File manager
5. Buffer Manager
5. Functions of DBMS:
a. DBMS free the programmers from the need to worry about the organization and
location of the data i.e. it shields the users from complex hardware level details.
b. DBMS can organize process and present data elements from the database. This
capability enables decision makers to search and query database contents in order to
extract answers that are not available in regular Reports.
c. Programming is speeded up because programmer can concentrate on logic of the
application.
d. It includes special user friendly query languages which are easy to understand by non
programming users of the system.
1.16.1. DDL (Data Definition Language) : DDL or Data Definition Language actually consists of the
SQL commands that can be used to define the database schema. It simply deals with descriptions
of the database schema and is used to create and modify the structure of database objects in the
database.
CREATE – is used to create the database or its objects (like table, index, function, views,
store procedure and triggers).
Syntax: 1
Syntax: 2
Example 2:
CREATE TABLE Students (ROLL_NO int(3), NAME varchar(20), SUBJECT varchar(20),);
DROP is used to delete a whole database or just a table. The DROP statement destroys
the objects like an existing database, table, index, or view.
A DROP statement in SQL removes a component from a relational database management
system (RDBMS).
Syntax :
Examples:
DROP TABLE table_name;
table_name: Name of the table to be deleted.
ALTER TABLE is used to add, delete/drop or modify columns in the existing table. It is also
used to add and drop various constraints on the existing table.
ADD is used to add columns into the existing table. Sometimes we may require to add
additional information, in that case we do not require to create the whole database
again, ADD comes to our rescue.
DROP COLUMN is used to drop column in a table. Deleting the unwanted columns from the
table.
Syntax: ALTER TABLE table_name
DROP COLUMN column_name;
Example :
ROLL_NO NAME
1 Ram
2 Abhi
3 Rahul
4 Tanu
QUERY:
To ADD 2 columns AGE and COURSE to table Student.
ALTER TABLE Student ADD (AGE number (3), COURSE varchar (40));
OUTPUT:
ROLL_NO NAME AGE COURSE
1 Ram
2 Abhi
3 Rahul
4 Tanu
OUTPUT:
ROLL_NO NAME AGE
1 Ram
2 Abhi
3 Rahul
4 Tanu
TRUNCATE–is used to remove all records from a table, including all spaces allocated for
the records are removed.
TRUNCATE statement is a Data Definition Language (DDL) operation that is used to mark
the extents of a table for deallocation (empty for reuse). The result of this operation
quickly removes all data from a table, typically bypassing a number of integrity enforcing
mechanisms. The TRUNCATE TABLE mytable statement is logically (though not physically)
equivalent to the DELETE FROM mytable statement (without a WHERE clause).
Syntax :
Truncate is normally ultra-fast and its ideal for deleting data from a temporary table.
Truncate preserves the structure of the table for future use, unlike drop table where the
table is deleted with its full structure.
Table or Database deletion using DROP statement cannot be rolled back, so it must be
used wisely.
After running the above query Student_details table will be truncated, i.e, the data will be
deleted but the structure will remain in the memory for further operations.
Columns can be also be given new name with the use of ALTER TABLE.
QUERY:
DQL statements are used for performing queries on the data within schema objects. The purpose
of the DQL Command is to get some schema relation based on the query passed to it.
Example of DQL:
Sample Table:
This query will return all the rows in the table with fields’ column1, column2.
Query to fetch the fields ROLL_NO, NAME, AGE from the table Student:
Output:
Output:
1.16.3 DML (Data Manipulation Language): The SQL commands that deals with the manipulation
of data present in the database belong to DML or Data Manipulation Language and this includes
most of the SQL statements.
Examples of DML:
The INSERT INTO statement of SQL is used to insert a new row in a table. There are two
ways of using INSERT INTO statement for inserting rows:
1. Only values: First method is to specify only the value of data to be inserted without the
column names.
2. Column names and values both: In the second method we will specify both the columns
which we want to fill and their corresponding values as shown below:
Output:
The table Student will now look like:
ROLL_NO NAME ADDRESS PHONE Age
1 Ram Delhi XXXXXXXXXX 18
2 RAMESH GURGAON XXXXXXXXXX 18
3 SUJIT ROHTAK XXXXXXXXXX 20
4 SURESH Delhi XXXXXXXXXX 18
3 SUJIT ROHTAK XXXXXXXXXX 20
2 RAMESH GURGAON XXXXXXXXXX 18
5 HARSH WEST BENGAL XXXXXXXXXX 19
Output:
The table Student will now look like:
Notice that the columns for which the values are not provided are filled by null. Which is the
default values for those columns.
Inserting all columns of a table: We can copy all the data of a table and insert into in a
different table.
We have used the SELECT statement to copy the data from one table and INSERT INTO
statement to insert in a different table.
Inserting specific columns of a table: We can copy only those columns of a table which
we want to insert into in a different table.
Syntax:
We have used the SELECT statement to copy the data of the selected columns only from
the second table and INSERT INTO statement to insert in first table.
Copying specific rows from a table: We can copy specific rows from a table to insert into
another table by using WHERE clause with the SELECT statement. We have to provide
appropriate condition in the WHERE clause to select specific rows.
Output:
This query will insert all the data of the table LateralStudent in the table Student.
The table Student will now look like,
Output:
This query will insert the data in the columns ROLL_NO, NAME and Age of the table
LateralStudent in the table Student and the remaining columns in the Student table will
be filled by null which is the default value of the remaining columns. The table Student
will now look like,
INSERT INTO Student SELECT * FROM Lateral Student WHERE Age = 18;
Output:
This query will select only the first row from table Lateral Student to insert into the table
Student. The table Student will now look like,
You need to provide multiple lists of values where each list is separated by ", ". Every list of value
corresponds to values to be inserted in each new row of the table.
Values in the next list tell values to be inserted in the next Row of the table.
Example:
Input :
INSERT INTO STUDENT (ID, NAME, AGE, GRADE, CITY) VALUES
(1,"AMIT KUMAR",15,10,"DELHI"),
(2,"GAURI RAO",18,12,"BANGALORE"),
(3,"MANAV BHATT",17,11,"NEW DELHI")
(4,"RIYA KAPOOR",10,5,"UDAIPUR");
The UPDATE statement in SQL is used to update the data of an existing table in database.
We can update single columns as well as multiple columns using UPDATE statement as
per our requirement.
WHERE condition;
Example Queries : Updating single column: Update the column NAME and set the value to
‘PRATIK’ in all the rows where Age is 20.
Output:
This query will update two rows(third row and fifth row) and the table Student will now
look like,
Updating multiple columns: Update the columns NAME to ‘PRATIK’ and ADDRESS to
‘SIKKIM’ where ROLL_NO is 1.
Output:
The above query will update two columns in the first row and the table Student will now
look like,
Note: For updating multiple columns we have used comma (,) to separate the names and
values of two columns.
Omitting WHERE clause: If we omit the WHERE clause from the update query then all of
the rows will get updated.
Output:
The table Student will now look like,
The DELETE Statement in SQL is used to delete existing records from a table. We can
delete a single record or multiple records depending on the condition we specify in the
WHERE clause.
Syntax:
DELETE FROM table_name WHERE some_condition;
Note: We can delete single as well as multiple records depending on the condition we
provide in WHERE clause. If we omit the WHERE clause then all of the records will be
deleted and the table will be empty.
Sample Table:
Example Queries:
Deleting single record: Delete the rows where NAME = ‘Ram’. This will delete only the
first row.
DELETE FROM Student WHERE NAME = 'Ram';
Output:
The above query will delete only the first row and the table Student will now look like,
Deleting multiple records: Delete the rows from the table Student where Age is 20. This
will delete 2 rows (third row and fifth row).
Output:
The above query will delete two rows(third row and fifth row) and the table Student will
now look like,
Delete all of the records: There are two queries to do this as shown below,
Output:
All of the records in the table will be deleted, there are no records left to display. The
table Student will become empty!
1.16.4. DCL (Data Control Language): DCL includes commands such as GRANT and REVOKE which
mainly deal with the rights, permissions and other controls of the database system.
TCL (transaction Control Language): TCL commands deal with the transaction within the
database.
A distributed database is basically a database that is not limited to one system; it is spread over
different sites, i.e, on multiple computers or over a network of computers. A distributed
database system is located on various sites that don’t share physical components. This may be
required when a particular database needs to be accessed by various users globally. It needs to
be managed such that for the users it looks like one single database.
Types:
1. Homogeneous Database:
In a homogeneous database, all different sites store database identically. The operating system,
database management system and the data structures used – all are same at all sites. Hence,
they’re easy to manage.
2.HeterogeneousDatabase:
In a heterogeneous distributed database, different sites can use different schema and software
that can lead to problems in query processing and transactions. Also, a particular site might be
completely unaware of the other sites. Different computers may use a different operating
system, different database application. They may even use different data models for the
database. Hence, translations are required for different sites to communicate.
1.Replication :
In this approach, the entire relation is stored redundantly at 2 or more sites. If the entire
database is available at all sites, it is a fully redundant database. Hence, in replication, systems
maintain copies of data.
This is advantageous as it increases the availability of data at different sites. Also, now query
requests can be processed in parallel.
However, it has certain disadvantages as well. Data needs to be constantly updated. Any change
made at one site needs to be recorded at every site that relation is stored or else it may lead to
inconsistency. This is a lot of overhead. Also, concurrency control becomes way more complex as
concurrent access now needs to be checked over a number of sites.
2. Fragmentation:
In this approach, the relations are fragmented (i.e., they’re divided into smaller parts) and each
of the fragments is stored in different sites where they’re required. It must be made sure that
the fragments are such that they can be used to reconstruct the original relation (i.e, there isn’t
any loss of data). Fragmentation is advantageous as it doesn’t create copies of data, consistency
is not a problem.
A relational database is a type of database that stores and provides access to data points that are
related to one another. Relational databases are based on the relational model, an intuitive,
straightforward way of representing data in tables. In a relational database, each row in the table
is a record with a unique ID called the key. The columns of the table hold attributes of the data,
and each record usually has a value for each attribute, making it easy to establish the
relationships among data points.
How relational databases are structured
The relational model means that the logical data structures—the data tables, views, and
indexes—are separate from the physical storage structures. This separation means that database
administrators can manage physical data storage without affecting access to that data as a logical
structure. For example, renaming a database file does not rename the tables stored within it.
The distinction between logical and physical also applies to database operations, which are
clearly defined actions that enable applications to manipulate the data and structures of the
database. Logical operations allow an application to specify the content it needs, and physical
operations determine how that data should be accessed and then carries out the task.
To ensure that data is always accurate and accessible, relational databases follow certain
integrity rules. For example, an integrity rule can specify that duplicate rows are not allowed in a
table in order to eliminate the potential for erroneous information entering the database.
What is table
The RDBMS database uses tables to store data. A table is a collection of related data entries and
contains rows and columns to store data.
A table is the simplest example of data storage in RDBMS.
Let's see the example of student table.
What is field
Field is a smaller entity of the table which contains specific information about every record in the
table. In the above example, the field in the student table consist of id, name, age, course.
What is column?
A column is a vertical entity in the table which contains all information associated with a specific
field in a table. For example: "name" is a column in the above table which contains all
information about student's name.
Name
Anusha
Madhu
Samskruthi
Ashwini
Sragavi
NULL Values
The NULL value of the table specifies that the field has been left blank during record creation. It
is totally different from the value filled with zero or a field that contains space.
Data Integrity
There are the following categories of data integrity exist with each RDBMS:
Domain integrity: It enforces valid entries for a given column by restricting the type, the format,
or the range of values.
Referential integrity: It specifies that rows cannot be deleted, which are used by other records.
DBMS Vs RDBMS
DBMS RDBMS
RDBMS applications store data in a tabular
DBMS applications store data as file.
form.
In RDBMS, the tables have an identifier called
In DBMS, data is generally stored in either a
primary key and the data values are stored in
hierarchical form or a navigational form.
the form of tables.
Normalization is not present in DBMS. Normalization is present in RDBMS.
RDBMS defines the integrity constraint for the
DBMS does not apply any security with
purpose of ACID (Atomocity, Consistency,
regards to data manipulation.
Isolation and Durability) property.
in RDBMS, data values are stored in the form of
DBMS uses file system to store data, so there tables, so a relationship between these data
will be no relation between the tables. values will be stored in the form of a table as
well.
RDBMS system supports a tabular structure of
DBMS has to provide some uniform methods
the data and a relationship between them to
to access the stored information.
access the stored information.
DBMS does not support distributed database. RDBMS supports distributed database.
DBMS is meant to be for small organization RDBMS is designed to handle large amount of
and deal with small data. it supports single data. it supports multiple users.
user.
Examples of DBMS are file systems xml etc.Example of RDBMS are mysql
UNIT –II
DATABASE DESIGN ER MODEL
2 .1 What is ER Diagram?
ER Diagram stands for Entity Relationship Diagram,
also known as ERD is a diagram that displays the
relationship of entity sets stored in a database.
2.3 Following are the main components and its symbols in ER Diagrams:
2.3.1. Entity
An entity is an object or component of data. An entity is represented as rectangle in an ER
diagram.
For example: In the following ER diagram we have two entities Student and College and these
two entities have many to one relationship as many students study in a single college. We will
read more about relationships later, for now focus on entities.
2.3.2. Attribute
An attribute describes the property of an entity. An attribute is represented as Oval in an ER
diagram. There are four types of attributes:
1. Key Attribute:
A key attribute can uniquely identify an entity
from an entity set. For example, student roll
number can uniquely identify a student from
a set of students. Key attribute is represented
by oval same as other attributes however the
text of key attribute is underlined.
2. Composite Attribute:
3. Multivalued attribute:
An attribute that can hold multiple values is known as Multivalued attribute. It is represented
with double ovals in an ER Diagram. For example – A person can have more than one phone
numbers so the phone number attribute is Multivalued.
4. Derived attribute:
A derived attribute is one whose value is dynamic and derived from another attribute. It is
represented by dashed oval in an ER Diagram. For example – Person age is a derived attribute as
it changes over time and can be derived from another attribute (Date of birth).
2.3.3. Relationship
A relationship is represented by diamond shape in ER diagram; it shows the relationship among
entities. There are four types of relationships:
1. One to One
2. One to Many
3. Many to One
4. Many too Many
When a single instance of an entity is associated with more than one instances of another entity
then it is called one to many relationship. For example – a customer can place many orders but a
order cannot be placed by many customers.
When more than one instances of an entity is associated with a single instance of another entity then
it is called many to one relationship. For example – many students can study in a single college but a
student cannot study in many colleges at the same time.
When more than one instances of an entity is associated with more than one instances of another
entity then it is called many to many relationship. For example, a can be assigned to many projects
and a project can be assigned to many students.
Any defined object in the database which can be used to reference or store data is known as a
database object. Database objects can be made using the create command. These database
objects are used for holding and manipulating the data in the database.
1. View: Subsets of data from more than one table are logically represented.
2. Table: Composed of rows and columns, the table is the primary form of data representation.
3. Sequence: Sequence generates the primary key values.
4. Synonym: It is an alternative name for a specific object.
5. Index: It improves the performance of some particular queries.
Example: CREATE TABLE dept (deptno Number (2) , dname VARCHAR2(14) , loc VARCHAR2 (14) );
2.View :
This object is used in the database to create a type of view of the database. It is a logical view
based on one or more tables or even another view. A view does not contain any data of its own
but is used to view data in other tables. The view is based on a table, and that table is known as
the base table. The data dictionary stores the view as a SELECT statement.
Syntax:
Example:
3. Sequence:
This object in the database is used to create a sequence in the database. It is a user created
database object which can be shared by more than two users to create a unique integer in the
database. The most often use of sequence is to create a primary value in the database. This
primary value is unique for each row. Once the sequence is generated, it is decremented or
incremented using an Oracle routine.
4. Index – This database object is used to create a indexes in database. An Oracle server index
is a schema object that can speed up the retrieval of rows by using a pointer. Indexes can be
created explicitly or automatically. If you do not have an index on the column, then a full table
scan occurs.
An index provides direct and fast access to rows in a table. Its purpose is to reduce the
necessity of disk I/O by using an indexed path to locate data quickly. The index is used and
maintained automatically by the Oracle server. Once an index is created, no direct activity is
required by the user. Indexes are logically and physically independent of the table they index.
This means that they can be created or dropped at any time and have no effect on the base
tables or other indexes.
Syntax: CREATE INDEX index
ON table (column [, column]...);
Example: CREATE INDEX emp_last_name_idx
ON employees(last_name);
5.Synonym – This database object is used to create a indexes in database.It simplify access to
objects by creating a synonym(another name for an object). With synonyms, you can Ease
referring to a table owned by another user and shorten lengthy object names.To refer to a
table owned by another user, you need to prefix the table name with the name of the user
who created it followed by a period. Creating a synonym eliminates the need to qualify the
object name with the schema and provides you with an alternative name for a table, view,
sequence, procedure, or other objects. This method can be especially useful with lengthy
object names, such as views.
There are five such types of attributes: Simple, Composite, Single-valued, Multi-valued, and
Derived attribute.
These are explained as following below.
2. Composite Attribute
An attribute which can be splitted into components is a composite attribute.
Example: The address can be further splitted into house number, street number, city, state,
country and pincode, the name can also be splitted into first name middle name and last name.
4.Multi-Valued Attribute :
The attribute which takes up more than a single value for each entity instance is multi-valued
attribute.
Example: Phone number of a student: Landline and mobile.
5.Dervied Attribute :
An attribute that can be derived from other attributes is derived attribute.
Example: Total and average marks of a student .
2.8.1 Entity
Entities are represented by means of rectangles. Rectangles are named with the entity set they
represent.
2.8.2 Attributes
Attributes are the properties of entities. Attributes are represented by means of ellipses. Every
ellipse represents one attribute and is directly connected to its entity (rectangle).
2.8.3 Composite: they are further divided in a tree like structure. Every node is then connected
to its attribute. That is, composite attributes are represented by ellipses that are connected with
an ellipse.
2.9 Relationship
The association among entities is called a relationship. For example, an employee works_at a
department, a student enrolls in a course. Here, Works_at and Enrolls are called relationships.
Relationship Set
A set of relationships of similar type is called a relationship set. Like entities, a relationship too
can have attributes. These attributes are called descriptive attributes.
Degree of Relationship
The number of participating entities in a relationship defines the degree of the relationship.
Binary = degree 2
Ternary = degree 3
n-ary = degree
2.10 Mapping Cardinalities
Cardinality defines the number of entities in one entity set, which can be associated with the
number of entities of other set via relationship set.
One-to-one − One entity from entity set A can be associated with at most one entity of
entity set B and vice versa.
One-to-many − One entity from entity set A can be associated with more than one
entities of entity set B however an entity from entity set B, can be associated with at
most one entity.
Many-to-one − More than one entities from entity set A can be associated with at most
one entity of entity set B, however an entity from entity set B can be associated with
more than one entity from entity set A.
Many-to-many − One entity from A can be associated with more than one entity from B
and vice versa.
Many-to-one − When more than one instance of entity is associated with the
relationship, it is marked as 'N:1'. The following image reflects that more than one
instance of an entity on the left and only one instance of an entity on the right can be
associated with the relationship. It depicts many-to-one relationship.
Many-to-many − The following image reflects that more than one instance of an entity
on the left and more than one instance of an entity on the right can be associated with
the relationship. It depicts many-to-many relationship.
Participation Constraints
Total Participation − Each entity is involved in the relationship. Total participation is
represented by double lines.
Partial participation − Not all entities are involved in the relationship. Partial
participation is represented by single lines.
2.12 Key
A key is an attribute or set of attributes which helps us in uniquely identifying the rows of a
table. It also helps in establishing relationship among tables. We will now see how this is done
with the help of examples.
Example: If we have the details of students of a classroom stored in Student table as follows:
Now, from this classroom, if we want to call a student whose name is ‘Andrew’ we don't know
which ‘Andrew’ to call as there are two students with the same name. Also, we if know the age
of student ‘Andrew’ we can’t distinguish between both the students because both are having
the same age. So, there must some value through which we can distinguish and uniquely
identify the students. The ‘Roll_no’ attribute will help us in uniquely identifying the rows in a
table. We can say that ‘Roll_no’ is the key here. Now, if we know the ‘Roll_no’ of the student
then there will be no confusion and we can easily select the student from here.
Super Key
Candidate Key
Primary Key
Alternate Key
Foreign Key
Example: In the given Student Table we can have the following keys as the super key.
1. {Roll_no}
2. {Registration_no}
3. {Roll_no, Registration_no},
4. {Roll_no, Name}
5. {Name, Registration_no}
6. {Roll_no, Name, Registration_no}
All the above keys are able to uniquely identify each row. So, each of these keys is super key.
Here you can see that by using Roll_no only, we can uniquely identify the rows but if you are
making a super key, then you will try to find all the possible cases of keys that can be used to
identify data uniquely.
If the subset of the candidate key is a super key, then that candidate key is not a valid
candidate key.
Example: In the above example, we had 6 super keys but all of them cannot become a
candidate key. Only those super keys would become a candidate key which have no redundant
attributes.
1. {Roll_no}: This key doesn't have any redundant or repeating attribute. So, it can be
considered as a candidate key.
2. {Registration_no}: This key also doesn't have any repeating attribute. So, it can be
considered as a candidate key.
3. {Roll_no, Registration_no}: This key cannot be considered as a candidate key because
when we take the subset of this key we get two attributes i.e Roll_no or
Registration_no. Each of these attributes is the candidate key. So, it is not a minimal
super key. Hence, this key is not a candidate key.
4. {Roll_no, Name}: This key cannot be considered as a candidate key because when we
take the subset of this key we get two attributes i.e. Roll_no or Name. Roll_no is a
candidate key. So, it is not a minimal super key. Hence, this key is not a candidate key.
5. {Name, Registration_no}: This key cannot be considered as a candidate key because
when we take the subset of this key we get two attributes i.e Registration_no or Name.
Registration_no is a candidate key. So, it is not a minimal super key. Hence, this key is
not a candidate key.
6. {Roll_no, Name, Registration_no}: This key cannot be considered as a candidate key
because when we take the subset of this key we get three attributes i.e Roll_no,
Registration_no and Name. Two of these attributes i.e Roll_no and Registration_no are
the candidate key. So, it is not a minimal superkey. Hence, this key is not a candidate
key.
So, from the above discussion, we conclude that we can have only 2 out of above 6
super keys as the candidate key. i.e. (Roll_no) and(Registration_no).
Example: In the above example, since we have made ‘Roll_no’ as the Primary Key our Alternate
Key would be ‘Registration_no’.
Example: If we have two tables of Student and Course then we can establish a relationship
between these two tables using a foreign key. The ‘Course_id’ in the Student table is the
foreign key as it establishes the link between the Student and Course Table. So, if we need to
find the information about any course opted by any student then we can go the Course table
using the foreign key.
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.
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
There are many types of Integrity Constraints in DBMS. 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
2.14.1Domain 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.
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”.
Example:
Insert 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.
1. Strong entity
2. Weak entity
Representation
The strong entity is represented by a single rectangle.
Relationship between two strong entities is represented by a single diamond.
weak entity is an entity set that does not have sufficient attributes for Unique
Identification of its records
Simply a weak entity is nothing but an entity which does not have a primary key
attribute
It contains a partial key called as discriminator which helps in identifying a group of
entities from the entity set
Discriminator is represented by underlining with a dashed line
Representation
Relational database means the data is stored as well as retrieved in the form of relations
(tables). Table 1 shows the relational database with only one relation called STUDENT which
stores ROLL_NO, NAME, ADDRESS, PHONE and AGE of students.
Student Database:
Roll _No NAME ADDRESS PHONE AGE
401 AKHILA VISHAKAPATNAM 9912204100 24
402 SAMSKRUTHI DUBAI 9704216317 25
403 ASHWINI REDDY LONDON 9346261029 28
404 SANDHYA BANGALORE 9951063698 26
405 SHRAGVI GOKARANA 9755858898 27
These are some important terminologies that are used in terms of relation.
Attribute: Attributes are the properties that define a relation. e.g.; ROLL_NO, NAME etc.
Tuple: Each row in the relation is known as tuple. The above relation contains 4 tuples, one of
which is shown as:
Degree: The number of attributes in the relation is known as degree of the relation.
The STUDENT relation defined above has degree 5.
Cardinality: The number of tuples in a relation is known as cardinality. The STUDENT relation
defined above has cardinality 4.
Column: Column represents the set of values for a particular attribute. The column ROLL_NO is
extracted from relation STUDENT.
Roll _No
401
402
403
404
405
Data Manipulation Language: It is used to manipulate data in the relations. e.g.; INSERT,
DELETE, UPDATE and so on.
Data Query Language: It is used to extract the data from the relations. e.g.; SELECT
So first we will consider the Data Query Language. A generic query to retrieve from a relational
database is:
1. SELECT [DISTINCT] Attribute_List FROM R1,R2….RM
2. [WHERE condition]
3. [GROUP BY (Attributes)[HAVING condition]]
4. [ORDER BY(Attributes)[DESC]];
Part of the query represented by statement 1 is compulsory if you want to retrieve from a
relational database. The statements written inside [] are optional. We will look at the possible
query combination on relation shown in Table 1.
Case 1: If we want to retrieve attributes ROLL_NO and NAME of all students, the query will be:
Case 2: If we want to retrieve ROLL_NO and NAME of the students whose ROLL_NO is greater
than 2, the query will be:
Roll_No Name
403 ASHWINI REDDY
404 SANDHYA
405 SHRAGVI
CASE 3: If we want to retrieve all attributes of students, we can write * in place of writing all
attributes as:
SELECT * FROM STUDENT WHERE ROLL_NO>2;
CASE 4: If we want to represent the relation in ascending order by AGE, we can use ORDER BY
clause as:
Note: ORDER BY AGE is equivalent to ORDER BY AGE ASC. If we want to retrieve the results in
descending order of AGE, we can use ORDER BY AGE DESC.
COUNT (PHONE)
5
SUM (AGE) = 74
In the same way, MIN, MAX and AVG can be used. As we have seen above, all aggregation
functions return only 1 row.
AVERAGE: It gives the average values of the tupples. It is also defined as sum divided by count
values.
Syntax:AVG(attributename)
OR
Syntax:SUM(attributename)/COUNT(attributename)
The above mentioned syntax also retrieves the average value of tupples.
MAXIMUM:It extracts the maximum value among the set of tupples.
Syntax:MAX(attributename)
MINIMUM:It extracts the minimum value amongst the set of all the tupples.
Syntax:MIN(attributename)
GROUP BY: Group by is used to group the tuples of a relation based on an attribute or group of
attribute. It is always combined with aggregation function which is computed on group
SELECT ADDRESS, SUM(AGE) FROM STUDENT GROUP BY (ADDRESS);
ADDRESS AGE
VISHAKAPATNAM 24
DUBAI 25
LONDON 28
BANGALORE 26
GOKARANA 27
UNIT –III
STRUCTURED QUERY LANGUAGE (SQL)
Structured Query Language is a standard Database language which is used to create, maintain
and retrieve the relational database. Following are some interesting facts about SQL.
SQL is case insensitive. But it is a recommended practice to use keywords (like SELECT,
UPDATE, CREATE, etc) in capital letters and use user defined things (liked table name,
column name, etc) in small letters.
We can write comments in SQL using “–” (double hyphen) at the beginning of any line.
SQL is the programming language for relational databases (explained below) like
MySQL, Oracle, Sybase, SQL Server, Postgre, etc. Other non-relational databases (also
called NoSQL) databases like MongoDB, DynamoDB, etc do not use SQL
Although there is an ISO standard for SQL, most of the implementations slightly vary in
syntax. So we may encounter queries that work in SQL Server but do not work in MySQL.
3.4 What is SQL Operator: A set operator in SQL is a keyword that lets you combine the results
of two queries into a single query.
Sometimes when working with SQL, you’ll have a need to query data from two more tables. But
instead of joining these two tables, you’ll need to list the results from both tables in a single
result, or in different rows. That’s what set operators do.
It uses two (or more) SELECT queries, with a set operator in the middle.
There are a few things to keep in mind though.
When selecting your columns, the number of columns needs to match between queries,
and the data type of each column needs to be compatible.
So, if you select three columns in the first query, you need to select three columns in the
second query. The data types also need to be compatible, so if you select a number and
two character types in the first query, you need to do the same in the second query.
Also, if you want to order your results, the ORDER BY must go at the end of the last query.
You can’t add ORDER BY inside each SELECT query before the set operator.
DEPARTMENT_ID DEPARTMENT_NAME
1 Executive
2 HR
3 Sales
4 Development
5 Support
6 Research
This shows a list of 6 departments and 16 employees. The manager_id column in the employee table
refers to the employee_id column in the same table. I’ll show you how to use this later in this guide.
If you want to follow along and create the database yourself, here is the SQL:
CREATE TABLE employee (employee _id NUMBER(5) PRIMARY KEY , full_name VARCHAR2(100),
department _id NUMBER (5) REFERENCES department (department_id), job_roleVARCHAR2(100),
manager_id NUMBER(5) );
INSERT INTO department (department _id ,department _name ) VALUES (1, ‘Executive’);
INSERT INTO department (department _id ,department _name ) VALUES (2, ‘HR’);
INSERT INTO department (department _id ,department _name ) VALUES (3, ‘Sales’);
INSERT INTO department (department _id ,department _name ) VALUES (4, ‘Development’);
INSERT INTO department (department _id ,department _name ) VALUES (5, ‘Support’);
INSERT INTO department (department _id ,department _name ) VALUES (6, ‘Research’);
Our sample data for this article uses a customer and employee table.
Customer Employee
But looking at this, we can’t tell which record comes from each table. Often we don’t need to
know, but sometimes we do.
How can we do that? We can add a static value to each query to indicate which table it came
from, or what type of record it is. As long as the number and type of columns match, the query
will work.
SELECT ‘ Customer ‘ AS record_type , First_name , last_name FROM Customer UNION SELECT
‘Employee’ , First _name , Last_name FROM employee ;
Result :
In this query, I added in a value of ‘Customer’ to display for all records from the Customer
table. It has a column alias of record_type. The same column is labelled as ‘Employee’ from
the employee table. Looking at the results you can see which records came from which table.
You don’t need to specify the column aliases on the second table. Oracle will know that the
first columns match and use the alias already provided in the first query.
All of the set operators support standard keywords inside the SELECT statement. The set
operator is just a way of combining results.
So, you can add WHERE clauses like this if you need to:
SELECT ‘ Customer ‘ AS record_type , first _name , last_name FROM customer WHERE
status = “ Active” UNION SELECT ‘ Employee ‘ , first_name , last_name FROM
employee WHERE emp_status = ‘ Current ‘ ORDER BY record_type ,first_name ,
last_name ;
The UNION and JOIN keywords both combine results from two different tables or queries.
UNION combines data into separate rows, and JOIN combines data into separate columns.
When performing a JOIN, there is a column that matches between the two tables, and
additional data may be displayed.
If we wanted to JOIN our employee and customer tables, our query might look like this:
Result :
First_name last_name
Stephen Jones
Mark Smith
Denise King
Paula Johnson
Richard Archer
Christina Jones
Michael McDonald
Richard Smith
We can use different JOIN types to display different records based on matches being found,
but in general, that’s how a join is different to a UNION.
MINUS:
Another set operator we can use is the MINUS keyword.
The MINUS set operator will return results that are found in the first query specified that
don’t exist in the second query.
Using our example data, we could use the MINUS set operator to find all names in the
customer table that don’t exist in the employee table.
First_name last_name
Mark Smith
Denise King
Richard Archer
If a result exists in the employee table as well as the customer table, it is not shown. Only the
results from the customer table that are not in the employee table are shown.
The EXCEPT keyword is another set operator you might see in your code or in online
examples.
EXCEPT is the same as MINUS – they both show results from one query that don’t exist in
another query.
However, MINUS is an Oracle-specific keyword, and EXCEPT is in other databases such as SQL
Server.
So, if you see EXCEPT anywhere, just know it’s the same as MINUS but for a different
database.
INTERSECT:
The INTERSECT keyword allows you to find results that exist in both queries. Two SELECT
statements are needed, and any results that are found in both of them are returned if
INTERSECT is used.
Using our example data, we could use the INTERSECT set operator to find all names in the
customer table that don’t exist in the employee table.
Result :
first_name last_name
Stephen Jones
Paula Johnson
This shows all names that are in both the customer and employee table.
If we want to order these, we add an ORDER BY at the end.
Paula Johnson
Stephen Jones
The difference between UNION and INTERSECT is that UNION gets results from both queries
and combines them, while INTERSECT gets results that only exist in both queries.
So, if Query 1 returns records A and B, and Query 2 returns records B and C, UNION would
return A, B and C. INTERSECT would only return B.
Sub queries:
FROM
The SQL FROM clause is where you specify where your data is to be retrieved from. This will
often be a table in your database, but it can also be a view or a subquery.
The syntax of the FROM clause looks the same regardless of what you’re selecting from:
This example selects data from one table: the employee table. We can’t actually tell if it’s a
table or a view by looking at the name, but it doesn’t matter for the purpose of this query.
You can also use joins to SELECT data from multiple tables. I’ve written an entire post on
joins, as they are a pretty big feature of SQL, but a basic query with a join looks like this:
This query will show the employee’s first name and last name, as well as their department
name. It uses an INNER JOIN to match records based on each table’s department ID.
WHERE:
The WHERE clause of the SQL SELECT statement is where you determine which rows to return
from your table or view. It’s an optional clause, so if you don’t specify a WHERE clause in your
query, you’ll get all the records:
The criteria is a rule that is checked against each row. If the criteria is true for a row, the row is
included in the results. If it is false, the row is not included.
For example, this query shows all employees with a first_name of John.
The WHERE clause can get quite complicated. You can have multiple criteria using the AND
or OR keywords, you can use brackets to group criteria, you can have greater than and less
than, partial matches, and much more.;
GROUP BY :
The SQL GROUP BY clause is used when you are using aggregate functions and want to
specify what values you want to have those aggregate functions calculated by.
For example, this query will count all employees:
HAVING:
The HAVING clause lets you filter a SELECT query that uses a GROUP BY clause based on the
results after a GROUP BY.
It uses the same concept as a WHERE clause, except the WHERE clause filters data before the
grouping, and HAVING filters data after the grouping.
For example, this query shows the count of employees in each department where there is
more than 1 employee in the department.
SELECT dept _id , COUNT (*) FROM employee GROUP BY dept_id HAVING COUNT ( *)
>1;
ORDER BY
The ORDER BY clause lets you specify the order you want the query results to be displayed in.
The database does not guarantee the order that the results are returned in. Even if it looks
like there is an order (e.g. ordered by ID), if you run the same query at a later date, the order
could change.
So, if you want your data in a specific order, you can use the ORDER BY clause:
https://www.databasestar.com/sql-joins/
CHAPTER – IV
DEPENDENCIES AND NORMAL FORMS
4.1 What is Normalization?
Normalization is a database design technique that reduces data redundancy and eliminates
undesirable characteristics like Insertion, Update and Deletion Anomalies. A normalization rule
divides larger tables into smaller tables and links them using relationships. The purpose of
Normalisation in SQL is to eliminate redundant (repetitive) data and ensure data is stored
logically.
The inventor of the relational model Edgar Codd proposed the theory of normalization of data
with the introduction of the First Normal Form, and he continued to extend theory with Second
and Third Normal Form. Later he joined Raymond F. Boyce to develop the theory of Boyce-Codd
Normal Form.
As per the rule of first normal form, an attribute (column) of a table cannot hold multiple values.
It should hold only atomic values.
In our database, we have two people with the same name Robert Phil, but they live in different
places.
Hence, we require both Full Name and Address to identify a record uniquely. That is a composite
key.
It is clear that we can’t move forward to make our simple database in 2 nd Normalization form
unless we partition the table above.
We have divided our 1NF table into two tables viz. Table 1 and Table2. Table 1 contains member
information. Table 2 contains information on movies rented.
We have introduced a new column called Membership_id which is the primary key for table 1.
Records can be uniquely identified in Table 1 using membership id
4.5.1: Database – Foreign Key: From the above table, Membership_ID is the Foreign Key
Membership Movies data
1 Pirates of the Caribbean
1 Clash of Titans
2 Forgetting Sarah Marshal
2 Daddy ‘s little Girl
3 Clash of Titans
Foreign Key references the primary key of another Table! It helps connect your Tables
A foreign key can have a different name from its primary key
It ensures rows in one table have corresponding rows in another
Unlike the Primary key, they do not have to be unique. Most often they aren’t
Foreign keys can be null even though primary keys can not
Foreign Key
Consider the table 1. Changing the non-key column Full Name may change Salutation.
To move our 2NF table into 3NF, we again need to again divide our table.
We have again divided our tables and created a new table which stores salutation
There are no transitive functional dependencies, and hence our table is in 3NF
In Table 3 Salutation ID is primary key, and in Table 1 Salutation ID is foreign to primary key in
Table 3
It is an advance version of 3NF that’s why it is also referred as 3.5NF. BCNF is stricter than 3NF. A
table complies with BCNF if it is in 3NF and for every functional dependency X->Y, X should be the
super key of the table.
Example: Suppose there is a company wherein employees work in more than one department.
They store the data like this:
The table is not in BCNF as neither emp_id nor emp_dept alone are keys.
To make the table comply with BCNF we can break the table in three tables like this:
emp_nationality table:
emp_id emp_nationality
1001 Austrian
1002 American
emp_dept table:
emp_dept_mapping table:
emp_id emp_dept
1001 Production and planning
1001 stores
1002 design and technical support
1002 Purchasing department
Functional dependencies:
emp_id -> emp_nationality
emp_dept -> {dept_type, dept_no_of_emp}
Candidate keys:
For first table: emp_id
For second table: emp_dept
For third table: {emp_id, emp_dept}
This is now in BCNF as in both the functional dependencies left side part is a key.
4.8 A good database design has many benefits and is a goal to achieve for every DBA −
Easy Retrieval of Information
If the design is developed properly, then it would be easier to retrieve information. Correct
design means the tables, constraints, and relationships created are flawless.
Easier Modification
Changes that you make to the value of a given field will not adversely affect the values of other
fields within the table.
Easy to Maintain
The database structure should be easy to maintain. The design is perfect if changes in one field is
not affecting changes in another field.
Information
With a good design, you can enhance the quality and consistency of information.
Well-designed Database
If the database is well defined, then the flaws and issues of a poorly designed database will not
need to be addressed.
Related data is scattered over various tables. A change must be updated at many places.
It's possible that the information is only half present; it's there in one table, but missing in
another one.
Data is inconsistent or ambiguous (poly interpretable).
The database is unnecessary complex, hacked with lots of tricks. The database designer
done unnecessary complex things, where it could have been done so much easier.
The database has 'hidden' information, for example by the sequence of rows in a table.
The database is slow, inflexible, hard to extend and cannot handle all real life situations.
Axioms is a set of inference rules used to infer all the functional dependencies on a
Axiom
relational database.
It is a rule that suggests if you have a table that appears to contain two entities which are
Decomposition
determined by the same primary key then you should consider breaking them up into two
different tables.
Dependent It is displayed on the right side of the functional dependency diagram.
It suggests that if two tables are separate, and the PK is the same, you should consider
Union
putting them together
Multivalued Dependency
Trivial Functional Dependency
Non-Trivial Functional Dependency
Transitive Dependency
Example:
Car_model Maf_year Color
H001 2017 Metallic
H001 2017 Green
H005 2018 Metallic
H005 2018 Blue
H010 2015 Metallic
H033 2012 Gray
In this example, maf_year and color are independent of each other but dependent on
car_model. In this example, these two columns are said to be multivalue dependent on
car_model.
This dependence can be represented like this:
car_model -> maf_year
car_model-> colour
4.13.2 Trivial Functional Dependency in DBMS
The Trivial dependency is a set of attributes which are called a trivial if the set of attributes are
included in that attribute.
So, X -> Y is a trivial functional dependency if Y is a subset of X. Let’s understand with a Trivial
Functional Dependency Example.
For example:
Emp_id Emp_name
AS555 Harry
AS811 George
AS999 Kevin
Example:
(Company} -> {CEO} (if we know the Company, we knows the CEO name)
But CEO is not a subset of Company, and hence it’s non-trivial functional dependency.
Example:
{Company} -> {CEO} (if we know the compay, we know its CEO’s name)
{ Company} -> {Age} should hold, that makes sense because if we know the company name, we
can know his age.
Axioms –
Secondary Rules : These rules can be derived from the above axioms.
UNIT-V
TRANSACTIONS
5.1 Transactions:
OR
A transaction is an action or series of actions that are being performed by a single user or
application program, which reads or updates the contents of the database.
A transaction can be defined as a logical unit of work on the database. This may be an entire
program, a piece of a program, or a single command (like the SQL commands such as INSERT or
UPDATE), and it may engage in any number of operations on the database. In the database
context, the execution of an application program can be thought of as one or more transactions
with non-database processing taking place in between.
Example: Suppose an employee of bank transfers Rs 800 from X's account to Y's account. This
small transaction contains several low-level tasks:
X – ACCOUNT Y-ACCOUNT
Open_Account(X) Open_Account(y)
Old_Balance = X.balance Old _Balance = Y.Balance
New_Balance = Old_Balance - 800 New_Balance = Old_Balance + 800
X.balance = New_Balance Y.balance = New_Balance
Close_Account(X) Close_Account(Y)
Read(X): Read operation is used to read the value of X from the database and stores it
in a buffer in main memory.
Write(X): Write operation is used to write the value back to the database from the
buffer.
Let's take an example to debit transaction from an account which consists of following
operations:
1. R(X);
2. X = X - 500;
3. W(X);
For example: If in the above transaction, the debit transaction fails after executing operation 2
then X's value will remain 4000 in the database which is not acceptable by the bank.
Property of Transaction
1. Atomicity
2. Consistency
3. Isolation
4. Durability
Atomicity
It states that all operations of the transaction take place at once if not, the transaction is
aborted.
There is no midway, i.e., the transaction cannot occur partially. Each transaction is
treated as one unit and either run to completion or is not executed at all.
Example: Let's assume that following transaction T consisting of T1 and T2. A consists of Rs 600
and B consists of Rs 300. Transfer Rs 100 from account A to account B.
T1 T2
Read(A) Read(B)
A:=A-100 Y:=Y+100
Write(A) Write(B)
Isolation
It shows that the data which is used at the time of execution of a transaction cannot be
used by the second transaction until the first one is completed.
In isolation, if the transaction T1 is being executed and using the data item X, then that
data item can't be accessed by any other transaction T2 until the transaction T1 ends.
The concurrency control subsystem of the DBMS enforced the isolation property.
Durability
The durability property is used to indicate the performance of the database's consistent
state. It states that the transaction made the permanent changes.
They cannot be lost by the erroneous operation of a faulty transaction or by the system
failure. When a transaction is completed, then the database reaches a state known as the
consistent state. That consistent state cannot be lost, even in the event of a system's
failure.
The recovery subsystem of the DBMS has the responsibility of Durability property.
Active state
The active state is the first state of every transaction. In this state, the transaction is being
executed.
For example: Insertion or deletion or updating a record is done here. But all the records
are still not saved to the database.
Partially committed
In the partially committed state, a transaction executes its final operation, but the data is
still not saved to the database.
In the total mark calculation example, a final display of the total marks step is executed in
this state.
Committed
A transaction is said to be in a committed state if it executes all its operations successfully. In this
state, all the effects are now permanently saved on the database system.
Failed state
If any of the checks made by the database recovery system fails, then the transaction is said
to be in the failed state.
In the example of total mark calculation, if the database is not able to fire a query to fetch
the marks, then the transaction will fail to execute.
Aborted
If any of the checks fail and the transaction has reached a failed state then the database
recovery system will make sure that the database is in its previous consistent state. If not
then it will abort or roll back the transaction to bring the database into a consistent state.
If the transaction fails in the middle of the transaction then before executing the transaction,
all the executed transactions are rolled back to its consistent state.
After aborting the transaction, the database recovery module will select one of the two
operations:
5.5 Schedule
A series of operation from one transaction to another transaction is known as schedule. It is used
to preserve the order of the operation in each of the individual transaction.
1. Serial Schedule
The serial schedule is a type of schedule where one transaction is executed completely before
starting another transaction. In the serial schedule, when the first transaction completes its
cycle, then the next transaction is executed.
For example: Suppose there are two transactions T1 and T2 which have some operations. If it
has no interleaving of operations, then there are the following two possible outcomes:
1. Execute all the operations of T1 which was followed by all the operations of T2.
2. Execute all the operations of T1 which was followed by all the operations of T2.
In the given (a) figure, Schedule A shows the serial schedule where T1 followed by T2.
In the given (b) figure, Schedule B shows the serial schedule where T2 followed by T1.
2. Non-serial Schedule
If interleaving of operations is allowed, then there will be non-serial schedule.
It contains many possible orders in which the system can execute the individual
operations of the transactions.
In the given figure (c) and (d), Schedule C and Schedule D are the non-serial schedules. It
has interleaving of operations.
3. Serializable schedule
The serializability of schedules is used to find non-serial schedules that allow the
transaction to execute concurrently without interfering with one another.
It identifies which schedules are correct when executions of the transaction have
interleaving of their operations.
A non-serial schedule will be serializable if its result is equal to the result of its
transactions executed serially.
Here :
Schedule A and Schedule B are serial schedule.
Schedule C and Schedule D are Non-serial schedule.
Assume a schedule S. For S, we construct a graph known as precedence graph. This graph
has a pair G = (V, E), where V consists a set of vertices, and E consists a set of edges. The
set of vertices is used to contain all the transactions participating in the schedule. The set
of edges is used to contain all edges Ti ->Tj for which one of the three conditions holds:
Precedence of Graph S :
If a precedence graph contains a single edge Ti → Tj, then all the instructions of Ti are
executed before the first instruction of Tj is executed.
If a precedence graph for schedule S contains a cycle, then S is non-serializable. If the
precedence graph has no cycle, then S is known as serializable.
The precedence graph for schedule S1 contains a cycle that's why Schedule S1 is non-serializable.
.
Explanation:
Read(A): In T4,no subsequent writes to A, so no new edges
Read(C): In T4, no subsequent writes to C, so no new edges
Write(A): A is subsequently read by T5, so add edge T4 → T5
Read(B): In T5,no subsequent writes to B, so no new edges
Write(C): C is subsequently read by T6, so add edge T4 → T6
Write(B): A is subsequently read by T6, so add edge T5 → T6
Write(C): In T6, no subsequent reads to C, so no new edges
Write(A): In T5, no subsequent reads to A, so no new edges
Write(B): In T6, no subsequent reads to B, so no new edges
The precedence graph for schedule S2 contains no cycle that's why ScheduleS2 is serializable.
Conflicting Operations
Schedule S2 is a serial schedule because, in this, all operations of T1 are performed before
starting any operation of T2. Schedule S1 can be transformed into a serial schedule by swapping
non-conflicting operations of S1.
T1 T2
Read(A)
Write(A)
Read(B)
Write(B)
Read(A)
Write(A)
Read(B)
Write(B)
View Equivalent
Two schedules S1 and S2 are said to be view equivalent if they satisfy the following conditions:
1. Initial Read
An initial read of both schedules must be the same. Suppose two schedule S1 and S2. In schedule
S1, if a transaction T1 is reading the data item A, then in S2, transaction T1 should also read A.
Above two schedules are view equivalent because Initial read operation in S1 is done by T1 and
in S2 it is also done by T1.
2. Updated Read
In schedule S1, if Ti is reading A which is updated by Tj then in S2 also, Ti should read A which is
updated by Tj
Above two schedules are not view equal because, in S1, T3 is reading A updated by T2 and in S2,
T3 is reading A updated by T1.
3. Final Write
A final write must be the same between both the schedules. In schedule S1, if a transaction T1
updates A at last then in S2, final writes operations should also be done by T1.
Above two schedules is view equal because Final write operation in S1 is done by T3 and in S2, the final
write operation is also done by T3.
Example:
Schedule S
= 3! = 6
S1 = <T1 T2 T3>
S2 = <T1 T3 T2>
S3 = <T2 T3 T1>
S4 = <T2 T1 T3>
S5 = <T3 T1 T2>
S6 = <T3 T2 T1>
Schedule S1
Step 1: final Updation on data items
In both schedules S and S1, there is no read except the initial read that's why we don't need to
check that condition.
Step 2: Initial Read
The initial read operation in S is done by T1 and in S1, it is also done by T1.
Step 3: Final Write
The final write operation in S is done by T3 and in S1, it is also done by T3. So, S and S1 are view
Equivalent.
The first schedule S1 satisfies all three conditions, so we don't need to check another schedule.
Hence, view equivalent serial schedule is:
T1 → T2 → T3
The above table 1 shows a schedule which has two transactions. T1 reads and writes the value of
A and that value is read and written by T2. T2 commits but later on, T1 fails. Due to the failure,
we have to rollback T1. T2 should also be rollback because it reads the value written by T1, but
T2 can't be rollback because it already committed. So this type of schedule is known as
irrecoverable schedule.
Irrecoverable schedule: The schedule will be irrecoverable if Tj reads the updated value of Ti and
Tj committed before Ti commit.
The above table 2 shows a schedule with two transactions. Transaction T1 reads and writes A,
and that value is read and written by transaction T2. But later on, T1 fails. Due to this, we have to
rollback T1. T2 should be rollback because T2 has read the value written by T1. As it has not
committed before T1 commits so we can rollback transaction T2 as well. So it is recoverable with
cascade rollback.
Recoverable with cascading rollback: The schedule will be recoverable with cascading rollback
if Tj reads the updated value of Ti. Commit of Tj is delayed till commit of Ti.
The above Table 3 shows a schedule with two transactions. Transaction T1 reads and write A and
commits, and that value is read and written by T2. So this is a cascade less recoverable schedule.
Isolation levels define the degree to which a transaction must be isolated from the data
modifications made by any other transaction in the database system. A transaction isolation
level is defined by the following phenomena –
Dirty Read – A Dirty read is the situation when a transaction reads a data that has not
yet been committed. For example, let’s say transaction 1 updates a row and leaves it
uncommitted, meanwhile, Transaction 2 reads the updated row. If transaction 1 rolls back
the change, transaction 2 will have read data that is considered never to have existed.
Non Repeatable read – Non Repeatable read occurs when a transaction reads same
row twice, and get a different value each time. For example, suppose transaction T1 reads
data. Due to concurrency, another transaction T2 updates the same data and commit, Now
if transaction T1 rereads the same data, it will retrieve a different value.
Phantom Read – Phantom Read occurs when two same queries are executed, but the
rows retrieved by the two, are different. For example, suppose transaction T1 retrieves a
set of rows that satisfy some search criteria. Now, Transaction T2 generates some new rows
that match the search criteria for transaction T1. If transaction T1 re-executes the
statement that reads the rows, it gets a different set of rows this time.
Based on these phenomena, The SQL standard defines four isolation levels:
1. Read Uncommitted – Read Uncommitted is the lowest isolation level. In this level, one
transaction may read not yet committed changes made by other transaction, thereby
allowing dirty reads. In this level, transactions are not isolated from each other.
2. Read Committed – This isolation level guarantees that any data read is committed at
the moment it is read. Thus it does not allow dirty read. The transaction holds a read or
write lock on the current row, and thus prevent other transactions from reading, updating
or deleting it.
3. Repeatable Read – This is the most restrictive isolation level. The transaction holds read
locks on all rows it references and writes locks on all rows it inserts, updates, or deletes.
Since other transaction cannot read, update or delete these rows, consequently it avoids
non-repeatable read.
4. Serializable – This is the highest isolation level. A serializable execution is guaranteed to
be serializable. Serializable execution is defined to be an execution of operations in which
concurrently executing transactions appears to be serially executing.
A transaction is a unit of work that is performed against a database. Transactions are units or
sequences of work accomplished in a logical order, whether in a manual fashion by a user or
automatically by some sort of a database program. A transaction is the propagation of one or
more changes to the database.
Following is an example which would delete those records from the table which have age = 20
and then COMMIT the changes in the database.
Queries:
DELETE FROM Student WHERE AGE = 20;
COMMIT;
Output:
Thus, two rows from the table would be deleted and the SELECT statement would look like,
4. ROLLBACK: If any error occurs with any of the SQL grouped statements, all changes need to
be aborted. The process of reversing changes is called rollback. This command can only be
used to undo transactions since the last COMMIT or ROLLBACK command was issued.
Syntax: ROLLBACK;
Example:
From the above example 1
Delete those records from the table which have age =20 and then ROLLBACK changes in the
database.
Queries:
DELETE FROM student WHERE AGE =20;
ROLLBACK;
OUTPUT:
This command is used only in the creation of SAVEPOINT among all the transactions.
In general ROLLBACK is used to undo a group of transactions.
Syntax for rolling back to Savepoint command:
ROLLBACK TO SAVEPOINT_NAME;
you can ROLLBACK to any SAVEPOINT at any time to return the appropriate data to its original
state.
Example:
From the above example Sample table1,
Delete those records from the table which have age = 20 and then ROLLBACK the changes in
the database by keeping Savepoints.
Queries:
SAVEPOINT SP1; //Savepoint created.
DELETE FROM Student WHERE AGE = 20; //deleted
SAVEPOINT SP2; //Savepoint created.
Here SP1 is first SAVEPOINT created before deletion.
In this example one deletion have taken place.
After deletion again SAVEPOINT SP2 is created.
Deletion have been taken place, let us assume that you have changed your mind and decided
to ROLLBACK to the SAVEPOINT that you identified as SP1 which is before deletion.
deletion is undone by this statement ,
ROLLBACK TO SP1;
//Rollback completed.
6. RELEASE SAVEPOINT:- This command is used to remove a SAVEPOINT that you have
created.
Syntax: RELEASE SAVEPOINT SAVEPOINT_NAME
Once a SAVEPOINT has been released, you can no longer use the ROLLBACK command to undo
transactions performed since the last SAVEPOINT.
It is used to initiate a database transaction and used to specify characteristics of the
transaction that follows.
5.13 Serializability by Locks-Locking: Lock-Based Protocol
In this type of protocol, any transaction cannot read or write data until it acquires an appropriate
lock on it. There are two types of lock:
1. Shared lock:
o It is also known as a Read-only lock. In a shared lock, the data item can only read by the
transaction.
o It can be shared between the transactions because when the transaction holds a lock,
then it can't update the data on the data item.
2. Exclusive lock:
o In the exclusive lock, the data item can be both reads as well as written by the
transaction.
o This lock is exclusive, and in this lock, multiple transactions do not modify the same data
simultaneously.
It is the simplest way of locking the data while transaction. Simplistic lock-based protocols allow
all the transactions to get the lock on the data before insert or delete or update on it. It will
unlock the data item after completing the transaction.
Growing phase: In the growing phase, a new lock on the data item may be acquired by the
transaction, but none can be released.
Shrinking phase: In the shrinking phase, existing lock held by the transaction may be released,
but no new locks can be acquired.
In the below example, if lock conversion is allowed then the following phase can happen:
1. Upgrading of lock (from S(a) to X (a)) is allowed in growing phase.
2. Downgrading of lock (from X(a) to S(a)) must be done in shrinking phase.
Example :
The following way shows how unlocking and locking work with 2-PL.
Transaction T1:
o Growing phase: from step 1-3
o Shrinking phase: from step 5-7
o Lock point: at 3
Transaction T2:
o Growing phase: from step 2-6
o Shrinking phase: from step 8-9
o Lock point: at 6
Strict Two-phase locking (Strict-2PL)
o The first phase of Strict-2PL is similar to 2PL. In the first phase, after acquiring all the
locks, the transaction continues to execute normally.
o The only difference between 2PL and strict 2PL is that Strict-2PL does not release a lock
after using it.
o Strict-2PL waits until the whole transaction to commit, and then it releases all the locks at
a time.
o Strict-2PL protocol does not have shrinking phase of lock release.
1. Check the following condition whenever a transaction Ti issues a Read (X) operation:
o If W_TS(X) >TS(Ti) then the operation is rejected.
o If W_TS(X) <= TS(Ti) then the operation is executed.
o Timestamps of all the data items are updated.
Where,
TS(TI) denotes the timestamp of the transaction Ti.
R_TS(X) denotes the Read time-stamp of data-item X.
W_TS(X) denotes the Write time-stamp of data-item X.
o TS protocol ensures freedom from deadlock that means no transaction ever waits.
o But the schedule may not be recoverable and may not even be cascade- free.
Validation phase is also known as optimistic concurrency control technique. In the validation
based protocol, the transaction is executed in the following three phases:
1. Read phase: In this phase, the transaction T is read and executed. It is used to read the
value of various data items and stores them in temporary local variables. It can perform
all the write operations on temporary variables without an update to the actual database.
2. Validation phase: In this phase, the temporary variable value will be validated against the
actual data to see if it violates the serializability.
3. Write phase: If the validation of the transaction is validated, then the temporary results
are written to the database or system otherwise the transaction is rolled back.
Validation (Ti): It contains the time when Ti finishes its read phase and starts its validation phase.
This protocol is used to determine the time stamp for the transaction for serialization
using the time stamp of the validation phase, as it is the actual phase which determines if
the transaction will commit or rollback.
Hence TS(T) = validation(T).
The serializability is determined during the validation process. It can't be decided in
advance.
While executing the transaction, it ensures a greater degree of concurrency and also less
number of conflicts.
Thus it contains transactions which have less number of rollbacks.
Assignment Questions
UNIT –I
1. Explain the Types of Languages in DBMS?
2. Explain about Distributed Databases?
3. Explain the DBMS Structure?
4. Differnce between File Processing System VS DBMS
UNIT –II
1. Explain about E R Model?
2. Explain about Primary key, Super Key, Candidate Key with Examples?
3. What are the operations in Relational Databases?
4. What are the Different database Objects
UNIT –III
1. What are the Different types of SET Operations with Examples?
2. What are the Relational Database Operations with Examples?
3. Write 10 Examples for SQL database operations?
4. Write 15 SQL Commands with Syntax?
UNIT –IV
1. What is Normalization and what are the types of Normalization?
2. Explain the difference between Good Schema and Bad Schema?
3. Define Normal Forms with examples?
4. What are the types of Functional Dependencies in DBMS
UNIT –V
1. What are the States of Transaction available?
2. What is Serializability –lock based protocol?
3. What is Time based Protocol and Validation based Protocol?
4. Tell about Testing of Serializability and Precedence graph of Schedule
TUTORIAL QUESTIONS
UNIT – I
UNIT –III
UNIT –IV
UNIT –V
Important Questions
UNIT – I
1. Explain DBMS? Explain Database system Applications.
2. Make a comparison between Database system and File system. ?
3. Explain storage manager component of Database System structure.?
4. Explain the Database users and user interfaces.
5. Explain levels of data abstraction.
6. List and explain the functions of data base administrator?
7. What are the types of languages a database?
8. Types of Databases?
9. Charactersitcs of DBMS and Advantages and Disadvantages?
10.Types of DBMS Architecture ?
11. Schema Level Architecture?
12. Functional Components of DBMS?
UNIT _II
UNIT-III
UNIT –IV
UNIT-V
2. which of the following provides the ability to query information from the database and
insert tuples into, delete tuples from, and modify tuples in the database?
a. DML(Data Manipulation Language)
b. DDL(Data Definition Language)
c. Query
d. Relational Schema
6. A huge collection of the information or data accumulated form several different sources is
known as ________:
a. Data Management
b. Data Mining
c. Data Warehouse
d. Both B and C
7. Which one of the following refers to the "data about data"?
a. Directory
b. Sub Data
c. Warehouse
d. Meta Data
8. Which of the following refers to the level of data abstraction that describes exactly how the
data actually stored?
a. Conceptual Level
b. Physical Level
c. File Level
d. Logical Level
UNIT –II
2. In a relation database, every tuples divided into the fields are known as the______.
a. Queries
b. Domains
c. Relations
d. All of the above
3. In the relational table, which of the following can also be represented by the term
"attribute"?
a. Entity
b. Row
c. Column
d. Both B &C
6. Which of the following keys is generally used to represents the relationships between the
tables?
a. Primary key
b. Foreign key
c. Secondary key
d. None of the above
7. Which one of the following keyword is used to find out the number of values in a column?
a. TOTAL
b. COUNT
c. SUM
d. ADD
8. Which one of the following commands is used to modify a column inside a table?
a. Drop
b. Update
c. Alter
d. Set
a. Dotted rectangle
b.Diamond
C.Doubly Outlined rectangle
d.None
UNIT _III
1. Which one of the following commands is used for removing (or deleting) a relation forms the
SQL database?
a. Delete
b. Drop
c. Remove
d. All of the above
2.What is the Language used by most of the DBMS for helping their users to access data ?
a.High level Language
b.Query Language
C.SQL
D.None
3.A Command that lets you change one or more fields in a record ?
a.Insert
b.Modify
c.Look-up
d.None
4.This is the Authorization command of SQL :
a.Access
b.Grant
C.Allow
d.None
5.Grant is a Command from SQL type :
a.DDL
b.DCL
c.DML
d.None
6.Which of the following is an aggregate function is SQL ?
a.Union
b.Like
c.Group
d.Min
a. Simple tables
b. Virtual tables
c. Complex tables
d. Actual Tables
UNIT-IV
1. In the __________ normal form, a composite attribute is converted to individual attributes.
a) First
b) Second
c) Third
d) Fourth
2. A table on the many side of a one to many or many to many relationship must:
a) Be in Second Normal Form (2NF)
b) Be in Third Normal Form (3NF)
c) Have a single attribute key
d) Have a composite key
3. Functional Dependencies are the types of constraints that are based on______
a) Key
b) Key revisited
c) Superset key
d) None of the mentioned
4. Which forms has a relation that possesses data about an individual entity:
a) 2NF
b) 3NF
c) 4NF
d) 5NF
5. Which forms are based on the concept of functional dependency:
a) 1NF
b) 2NF
c) 3NF
d) 4NF
6. We can use the following three rules to find logically implied functional dependencies. This
collection of rules is called
a) Axioms
b) Armstrong’s axioms
c) Armstrong
d) Closure
UNIT-V
1. Collections of operations that form a single logical unit of work are called __________
a) Views
b) Networks
c) Units
d) Transactions
1. T1 ->>T3->>T2
2. T2->>T1->>T3
3. T2->>T3->>T1
4. T3->>T1—T2
7. The set of ________ in a precedence graph consists of all the transactions participating in
the schedule
a) Vertices
b) Edges
c) Directions
d) None of the mentioned
8. The average time for a transaction to be completed after it has been submitted is called as
__________
a) Minimum response time
b) Average response time
c) Average reaction time
d) Minimum reaction time
Long Answers:
References:
TEXT BOOK:
REFERENCES:
3. Date.C.J, “An Introduction to Database”, Addison-Wesley Pub Co, 8th Edition, 2006.