Database Management System Overview
Database Management System Overview
Sc
DATA BASE MANAGEMENT SYSTEM
[Link]
UNIT I
Computer Science
This Book is dedicated to my Daughter. May God Bless you and be with you
little one!
Information:
Information is the result of processing raw data to reveal ors meaning. Data
processing can be as simple as organizing data to reveal patterns or as complex as
making forecasts or drawing inferences using statistical modeling.
Or
Data that have been processed in such a way as to increase the knowledge of the
person who use the data
Information is produced by processing data.
Information is used to reveal the meaning of data.
Accurate, relevant, and timely information os the key
Database: The database consists of logically related data stored in a single data
repository.
Metadata: The metadata provide a description of data characteristics and the set of
relationships that link the data found with in the database.
Ex:
Field: A character or group of characters that has a specific meaning. A field is used to
define and store data.
Record: A logically connected a set of one or more fields that describes a person, place
or thing.
1. Data Redundancy
o The same data may be duplicated in multiple files, leading to increased storage requirements
and potential inconsistencies.
2. Data Inconsistency
o Due to redundancy, changes made in one file might not reflect in others, causing mismatched
data across the system.
3. Limited Security
o File-based systems lack robust access controls, making it hard to restrict or monitor
unauthorized access.
4. Concurrency Problems
o Managing access by multiple users simultaneously can result in data corruption or access
conflicts.
5. Lack of Flexibility
o Modifications or adding new types of data often require significant effort and changes to the
system.
6. No Centralized Management
o Files are usually managed independently, making it challenging to maintain a unified view or
control.
7. Poor Data Sharing
o Sharing data between users or applications is cumbersome due to the absence of standard
interfaces or integration mechanisms.
8. Difficulty in Querying and Searching
o Complex data queries are not supported; users must often write custom programs or manually
search files.
9. Backup and Recovery Issues
o Backups must be handled manually, and recovery after failure can be time-consuming and
prone to errors.
10. Lack of Data Integrity
o Constraints like relationships between data are not inherently enforced, leading to potential
errors in data representation.
11. Scalability Challenges
o As the volume of data grows, file-based systems struggle with performance and management.
12. Limited Support for Complex Relationships
o Establishing and maintaining relationships between different data sets is difficult without a
database management system.
2. Based on Architecture
• Centralized DBMS:
o All data is stored and managed in a single location.
o Example: Mainframe-based databases.
• Distributed DBMS:
o Data is distributed across multiple locations, connected via a network.
o Example: Google Spanner, Amazon Aurora.
• Cloud-Based DBMS:
o Hosted in the cloud, offering scalability and remote access.
o Example: Google BigQuery, AWS RDS.
3. Based on Purpose
• Single-User DBMS:
o Supports one user at a time.
o Example: Microsoft Access.
• Read-Only DBMS:
o Primarily for querying and viewing data.
o Example: Data warehouses.
• Read-Write DBMS:
o Allows both querying and modification of data.
o Example: Standard transactional databases.
6. Based on Scalability
• In-Memory DBMS:
o Stores data in RAM for fast access.
o Example: SAP HANA, Redis.
• Disk-Based DBMS:
o Stores data on disk for durability and larger capacity.
o Example: Oracle, PostgreSQL.
Database systems offer several advantages that make them an essential component of modern
applications and businesses. Here are the key benefits:
5. Data Sharing
• Facilitates data sharing across multiple users and applications in a controlled manner.
• Supports concurrent access, allowing multiple users to work simultaneously without conflicts.
7. Scalability
• Supports the growth of data and users by allowing the system to expand without significant rework.
• Can handle distributed databases and cloud-based solutions.
• Separates data structure from application logic, allowing changes to the database without affecting
applications.
• Promotes reusability and portability of applications.
13. Standardization
• Follows industry standards (e.g., SQL) for querying and managing data.
• Facilitates integration with other systems and technologies.
• Enables use in diverse fields like e-commerce, banking, healthcare, and AI.
• Supports modern technologies like data warehousing, big data, and machine learning.
Database design refers to the activities that focus on the design of the database
structure that will be used to store and manage end-user data. A database that meets all
user requirements does not just happen; its structure must be designed carefully. In
fact, database design is such a crucial aspect of working with database.
Proper database design requires the designer to identify precisely the database’s
expected use. Designing a transactional database emphasizes accurate and consistent
data and operational speed. Designing a database to be used in a centralized, single-
user environment requires a different approach from that used in the design of a
distributed, multiuser database.
A well-designed database facilitated data management and generates accurate
and valuable information.
A database contains redundant data when the same data about the same entity
are kept in different locations. Therefore, the existence of redundant data can produce
uncorrected data entries and you probably won’t know which value is the correct one.
9 ) D a t a b a s e S y s te m v e r s u s F i l e S y s t e m
1. Hardware:
Hardware refers to all the system’s physical devices. The database system’s main
and most easily identified hardware component is the computer. Hardware also
includes all of the computer peripherals. Peripherals include keyboards, nice,
modems and printers. Peripherals also included any electronic devices that are used
to connect two or more computers.
2. Software:
Software refers to the collection of programs used by the computer within the
database system. Three types of software to make the database system function
fully operating system software, DBMS software and application programs and
utilities
• OS software manages all hardware components and makes its possible for all
other software to run the computers.
• DBMS software manages the database within the database system. Microsoft’s
Access and SQL server, oracle.
• Application programs and utility software’s are used to access and
manipulated the data in the DBMS. Application programs are most commonly
used to access the data found within the database to generate reports,
tabulations and other information to facilitate decision making. Utilities are the
software tools used to help manage the database system’s computer
components.
3. People:
.
Database Administrator
Database Administrator is a person having central control over data and programs
accessing that data. The database administrator is a manager whose responsibilities are
focused on management of technical aspects of the database system.
Database Designer
Database designer can be either logical database designer or physical database designer.
Logical database designer is concerned with identifying the data, the relationships
Database Manager
Database manager is a program module which provides the interface between the low
level data stored in the database and the application programs and queries submitted to
the system:
– The database manager would translate DML statement into low level
file system commands for storing, retrieving, and updating data in the
database.
that the database must remain consistent despite the fact of failures.
Database Users
Database users are the people who need information from the database to carry out
their business responsibility. The database users can be broadly classified into two
categories like application programmers and end users.
Sophisticated end users interact with the system without writing programs. They form
requests by writing queries in a database query language. These are submitted to query
processor. Analysts who submit queries to explore data in the database fall in this
category.
Specialized end users write specialized database application that does not fit into data-
processing frame work. Application involves knowledge base and expert system,
environment modeling system, etc.
Na¨ıve end user interact with the system by using permanent application program
Example: Query made by the student, namely number of books borrowed in library
database.
System Analysts
Canned Transaction
Ready made programs through which na¨ıve end users interact with the database is
called canned transaction.
4. Procedures
Procedures are the instructions and rules that govern the design and use of
the database system. Procedures play an important role in a company, they
enforced the standards procedures also are used to ensure that there is an
organized way to monitor and audit both the data that enter the database and the
information that is generated through the use of such data.
5. Data:
The word ‘Data’ covers the collection of facts stored in the database data are
the raw material from which information is generated.
Integrated Data
A data can be considered to be a unification of several distinct data files and when any
redundancy among those files is eliminated, the data are said to be integrated data.
Shared Data
A database contains data that can be shared by different users for different application
simultaneously. It is important to note that in this way of sharing of data, the
redundancy of data are reduced, since repetitions are avoided, the possibility of
inconsistencies is reduced.
Persistent Data
Persistent data are one, which cannot be removed from the database as a side effect of
some other process. Persistent data have a life span that is not limited to single
execution of the programs that use them.
1. Storage manager.
2. Query processor.
Storage Manager
Storage manager is responsible for storing, retrieving, and updating data in the
database. Storage manager components are:
2. Transaction manager.
3. File manager.
4. Buffer manager.
Transaction Manager
It ensures that the database remains in a consistent state despite system failures. The
transaction manager manages the execution of database manipulation requests. The
transaction manager function is to ensure that concurrent access to data does not result
in conflict.
File Manager
File manager manages the allocation of space on disk storage. Files are
File manager establishes and maintains the list of structure and indexes
– Create a file
– Delete a file
Buffer
The area into which a block from the file is read is termed a buffer
Buffer Manager
Buffer manager is responsible for fetching data from disk storage into main memory.
Programs call on the buffer manager when they need a block from disk. The requesting
program is given the address of the block in main memory, if it is already present in the
buffer. If the block is not in the buffer, the buffer manager allocates space in the buffer
for the block, replacing some other block
Query Processing
As query processing includes certain activities for data retrieval. Initially, the
given user queries get translated in high-level database languages such as SQL. It
gets translated into expressions that can be further used at the physical level of
the file system. After this, the actual evaluation of the queries and a variety of
query -optimizing transformations and takes place. Thus before processing a
query, a computer system needs to translate the query into a human-readable
and understandable language
Relational algebra is well suited for the internal representation of a query. The
translation process in query processing is similar to the parser of a query. When a
user executes any query, for generating the internal form of the query, the parser
in the system checks the syntax of the query, verifies the name of the relation in
the database, the tuple, and finally the required attribute value. The parser
creates a tree of the query, known as 'parse-tree.' Further, translate it into the
form of relational algebra. With this, it evenly replaces all the use of the views
when used in the query.
Suppose a user executes a query. As we have learned that there are various methods of
extracting the data from the database. In SQL, a user wants to fetch the records of the
employees whose salary is greater than or equal to 10000. For doing this, the following
query is undertaken:
Thus, to make the system understand the user query, it needs to be translated in the
form of relational algebra. We can bring this query in the relational algebra form as:
After translating the given query, we can execute each relational algebra operation by
using different algorithms. So, in this way, a query processing begins its working.
Evaluation
For this, with addition to the relational algebra translation, it is required to annotate the
translated relational algebra expression with the instructions used for specifying and
evaluating each operation. Thus, after translating the user query, the system executes a
query evaluation plan.
Optimization
• The cost of the query evaluation can vary for different types of queries. Although
the system is responsible for constructing the evaluation plan, the user does need
not to write their query efficiently.
• Usually, a database system generates an efficient query evaluation plan, which
minimizes its cost. This type of task performed by the database system and is
known as Query Optimization.
• For optimizing a query, the query optimizer should have an estimated cost
analysis of each operation. It is because the overall operation cost depends on the
memory allocations to several operations, execution costs, and so on.
1. Increased costs:
a. Database System required sophisticated hardware and software and highly skilled
personnel.
b. The cost of maintain the hardware, software and personnel required to operate
and manage a database system can be large.
2. Management Complexity:
1. Database Systems interface with many different technologies
2. And have a significant impact on a company’s resources and culture.
3. Database systems hold crucial company data
4. That are accessed from multiple sources, security issues must be assessed
constantly.
3. Maintaining currency:
1. To maximize the efficiency of the database system, you must key your system
current.
2. User must perform frequent updates and apply
3. The latest patches and security measures to all components.
4. Because database technologies advances rapidly, personnel training cost tend to
be significant.
4. Vendor dependence:
1. Given the heavy investment in technology and personnel training, companies
might be reluctant to change database vendors.
1. The basic building blocks of all data models are entities attributes, relationships and
constraints.
2. An entity is any thing (a person, a place, a thing or an event) about which data to
be collected and stored.
3. An attribute is a character of an entity. Attributes are the equivalent of fields in file
systems.
4. A relationship describes an association among entities.
5. Data models are used three types of relationships.
Eg: Employee salary must have values that are between 6,000 and 3,50,000
First Generation (1960-70): In this year File System is much dominated. It is used mainly on IBM
mainframe systems. It managed records only. It does not support relationships.
1. File-Based System: A file based system is a collection of application programs that perform
services for the users wishing to access information. Each program within a file based system
defines and manages its own data. Because of this, there are limits as to how that data can be used
or transported.
File based systems were developed as better alternatives to paper based filing systems. By havingfiles stored
on computers, the data could be accessed more efficiently. It was common practice for larger companies to
have each of its departments looking after its own data.
Second Generation (1970’s): In second generation hierarchical and Network models are
used.
2. Hierarchical Model: In Hierarchical model data is represented by an upside down tree. The
top layer (root) is preserved as the parent of the segment directly under it. The hierarchical model
supports One-to-many relationships.
Ex: parent and its children.
To help establish database standards CODASYL (Conference on Data System Language) create theDBTG
(Database Task Group). The DBTG report contains three crucial database components. i)Network schema
– In this schema includes definition of database name, record type for eachrecord, and the components
that make up of those records.
ii) Network Sub Schema – Which defines the portion of the database, seen by the application
programs that actually produce the desired information from the data contained within the
database.
iii) Data Management Language – It defines the environment in which data can be managed. In
network model allows a record to have more than one parent. In network database terminology,
relationship is called a set.
Third Generation (Mid of 1970’s): In this generation Relational model is used.
[Link] Model: The relational model was introduced by [Link] in 1970’s. In this
model the data is representing in the form of tables each table will contain set of rows andcolumns.
A relational model is support many to many relationships. Primary and Secondary Keysare used in this
model. A Foreign Key is used to establish the relation between the tables.
Fourth Generation (Mid of 1980’s): In this generation Object Oriented Database model ,
Multi Dimensional Database and Entity Relationship models are used.
6. Multi Dimensional Database Model: This database model is used in data ware housing
applications. There are 2 methods to represent the multi dimensional data base model. The 1st
method is cube method. The 2nd method is star View.
In multidimensional cube method each cell contains 1 or more simple attributes and the dimensions
of the raw data. These dimensions are factors on which the user wants to segment the data such as time
period, Geography, lines of business or people.
In star representation a fact table is located at center. This table will contains the entire row attribute
and the composite key made with the primary key of all its surrounding dimension tables
.[Link] MODEL: This model was developed by “CHEN”. ER Model is the logical representation of
the data for an organization. This model represents in terms of
1. Entity
2. Attributes
3. Relationship sets among
entitiesExmaple:
1. In the early 1970s the (American National Standards Institute) ANSI (standards
planning and Requirements committee) SPARC defined a framework for data
modeling based on degrees of data abstraction.
2. The ANSI/SPARC architecture defines three levels of data abstractions:
a. External,
b. conceptual and
The main objective of DBMS is to store and retrieve information efficiently; all the users
should be able to access same data. The designers use complex data structure to
represent the data, so that data can be efficiently stored and retrieved, but it is not
necessary for the users to know physical database storage details. The developers hide
the complexity from users through several levels of abstraction.
The Three-Schema Architecture is a framework for database systems that separates the database into
three distinct levels. This separation ensures abstraction, making the database system more flexible,
adaptable, and easier to use. Here’s an explanation:
• Definition:
o Represents the user-specific views of the database. It defines how individual users or
applications interact with the data.
• Purpose:
o Allows different users to see only the data they need, hiding irrelevant details.
o Provides security by restricting access to certain data.
• Example:
o An employee may see their personal details, while a manager sees a summary of all
employees' work hours.
• Key Features:
o Multiple external schemas can exist for the same database.
o Tailored to meet specific requirements of different user groups.
• Definition:
o Provides a unified view of the entire database. It describes the logical structure of the data and
relationships, independent of physical storage details.
• Purpose:
o Serves as a bridge between the external and internal schemas.
o Ensures data consistency across different external schemas.
• Example:
• Definition:
o Describes the physical storage of data on hardware. It deals with how data is actually stored,
retrieved, and optimized for performance.
• Purpose:
o Manages storage details, indexing, and file organization to ensure efficient data access and
retrieval.
• Example:
o Data is stored in a table format, with indexing on specific columns for faster search operations.
• Key Features:
o Concerned with storage structures like B-trees, hashing, or data clustering.
o Handles performance tuning, storage allocation, and data compression.
1. Data Abstraction:
o Users do not need to understand the physical storage details; they work with higher levels of
abstraction.
2. Data Independence:
o Changes in one schema do not affect the others:
▪ Logical Data Independence: Conceptual schema changes do not affect external
schemas.
▪ Physical Data Independence: Internal schema changes do not affect the conceptual
schema.
3. Enhanced Security and Flexibility:
o Different users can access tailored views without exposing sensitive information or complex
database details.
Q)Vendor dependency:
1. Give the heavy investment in the technology
2. And personnel training, companies may be unwilling to change database vendors.
Vendor products
IBM DB2/MVS
DB2/UDB
DB2/400
Informix Dynamic
Server(IDS)
Microsoft Access
SQL Server
DesktopEdition(MSDE)
Open Source MySQL
PostgreSQL
Oracle Oralce DBMS
RDB
Sybase Adaptive Server Enterprise (ASE)
Adaptive Server Anywhere (ASA)
Watcom
Unit – II
Entity-Relationship Model: Introduction, the building blocks of an entity relationship
diagram, classification of entity sets, attribute classification, relationship degree,
relationship classification, reducing ER diagram to tables, enhanced entity-relationship
model (EER model), generalization and specialization, IS A relationship and attribute
inheritance, multiple inheritance, constraints on specialization and generalization,
aggregation and composition, entity clusters, connection types, advantages of ER
modeling.
1)ENTITY RELATIONSHIP(ER) MODELING
ENTITIES:
EMPLOYEE
Strong Entities
1. A strong entity type is an entity that exists independently of other entity types.
2. Strong entity type always has a unique characteristic called an identifier.
3. That is an attribute or combination of attribute
4. That uniquely identified each occurrence (incidence) of that entity type.
5. It can be denoted as single line rectangle.
Example:
1. Consider the example, student takes course.
2. Here student is a strong entity
Weak Entities
1. A weak entity is an entity type whose existence depends on some other entity
type.
2. The entity has a primary key
3. That is partially or totally derived from the parent entity in the relationship.
4. It is represented by double line rectangle.
Example:
1. Consider the example, customer borrows loan.
2. Here loan is a weak entity.
ASSOCIATIVE ENTITY
EMTITY NMAE
Ename
Eno ESal
EMPLOYEE
Attributes: Ename
Eno
Esal
Note: The naming attributes we use an initial capital letter followed by lower case letter.
1. Domain
2. Composite and simple attributes
3. Single-valued attribute
4. Multivalued attribute
5. Derived attribute
6. Identifiers
7. Composite primary keys
Domains
1. Attribute have a domain.
2. A domain is the ser of possible values for a given attribute.
3. For example the domain for the gender attribute consists of only two possible: M
or F.
Male Female
36
Age facebook
Pin No
ATM card
card
Single valued attribute
Multivalued attribute
1. Multivalve attributes are attributes that may take on more than one value for a
given entity instance.
2. A multi value attribute with an ellipse with double lines.
Ename
skill
Eno
EMPLOYEE
[Link] M.C.A,[Link],[Link].., Page 26
Derived attributes
Ename
skill
Eno
EMPLOYEE Join_date
Experience
Ex:
Jdc(Eno, ename, salary);
Null Value Attribute
In some cases, a particular entity may not have any applicable value for an attribute. For
such situation, a special value called null value is created. Null value situations Not
applicable Not known
Example
In application forms, there is one column called phone no. if a person do not have phone
then a null value is entered in that column
Composite identifiers
M N
CITY Vehicle ROOTS
a. one-to-one,
1 1
Principal Manages Department
b. one-to many
1 M
Subject has Lectures
c. many to many
M N
Lectures Teach Subjects
EXISTENCE DEPENDENCE
1. An entity is said to be existence-dependent
2. If it can exist in the database only when it is associated with another related
entity occurrence.
3. In entity can exist apart from one or more related entities, it is said to be
existence-independent.
Author Book
1. For example, there are two entities named Author and Book.
2. A writer to take an advance to write a book for a publisher,
3. But the first book written by the writer for this publisher,
4. There will be no entry in the Book entity until the contracted book has been written and
published
5. In this case, the relationship between Author and Book is 1:0, indicating that the
existence of an instance of Book is optional
2) RELATIONSHIP STRENGTH
1. Relationship strength is based on how the primary key of a related entity is
demined.
2. To implement a relationship, the primary key of one entity connects as a foreign
key in the related entity.
Ex:
College (SNO, SNAME, SSECTION)
Hostel (SNO, SNAME, ROOMECODE,)
3)RELATIONSHIP PARTICIPATION
Participation in an entity relationship is either optional or mandatory.
Optional:
1. Optional participation means that one entity occurrence does not require a
corresponding entity occurrence in a particular relationship.
2. Ex: Some Lecturers may Teach any Students I Each Student must be taught by at
least one Lecturer
M N
Lectures Teaches Student
Mandatory:
1. Unary (Degree I)
2. Binary (Degree II)
3. Ternary (Degree III)
Higher relationship degrees are also possible but they are rear in use.
UNARY RELATIONSHIP:
1. A unary relationship is a relationship between the instances of a single entity
type.
2. These relationships are also called a recursive relationship.
One-to-one relationship (1-1):
One instant of entity type
associated one instant of the PERSON Is-married_to
same entity
[Link] then it is called
M.C.A,[Link],[Link].., Page 29
In this Eg is_married_to is shown as a 1-1 relationship between instances of the
person entity type.
EMPLOYEE Manages
One_to_many (1 – N):
Some organizations it may be possible for one employee to be managed by many other
employees.
Many_to_many (N – N)
BINARY RELATIONSHIP:
A binary relationship is relationship between the instances of two entity types.
One_to_one(1-1): One instance of the one entity type can be associated with one
instances of other entity type.
This eg indicates that an employee is assigned one parking place and each parking
place is assigned to only one employee.
One to many (1-N): One instance of the one entity type can be associated with
number of instances of other entity type.
In this eg has is the relation between product groups and products many no. of
products are related to only one product group.
Many-to-many: The number of instances of one entity type can associated with
number of instances of other entity type.
This eg indicated that an employee may complete more than one course and then
each course may have many employees.
TERNARY RELATIONSHIP
Quaternary Relationships
relationship is “A professor teaches a course to students using slides.” Here the four
entities are PROFESSOR, SLIDES, COURSE, and STUDENT. The relationships between
the entities are “Teaches.”
The 1: M relationship is the relational database norm. consider the PAINTER paints
PAINTING example.
1. Each painting is painted by one and only one painter, but each painter could
have painted many paintings.
2. There is only one row in the PAINTER table for any given row in the painting
table, but there may be many rows in the PAINTER table for any given row in
the PAINTER table.
3. The 1:M relationship is found in any database environment.
The 1: 1 Relationship:
As the 1: 1 table implies, in this relationship, one entity can be related to only one
other entity, and vice-versa. For example, one department chair – a professor – can
chair only one department can have only one department chair. The entities PROFESSOR
and DEPARTMENT thus exhibit a 1: 1 relationship.
PROFESS DEPARTMENT
Chairs
STUDENT CLASS
has
Indexes in the relational database environment work like the indexes described in
the preceding paragraphs. From a conceptual point of view, an index is composed of an
index key and a set of pointers.
DBMS use index for many different purposes. An index can be used to retrieve
data more efficiently. But indexes can also be used by a DBMS to retrieve data ordered
by a specific attribute or attributes.
For example, creating an index on a customer’s last name will allow you to
retrieve the customer data alphabetically by the customer’s last name.
Index play an important role in DBMSs for the implementation of primary keys,
when you define a table’s primary key column(s). The DBMS automatically creates a
unique index on that attribute. A unique index as its name implies, is an index in which
the index key can have only one0020pointer value (row) associated with it.
Example
In this example the composite attribute is the Customer address, which consists of
Street, City, State, and Zip.
The first relation contains all of the attributes of the entity type except
The second relation contains two attributes that form the primary key of
the second relation. The first of these attributes is the primary key from the first
relation, which becomes a foreign key in the second relation. The second is the
multivalued attribute.
EER Models:
As the complexity of the data structures being modeled has increased and as application
software requirements, there has been as increasing more information in the data
model. In this model represent some business rules also This model that has
resulted from extending the original ER model with new modeling constructs is called
EER model
❖ SUPERTYPE:
1. An entity super-type is a generic entity type
2. That is related to one or more entity subtypes
3. Where the entity super-type contains the common characteristics,
4. And the entity subtypes contain the unique characteristics of each entity
subtype
.
❖ SUBTYPE:
1. A subtype is a subgroup of the entities in an entity type
INHERITANCE
1. The property of inheritance enables (allow) an entity subtype to inherit the
attributes and relationships of the super type.
2. A super type contains those attributes that are common to all of its subtype.
3. In contrast, subtypes contain only the attributes that are unique to the
subtype.
4. One important inheritance characteristic is that all entity subtype inherit their
primary key attribute from their super type.
SUBTYPE DISCRIMINATOR
1. A subtype discriminator is the attribute in the super type entity that
determines to which subtype the super type occurrence is related.
Generalization:
the super class is defined first and the subclasses are defined next. Specialization is the
process of viewing an object as a more refined, specialized object.
Ex:
In the above diagrams car, truck and motor cycle contains a no. of attributes in
common, vehicle-ID, v-name, and price and engine displacement.
This fact suggests that each of the three entity types is really a version of a more
general entity types. This more general entity type (vehicle) together with the resulting
supertype / subtype relationships is shown in above fig b.
The entity car has the specific attribute, no. of passengers, while truck has 2
specific attributes capacity and cab type. Thus generalization has allowed us to group
entity types along with their common attributes and at the same time preserve specific
attribute that are peculiar to each subtype.
In the above examples, motorcycle is not included in the relationship because all
attributes of motor cycle are those that are common to all vehicles.
Specialization:
The process of defining one or more subtypes of the supertype and forming
supertype/subtype relationships.
Part-no Quantity
Part S-ID
on Hand
Routing-No Supplier
Unit
Price
Manufactur Purchased
Supplies
ed Part Part
In the above ex entity type part having attributes partno, description, unit price,
location, quality on hand, routing no and supplier.(a supplier attribute is Multivalued
attribute. since there may be more than one supplier with associated unit price, for a
part).there are 2 possible source for parts. Some are manufactured internally, while
others are purchased from outside suppliers. In this case, the choice depends on factors
such as manufacturing capacity, unit price of the parts. Thus routing_no applies only to
manufactured parts, while supplier_id and unit price apply only to purchase parts.
of the superclass. Since each member of the subclass is an ISA member of the
superclass, the circle below the EMPLOYEE entity set represents ISA relationship.
4)Multiple Inheritance
A subclass with more than one superclass is called a shared subclass. A subclass inherits
attributes not only of its direct superclass, but also of all its predecessor superclass, that
is it has multiple inheritance from its superclasses. In multiple inheritance a subclass can
be subclass of more than one superclass.
Overlap Constraint
Overlap refers to the fact that the same entity instance may be a member of more
than one subclass of the specialization
Example of Overlap Constraint
Consider the example of ANIMAL entity, which can be further subdivided
into LAND ANIMAL and WATER ANIMAL. Consider the example of Frog
and Crocodile which can live in both land and water hence the division of
ANIMAL into LAND and WATER animals is an example of overlap constraint.
Disjoint Constraint
Disjoint refers to the fact that the same entity instance may be a member of only
one subclass of the specialization.
Example of Disjointness Constraint
Total Specialization
Total completeness refers to the fact that every entity instance in the
superclass must be a member of some subclass in the specialization.
Partial Specialization
Partial completeness refers to the fact that an entity instance in the superclass
need not be a member of any subclass in the specialization. With partial
specialization, an instance of a supertype may or may not be a member of any
subtype.
Example of Partial Specialization
Consider the PERSON specialization into EMPLOYEE and STUDENT. This
is an example of partial specialization because there can be a person who is
unemployed and does not study.
Q) Advantages of ER Modeling
An ER model is derived from business specifications. ER models separate
UNIT III
Relational Model: Introduction, CODD Rules, relational data model, concept of key,
relational integrity, relational algebra, relational algebra operations, advantages of
relational algebra, limitations of relational algebra, relational calculus, tuple relational
calculus, domain relational Calculus (DRC). QBE
a. Structural Part
1. The structural part defines the database as a collection of relations.
b. Integrity Part
1. The database integrity is maintained in the relational model using primary
and foreign keys.
c. Manipulative Part
1. The relational algebra and relational calculus are the tools
2. It used to manipulate data in the database.
3. Thus relational model has a strong mathematical background.
Functional dependence:
Determinants:
The attribute on the left-hand side of the arrow in a functional dependency is
called a determinant.
Eg: In the EMP-COURSE relation the combination of eno, course_tittle is a
determinant.
There are different types keys relation data model. They are
1. Composite key
2. Candidate key
3. Super key
4. Alternate key
5. Secondary key
Explanation:
2. Candidate key:
a. A Candidate Key can be any column or a combination of columns
b. That can qualify as unique key in database.
c. There can be multiple Candidate Keys in one table.
d. Each Candidate Key can qualify as Primary Key.
e. [A Primary Key is a column or a combination of columns that uniquely identify a
record
f. A minimal super key. A super key that does not contain a subset of attributes
that is itself a super key. ]
For example: In the EMPLOYEE table, id is best suited for the primary key. Rest of the
attributes like SSN, Passport_Number, and License_Number, etc. are considered as a
candidate key.
3. Super key:
a. Super key is a combination of columns
b. That uniquely identifies any row within a RDBMS table.
c. It is reduced to the minimum number of columns required to uniquely identify each
row.
d. An attribute or combination of attributes that uniquely identifies each row in a
table is called super key.
4. Alternate key:
a. A Alternate key is a key that can be work as a primary key.
b. Basically it is a candidate key that currently is not primary key.
Or
a. Among of candidate keys if any single key or combination of keys made as
primary key then rest candidate key called as alternate key.
Exp:
1. Suppose in employee table EmpID is primary key
2. Then Emailid and SSN are called as alternate key
3. It mean later on these key can be act as primary key without affecting existing data in
table.
Secondary key:
1. An attribute (or combination of attributes) used strictly for data retrieval
purpose is called secondary key.
Exp :
create table tnam(ano number, bno number, bname char(12), primary
key(ano,bno))
In this bno is secondary key.
Primary key:
1. An attribute that uniquely identifies each row in a relation is called primary
key.
2. The combination of unique and not null
3. It cannot support duplicate value and also empty value in attribute
Foreign key:
1. It is used to create relation between two tables using with primary key.
2. A FOREIGN KEY is a key used to link two tables together
3. A FOREIGN KEY is a field (or collection of fields) in one table that refers to the
PRIMARY KEY in another table.
4. The table containing the foreign key is called the child table, and the table
containing the candidate key is called the referenced or parent table.
4. Active Online Catalog Based on the Relational model: The system list is a
collection of tables that the DBMS maintains for its own use. These tables hold the
description of the structure of the database.
5. The Comprehensive Data Sub-language Rule: This Rule states that the system
must support at least one language that performs data definition, View Definition,
data manipulation operations, security and integrity constraints and transaction
management operations.
6. The View Updation Rule: It used to All views that are theoretically updateable must
be updateable by the system.
7. High Level insert, update, and Delete: it used to rows should be treated as sets in
insert, delete and update operations.
12. Non – Subversion Rule: This rule states that different levels of the language can
not subvert or bypass the integrity rules and constraints.
1. Domain Integrity:
1. A domain is a set of values which is assigned to an attribute.
2. The components of the domain are domain name, meaning, data type, size and
range of the values.
2. Entity Integrity :
3. Referential Integrity :
1. A referential integrity is used to implement the foreign key.
2. A foreign key is a non key attribute in the relation R and it is a primary key in
relation R2.
3. This key is called as foreign key. The value of the foreign key is either NULL or primary
key.
4. Another integrity rules that can be enforced in the relational model are the
NOT NULL and UNIQUE constraints.
NOT NULL: its not supports empty value in attribute. The NOT NULL constraint
can be placed a value for that column.
UNIQUE: The UNIQUE constraint is used to not support duplicate values exists
column.
1. a. Selection Operation
1. The selection operation works on a single relation R
2. And it defines a relation that contains only those tuples of R
3. That satisfies the specified condition (Predicate).
4. Selection operation can be considered as row wise filtering.
5. This is pictorially represented also known as RESTRICT
6. It creates values for all rows found in a table that satisfy a given
condition.
7. Select can be used to list all of the row values, or it can create only those
row values
8. That matches a specified criterion.
9. Select create a horizontal subset of a table.
Syntax
σ Predicate (R).
SELECT only PRICE less than Rs. 2.00 yields P_CODE P_DESCRIPT PRICE
123459 9v battery 1.92
123455 100W bulb 1.47
1. b. Projection Operation
2. The projection operation works on a single relation R
3. And defines a relation that contains a vertical subject of R,
4. And extracting the values of specified attributes and elimination duplicates.
5. The projection operation can be considered as column wise filtering.
It’s creates all values for selected attributes. In other words, project creates
a vertical subset of a table.
Syntax
a1,a2,......an (R).
[Where a1, a2, . . . . . . an are attributes and R stands for relation To illustrate
projection operation consider the relation STAFF, with the attributes Staff number,
Name, Gender, Date of birth, and Salary.]
P_CODE PRICE
P_DESCRIPT PRICE
123456 Flashlight 5.26 PROJECT PRICE yields
5.26
123457 Lamp 25.15 25.15
123458 Box Fan 10.99 10.99
123459 9v battery 1.92 Select price from sales; 1.92
123455 100w bulb 1.47 1.47
123454 Power drill 34.99 34.99
PRICE
P_DESCRIPT
Flashlight 5.26
PROJECT P_DESCRIPTand PRICE yields Lamp 25.15
Box Fan 10.99
9v battery 1.92
100w bulb 1.47
Select components, price, from sales; Power drill 34.99
2. a. Union Operation
1. Union combines all rows from two tables, excluding (without) duplicate
rows.
2. The tables must have the same attribute characteristics to be used in the
UNION.
Or
3. The union of two relations R and S defines a relation
4. That contains all the tuples of R or S or both R and S,
5. Duplicate tuples being eliminated.
P_CODE PRICE
P_DESCRIPT
123456 Flashlight 5.26 PRICE
123457 Lamp 25.15 P_CODE P_DESCRIPT
UNION
123458 Box Fan 10.99 345678 Microwave 160.00
123459 9v battery 1.92 345679 Dishwasher 500.00
123455 100w bulb 1.47
123454 Powerdrill 34.99
Example
If there are 5 tuples in relation “R” and 2 tuples in relation “S” then the
number of tuples in R × S is 5 ∗ 2 = 10.
R S
R S
A 1 A 1
A 2
B 2 A 3
Note:
B 1
No. of tuples in R X S = 2 x 3
3 B 2
=6
B 3
d. Intersection Operation
1. The set of all tuples that are in both R and S.
2. Intersect create only the rows that appear in both tables.
3. As we true in the case of UNION table must be union-compatible to produce
(create) valid results.
4. For example, you cannot use INTERSECT if one of the attributes is numeric
and one is character – based.
CODE LOC
A 5
A 9 CODE
yields
A 4 DIVIDE A LOC
B 5 B
5
B 3
C 6
D 7
D 8
E 8
f. Join Operations
1. Join operation combines two relations to create a new relation.
2. The tables should be joined based on a common column.
3. The common column should be compatible in terms of domain.
4. It allows information to be combined from two or more tables.
5. Join is the real power behind the relation database, allowing the use of
independent table linked by common attributes (Characteristics).
Natural Join
The natural join performs an equi join of the two relations R and S over all common
attributes. One occurrence of each common attribute is eliminated from the result. In
other words a natural join will remove duplicate attribute.
In most systems a natural join will require that the attributes have the same name to
identity the attributes to be used in the join. This may require a renaming mechanism.
Even if the attributes do not have same name, we can perform the natural join provided
that the attributes should be of same domain.
Notation: R __ S
Equi Join
equality.
Given the two relations STAFF and DEPT, produce a list of staff and the
Theta Join
A conditional join in which we impose condition other than equality condition. If equality
condition is imposed then theta join become equi join. The symbol θ stands for the
comparison operator which could be >, <, >=, <=.
σθ(R × S)
To illustrate theta join consider two relations FRIENDS and OTHERS with
Outer Join
In outer join, matched pairs are retained unmatched values in other tables are
The pictorial representation of the left and the right outer join of two relations
R and S are :
1. Left Outer Join. Left outer joins is a join in which tuples from R that do
not have matching values in the common column of S are also included in
2. Right Outer Join. Right outer join is a join in which tuples from S that do not have
matching values in the common column of R are also included in the result relation.
3. Full Outer Join. Full outer join is a join in which tuples from R that do
not have matching values in the common columns of S still appear and
Consider two relations PEOPLE and MENU determine the full outer, left
Relationship
Person1 Person2 Relationship
Hari Krishna Lakshmi Mother
Sree harilal Nandalal Father
Hari Raj Brother
Sree Sravanthi Husband
Example:
Retrieve the birth dates and address of the employee whose name is ‘John
[Link]’
{ uv | ( (q) (r) (s) (t) (w) (x) (y) (z) (EMPLOYEE(qrstuvwxyz) and q = ‘John’
and r = ‘B’ and s = ‘Smith’ ) }
or
{ uv | EMPLOYEE(‘John’, ‘Smith’, ‘B’, t,u,v,w,x,y,z ) }
11)Explain QBE
1. QBE stands for Query By Example. QBE uses a terminal display with attribute
names as table headings for queries.
2. It is very easy to list the entire schema, simply by scrolling information on the
screen.
3. QBE was developed originally by IBM in the 1970s to help users in their retrieval
of data from a database.
4. QBE represents a visual approach for accessing data in a database through the
use of query templates.
5. QBE can be considered as GUI (Graphical User Interface) based on domain
calculus.
6. QBE allows users to key in their input requests by filling in empty tables on the
screen, and the system will also display its response in tabular form.
7. QBE is user-friendly because the users are not required to formulate sentences for
query requests with rigid query-language syntax.
8. In QBE the request is entered in the form of tables whose skeletons are initially
constructed by QBE.
9. Some of the QBE query template examples:
1. In this template P. implies “Print.” The meaning is: Print the PLAYER ADDRESS
who belong to the country INDIA.
2. To make a projection only put P. in any column of the projection.
3. QBE will enforce uniqueness of projections automatically.
1. The relational algebra and the relational calculus have the same expressive
power;
Introduction to ORACLE
a. Number(L,D):
1. The declaration Number (7,2) indicates numbers
2. That will be stored with two decimal places and may be up to seven digits
long,
Syntax:
Column-name data-type (L);
or
Column-name data-type (L, D)
Ex:
Sno number (3);
or
sno number(7,2);
b. Integer:
1. It may be abbreviated as INT
2. Integers are (whole) counting numbers,
3. So they cannot be used to store numbers that require decimal places
Syntax:
Column-name data-type (L);
Ex:
Sno integer (3);
c. Smallint:
1. Like Integer, but limited to integer values up to six digits.
2. If your integer values are relatively small, use smallint instead of Int.
Syntax:
Column-name data-type (L);
Ex:
Sno smallint(3);
d. Decimal(l,d)
1. Like the number specification, but the storage length is a minimum
specification.
2. That is, greater lengths are acceptable, but smller ones are not.
3. Decmal (9,2), decimal(9), and decimal are all acceptable.
Syntax:
Column-name data-type (L);
or
Column-name data-type (L, D)
Ex:
Sno decimal (3);
or
sno decimal (7,2);
Character
The character data type is used to store character ( alphanumeric) data. This can
be fixed length or variable length
1. Char(L)
2. Varchar(L) or Varchar2(L)
a. Char(L)
1. Fixed-length character data fro up to 255 characters.
2. If you store strings that are not as long as the char parameter value
3. The remaining spaces are left unused.
4. Therefore, if you specify char (25), each stored as 25 characters
Syntax:
Column-name data-type (L);
Ex:
Sna varchar(25);
Syntax:
Column-name data-type (L);
Ex:
Sna varchar2(25);
c. Date
1. The Date data type is used to store date and time information.
2. For each date value the information stored is, Century, Year, Month, Day,
Hour, Minute, Second
3. The default format of the date data type is ‘DD-MON-YY’.
4. The format can be changed with NLS_DATE_FORMAT command.
Syntax:
Column-name DATE
Long:
The variable length character data up to 4GB
BLOB:
BLOB means Binary Large Object. It store Binary data up to 4GB
CLOB:
Character Large Object. Single byte character up to 4GB
Long raw:
It uses raw binary data up to 2000 bytes
BFILE:
A BFILE can store up to 4GB of data. The BFILE data type stores unstructured
binary data in operating system files outside the database.
3)Commands in SQL
SQL commands can be classified in to different types:
COMMIT
Transaction Control Language
ROLLBACK
(TCL)
SAVEPOINT
GRANT
Data Control Language (DCL)
REVOKE
1. The CREATE TABLE command defines each column (Attribute) of the table
uniquely
2. Each column has a name, data type and size (column width).
3. Each table column definition is separated from the other by a COMMA.
4. Finally the SQL statement is terminated with a semi colon.
Syntax:
Alter table table-name ADD constraint [ADD constraint];
ADDING A COLUMN:
Syntax:
Alter table table-name add (column name <data type>
(size));
Table altered.
Some RDBMSs such as oracle, do not let you change data type unless the column
to be changed is empty.
Syntax: Alter table table-name add (column name <data type> (size));
Table altered.
Table altered.
RENAMING TABLES:
Changing the table name from old to new name is called rename a table.
TRUNCATE:
Truncate command is used to delete to all the records permanently from the
database.
SQL requires the use of the INSERT command to enter data into a table.
1. The row contents are entered between parentheses. Note that the first
character after value is a parenthesis and that the last character in the
command sequence is also a parenthesis.
2. Character (String) and date value must be entered between apostrophes (‘).
3. Numerical entries are not enclosed in apostrophes.
4. Attribute entries are separated by commas.
5. A value is required for each column in the table.
1. The attributes that have required values, by listing the attribute names inside
parentheses after the table name.
Syntax:
UPDATE TABLENAME
SET COLUMNNAME=EXPRESSION, COLUMNAME=EXPRESSION …,
WHERE CONDITION;
Ex:
SQL> UPDATE student SET totalmarks=499 WHERE sname='sam';
1. UPDATE command has not include the WHERE condition, will apply the changes
to all rows in the specified table.
Syntax:
SELECT COLUMNLIST FROM Table name; or Select * from Table name;
Syntax:
DELETE FROM TABLE_NAME
WHERE CONDITION;
Ex:
SQL> delete from student where sno=2;
1. Any changes made to the table contents are not saved on disk until user close
the database,
2. To change the database to use the COMMIT command
GRANT:
1. SQL GRANT is a command used to provide access or privileges on the database objects to
the users.
Syntax:
grant privilegesname on <object name> to <username>
Revoke:
1. The REVOKE command removes user access rights or privileges to the database
objects.
Syntax:
revoke privileges on <object name>from <username>
Syntax:
select[distinct | * | column_name[aliase],………]
From <table_nmae>[where<condition>
[Group by column list ]
Syntax:
Ex:
Select sno, sname from student;
Syntax:
Select * from table-name;
Ex:
Select * from ABC;
The above example shows all the columns from the student.
Ex:
SQL> Select distinct sname from std;
Ex:
SQL>select *from std where sno=12;
1. The above query will display the ascending order, which is default option.
2. To display the rows in descending order
Ex:
Select job,avg (sal) from emp group by job;
We can also use the group by clause to provide results for within groups.
Rows may be pre exclude with WHERE clause, before dividing them into groups.
Ex:
To show the average salary for each JOB excluding manager.
Having Clause
1. It works like a where clause, except that its logic is only related to the results of
group functions as opposite (different) to columns or expressions for individual
rows, which can still be selected with where clause.
Ex:
Select deptno,sum(sal) from emp group by deptno having sum(sal)>1000;
PROJECTION OPERATION
1. The projection operation performs column wise filtering.
2. Specific columns are selected in projection operation.
Syntax:
If all the columns of the table are selected, then it cannot be considered as PROJECTION.
1. The SQL command to perform PROJECTION operation on the relation PEAKS and
the corresponding results
2. it is clear that only three columns are selected in the result.
a. COUNT:
/* COUNT(EMPNO)
------------
14 */
SQL> SELECT COUNT (*) FROM EMP WHERE SAL < =1500;
/* COUNT(*)
--------
7 */
Count (*) returns the number of total rows returned by the query, including the
rows that contain nulls.
b. MAX:
1. The aggregate function Max (column) can be used only in the column list of a select
statement.
2. It returns a minimum value of a expression.
c. MIN:
1. The aggregate function Min (column) can be used only in the column list of a select
statement.
2. It returns min value of a given expression
e. AVG:
The avg function format is similar to that of min and max. it returns an average
value of given column name
1. The single row functions can appear in a select command and can also be
included in where class.
2. The single row functions classified as
a. Date ,
b. Numeric
c. Character
d. Mislenious
4)DATE FUNCTIONS: -
They operate on date values producing O/P which also belongs to date,
Data type except for months between date function which returns a number.
1. Add – months: It returns a date data type as a result format add-months date,
number.
/* ADD_MONTH
---------
27-OCT-04 */
2. Months-between:
a. It returns a number date type as a result. Formate: - moths-between
date1, date2;
/* MONTHS_BETWEEN('27-AUG-85','06-OCT-83')
---------------------------------------
22.68 */
Eg: -
SQL> SELECT SYSDATE FROM DUAL;
/* SYSDATE
---------
24-SEP-10*/
examples
NEXT_DAY( ) NEXT_DAY ('01-Jun-08', 'Wednesday') 04-JUN-08
5) NUMERIC FUNCTIONS: -
1. Numeric functions accept numeric inputs and returns numeric values as the result.
2. The values that numeric functions return or accurate upto 38 decimal digits.
3. Numeric functions are:
/* ABS(-12.3467)
-------------
12.35 */
/* POWER(3,4)
----------
81 */
/* TRUNC(12.3456,2)
----------------
12.34 */
/* ROUND(12.3456,2)
----------------
12.35*/
/*CEIL(68.78)
-----------
69 */
6) CHARACTER FUNCTIONS: -
1. Characters functions accepts character input it returns either character value or
number some of these functions are
/* INI
---
Ram */
/* CONCAT(
-------
goodday */
/* UPPE
----
GOOD */
/* LOW
---
Ram */
/* LPAD('GOOD',
------------
DAYDAYDAGOOD */
/* RPAD('GOOD',
------------
Gooddaydayda */
/* RTR
---
Sai */
Result:
SUBSTR (Store_Name, 3)
s Angeles
Example 2
Result:
SUBSTR (Store_Name, 2, 4)
an D
/* Chr
----
A */
INSTR (str, pattern, [starting position, [nth location]])
2
Length (str)
Result:
Length (Store_Name)
11
Table Geography
Region_Name Store_Name
East Boston
Result:
REGION1
Eastern
Eastern
West
West
7) MISLENIOUS FUNCTIONS:
/* LEAST(100,200)
--------------
100 */
/* USER
-----------
SCOTT */
/* UID
----------
66 */
1) Arithmetic operators : +, -, *, /
bound>;
Ex: select * from student where marks between 200 and 400;
c) NOT BETWEEN: This will gives the output based on the column which values
are not in itslower bound, upper bound.
Syntax:
select * from <table_name> where <col> not between <lower bound> and
<upper bound>;
Ex:
select * from student where marks not between 200 and 400;
d) IN: This will gives the output based on the column and its list of
values [Link]:
select * from <table_name> where <col> in ( value1, value2, value3 ……
value n);
Ex:
SQL> select * from student where sno in (1, 2, 3);
e) NOT IN: This will gives the output based on the column which values
are not in thelist of values specified.
Syntax:
select * from <table_name> where <col> not in ( value1, value2, value3 …
value n);
Ex:
f) IS NULL: This will gives the output based on the null values in the
specified [Link]:
select * from <table_name> where <col> is null;
Ex:
sQL> select * from student where marks is null;
g) NOT NULL: This will gives the output based on the not null values in the
specified [Link]:
select * from <table_name> where <col> is not null;
Ex:
select * from student where marks is not null;
h) LIKE: This will be used to search through the rows of database column based on
the Patternyou specify.
Syntax:
select * from <table_name> where <col> like <pattern>;
iii) This will give the rows whose name ends with ‘h’.
select * from student where name like '%h';
iv) This will give the rows whose name’s second letter start with ‘a’.
select * from student where name like '_a%';
V) This will give the rows whose name’s third letter start with ‘d’.
Vi) This will give the rows whose name’s second letter start with ‘t’ from ending.
3) Logical operators:
a) AND:
This will gives the output when all the conditions become true.
Syntax:
select * from <table_name> where <condition1> and <condition2> and ..
<condition n>;
Ex:
select * from student where sno = 2 and marks >= 200;
Syntax:
Select query
Union
Select query;
Ex:
select job from emp where deptno=10
union
Select job from emp where deptno=20;
b. UNION ALL:
The UNION ALL operator written all rows selected by either query including
duplicates.
Syntax:
Select query
Union all
Select query;
Ex:
c. Intersect:
The intersect operator writtens only rows that are common to both the queries.
D .Minus:
Minus operator writtens all distinct rows selected only by the first query and not by the
second.
Syntax:
Select query
Minus
Select query;
Ex:
SQL> select job from emp where deptno=10
minus
Select job from emp where deptno=20;
3. Referential Constraint
a. Foreign key
Syntax:
Create table <table name> (<column name> <data type>
constraint <constraint name> NOT NULL);
Example:
Create table tab (no number(3) constraint C NOT NULL);
Syntax:
Create table <table name> (<column name> <data type>
constraint <constraint name> check
(column name with condition));
Example:
Ex1: Create table stud (marks number (5) constraint c1 check (marks>35));
Ex2: alter table emp add constraint ck_emp check (sal + comm <10000);
Syntax:
Create table <table name> (<column name> <data type>
constraint <constraint name> unique
(column name));
Ex:
Create table JDC (sno number(10) , sname varchar2(10), sphno number(15)
unique);
3. Default constraint:
1. Its read automatically value when user not enter value
Syntax:
Create table <table name> (<column name> <data type>,
constraint <constraint name> references
<table name> (column name));
Ex:
Create table emp1 (eno number(3) constraint P1 primary key,
ename varchar2(20));
Syntax:
Syntax:
Alter table <table name> drop constraint <constraint name>;
Simple Join:
1. It retrieves rows from two tables having a common column and further
2. It classified into
a. Equi join and
b. Non equi join.
a. Equi Join:
A join which is based on equality is called an equi join.
Ex:
Ex:
Select ename,sal,losal,hisal,grade From emp,salgrade Where sal between losal
and hisal;
Ex:
Ex:
/*To which department name , job and location from department that does
not corresponding employees*/
Syntax:
Characteristics
1. You can use the name of view any where a table name is expected in SQL
statements.
2. Views are dynamically updated. i.e. the view is recreated on demand each time is
invoked.
3. Views provide a level of security in the database because the view can restrict
users to only specified column and specified rows in a table.
4. View may also be used as the basis for reports.
5. It use little storage space.
6. It establishes physical data Independency.
Disadvantages
1. Use processing time, each time the view is referenced.
2. It may or may not be directly updatable.
Syntax:
Updatable Views
1. User can’t join tables in the update statement.
2. To solve that problem, users have to create update view.
3. An update view is a view that can be used to update attributes in the base table
that are used in the views.
Restrictions:
1. Group by expressions of aggregate functions can not be used in the update views.
2. User can’t use set operators.
3. Most restrictions are base on the use of joins or group operators in view.
Materialized Views
Advantage of VIEW
1. The main advantages of view are
a. Improved security,
b. less complexity,
c. better convenience, and
d. Customization.
1. Improved security:
a. We can restrict the user to access on the data that are appropriate for the
user.
b. Hence views provide improved security.
2. Less complexity:
a. A view can simplify queries,
b. By getting data from several tables into a single table
c. Transforming multi table queries into a single table queries.
3. Convenience:
a. A database may contain much information.
b. All the information will not be useful to the users.
c. The users are provided with only the part of the database
d. That is relevant to them rather than the entire database;
e. Hence views provide great convenience to the users.
4. Customization:
a. Views provide a method to customize the appearance of the database
b. So that the users need not see full complexity of database.
c. View creates the illusion of a simpler database customized to the needs of a
particular category of users.
Drawback of VIEW
1. If the base table is modified by adding one or more columns
2. Then the columns added will not be available in the view unless it is recreated.
3. When a view is created from the base table, it is to be noted that all the views are
not updatable.
4. Views created from multiple tables are in general not updatable when there is a
group function, a GROUP BY clause, or restriction operators.
Rules
1. Enclose sub queries in parentheses.
2. Place sub queries on the right side of the comparison condition
3. The order by clause in the sub query is not needed unless you are performing top n
analysis.
4. Single row comparison operators are >,<=,<>,>=
Select ename from emp where sal > (select sal from emp where ename=’smith’);
The most common type of sub query uses an inner SELECT subquery on the right
side of a WHERE comparison expression.
Ex:
SQL> select ename,sal from emp where sal>=(select avg(sal) from emp);
A subquery with a HAVING clause , the HAVING clause is used to restrict the
output of a GROUP BY query by applying a conditional criteria to the grouped
rows.
Ex:
SQL> select deptno, sum(sal)
2 from emp
3 group by deptno
4 having sum(sal)>(select avg(sal) from emp);
ANY
1. ANY operator is multi row operator.
2. The ANY operator allows, to compares a single value of the list or less than
any value of the list.
IN
1. The equal to IN operator, which would be the equivalent of the ANY
operator.
To display employee who are clerk and whose salary is less than that of any clerk.
Select empno,ename,job,sal from emp
Where sal<any(select sal from emp where job=’clerk’); */
UNIT V
Syntax:
Declare
Variable declaration
Begin
Process statements
Or execution statement
[Exception
Exception statement]
End;
1. Declaration Section:
1. Code blocks start with a declaration section
2. In this block memory variable and other oracle objects can be declared
3. They can be used in SQL statements for data manipulation.
Example:
Declare
First_name varhcar2(10);
Num number(10);
2. Begin Section:
1. It consists of a set of SQL and PL/SQL statements
2. It describes process that has to be applied to table data.
3. Actual data manipulation, retrieval, looping and branching constructs are
specified in this section.
3. Exception Section:
1. This section deals with handling of errors
2. That arise during execution of the data manipulation statements
3. The errors can arise due to syntax and logic.
4. End Section:
a. This makes the end of a PL/SQL block.
Example:
Declare
a number(4);
b number(4);
c number(4);
begin
a:=10;
b:=20;
c:=a+b;
dbms_output.put_line(c);
end;
/*
1. dbms_ouput: it is a package.
2. That includes a number of procedures and functions that accumulate information
in a buffer so that it can be retrieved later.
3. These functions can also be used to display message.
4. put_line: put a piece of information in the package buffer followed by an end-of-
line marker.
5. dbms_ouput.put_line(‘Hello’);*/
1. Character Set
1. A PL/SQL program consists of text having specific set of characters.
2. Character set may include the following characters:
a. Alphabets, both in upper case [A–Z] and lower case [a–z]
b. Numeric digits [0–9]
c. Special characters ( ) + − * /< >= ! ∼ ˆ ; : . _ @ % , __ # $ & | { } ? [
]
d. Blank spaces, tabs, and carriage returns.
2. Lexical Units
1. A line of PL/SQL program contains groups of characters known as lexical units,
which can be classified as follows:
A. Delimiters
B. Identifiers
C. Literals
D. Comments
A. Delimiters
a. A delimiter is a simple or compound symbol
b. That has a special meaning to PL/SQL.
c. Simple symbol consists of one character
d. Compound symbol consists of more than one character.
B. Identifiers
a. Identifiers are used in the PL/SQL programs
b. To name the PL/SQL program items
i. Like constants, variables, cursors, cursor variables, subprograms,
etc.
c. Identifiers can consists of alphabets, numerals, dollar signs,
underscores, and number signs only.
d. Any other characters like hyphens, slashes, blank spaces, etc.
C. Literals
a. A literal is an explicitly defined character, string, numeric, or Boolean
value,
D. Comments
1. Comments are used in the PL/SQL program
2. It used to improve the readability and understandability of a program.
3. A comment can appear anywhere in the program code.
4. The compiler ignores comments.
5. Generally, comments are used to describe the purpose and use of each
code segment.
4) Variable declaration
<variable name> data type [(size)] := &variable name;
1. Conditional control
1. Conditional control, which run different statements for different data values.
2. It check the condition for single time only even it is true or false
3. The conditional control statements are If and case.
a. IF
i. If then statement
ii. If then else statement
iii. If then else if statement
iv. Nested if statement
b. Case
If statement
If condition is true it can execute statement 1 to statement n otherwise it
cannot execute statement 1 to statement n.
Syntax:
if(condition) then
Statement 1;
……………
Statement n;
End if;
Example:
DECLARE
a number:=&a;
BEGIN
if(a<10)then
dbms_output.put_line(‘welcome to pl/sql’);
end if;
END;
Example:
declare
a integer;
b integer;
begin
a:=&a; /* it take run time values*/
b:=&b; /* it take run time values*/
if(a>b) then
dbms_output.put_line(‘A is big’);
else
dbms_output.put_line(‘b is big’);
end if;
end;
Syntax:
if(condition) then
Statement 1;
elsif(condition) then
statement 2;
else
statement 3;
end if;
Example:
declare
a integer;
b integer;
c integer;
begin
a:=&a;
b:=&b;
c:=&c;
if(a>b and a>c) then
dbms_output.put_line(‘a is big’);
elsif(b>c) then
dbms_output.put_line(‘b is big’);
else
dbms_output.put_line(‘c is big’);
end if;
end;
Nested if statement
Syntax:
if(condition) then
if(condition) then
statement 1;
else
statement 2;
end if;
else
statement 3;
end if;
Example:
declare
a integer;
b integer;
c integer;
begin
a:=&a;
b:=&b;
c:=&c;
if(a>b) then
if(a>c) then
dbms_output.put_line(‘a is big’);
else
dbms_output.put_line(‘c is big’);
endif;
elsif(b>c)
dbms_output.put_line(‘b is big’);
else
dbms_output.put_line(‘c is big’);
end if;
end;
Case:
Syntax:
case variablename
When value1 then stmt;
When value2 then stmt;
……………
Else stmt;
End case;
1. The case statement runs the first statements for which value equals variable
name remaining conditions are not evaluated.
2. If no value equals to variable name, the case statements runs else statements.
Ex:
declare
Grade char:=’&grade’;
begin
case grade
when ‘A’ then dbms_output.put_line(‘Excellent’);
when ‘B’ then dbms_output.put_line(‘Very good’);
when ‘C’ then dbms_output.put_line(‘Good’);
1. Simple loop
2. While loop
3. For loop
1. Simple loop:
The statements that exit a loop are
o Exit
o Exit when
Syntax:
Exit: Exit when:
Loop Loop
Statement; Statement;
Exit; Exit when(condition);
end loop; end loop;
Example: Exit
Declare
n number:=0;
begin
loop
n:=n+1;
dbms_output.put_line(‘the value of n is’||n);
if(n>=10) then
exit;
end if;
end loop;
end;
2. while loop:
It is entry control loop. First check the condition if it is true it can be
execute and again check condition if it is true it can again execution other wise it
close the while loop.
Syntax:
While(condition)
loop
Statement 1;
…………
Statement n;
end loop;
Example:
declare
i number := 0;
begin
while i<= 10
Syntax:
for variable in[reverse] start . . end
Loop
Statement 1;
…………
Statement n;
end loop;
Example:
begin
for i in 1..10
loop
dbms_output.put_line('the value of i is ' || i);
end loop;
end;
SEQUENTIAL CONTROL:
1. Sequential control statements, which are not crucial (central or Main) to PL/SQL
programming.
2. The sequential control statements are
a. GOTO
It goes to a specified statement, and NULL, which does nothing.
Goto statement:
1. The Oracle PL/SQL GOTO statement is a sequential control structure available in
Oracle.
2. The GOTO statement immediately transfers program control (called "branching")
using with label or block label.
3. The statement or label name must be unique in the block.
Syntax:
<<Lable>>
Statement 1;
…………..
Statement n;
if(condition) then
Goto label;
end if;
Ex:
declare
n integer:=&n;
i integer:=1;
begin
<<p>>
dbms_output.put_line(i);
i:=i+1;
if(i<=n) then
goto p;
end if;
end;
Implicit Cursor –
1. It is automatically created in PL/SQL when the SQL statement returns only
one value.
Explicit Cursor –
1. It is created to hold the output of an SQL statement that may return two or
more rows.
Syntax:
Cursor <cursor name> is select query;
Cursor process commands open, fetch (get) and close any where between begin and
end keywords of PL/SQL block.
Command Explanation
1. Open the cursor, execute the SQL command and
populate the cursor with data.
Open 2. Before you can use a cursor, you need to open it.
Syntax:
open <cursor name>;
1. The fetch command to retrieve data from the cursor
and copy it to the PL/SQL variables for processing.
Fetch
Syntax:
fetch <cursor name> into <var list>;
1. The close command closes the cursor for processing.
Close Syntax:
close <cursor name>;
Syntax:
Declare
Cursor <cursorname> is <select statement>;
Variable declaration;
Begin
Open <cursorname>
Fetch <cursorname> into variablename1…..;
close <cursorname>;
End;
Attribute Description
Keeps the count of record for each fetch when the cursor is
%rowcount
open. Other wise it returns 0.
Keep Boolean values TRUE if fetch is successful otherwise
%found
FALSE if fetch did not return any row.
Keep Boolean values TRUE if fetch is did not return any row
%notfound
otherwise FALSE.
Returns TRUE if cursor is open otherwise FALSE if the cursor
%isopen
is closed.
Example:
Declare
a emp%rowtype;
cursor c2 is select * from emp where deptno=&deptno;
begin
open c2;
loop
fetch c2 into a;
if c2%found then
dbms_output.put_line([Link]||’ ‘||[Link]||’
‘||[Link]);
else
exit;
end if;
end loop;
close c2;
end;
Subprograms
1. Subprogram is a program unit/module
2. That performs a particular task. It also called block.
3. These subprograms are combined to form larger programs.
4. This is basically called the 'Modular design'. A
5. Subprogram can be invoked by another subprogram or program which is called
the calling program
6. Subprograms can be created at the schema level, inside the package, and inside
block
7. They are two types of sub programs
1. Procedures
2. Functions
User create a Procedure or function, you have to define this three parameters.
1. In
2. Out
3. In out
2. OUT
a. OUT parameter is referenced to the procedure or function.
b. Output only.
c. And value of parameter is overwritten allow.
3. IN OUT
a. IN OUT parameter is referenced to the procedure or function.
b. Both input and output.
c. And value of parameter is both overwritten allow or not allow.
1. Procedures
These subprograms do not return a value directly, mainly used to perform
an action.
Syntax:
CREATE [OR REPLACE] PROCEDURE procedure_name (procedure parameters)
{IS | AS}
BEGIN
< procedure_body >
END;
Example:
CREATE OR REPLACE PROCEDURE greetings
AS
BEGIN
dbms_output.put_line('Hello World!');
END;
/
Procedure created.
Execute:
When above code is executed using SQL prompt, it will produce the following
result:
Hello World
Or
You might call the procedure in a PL/SQL Block.
BEGIN
greetings;
END;
Hello World
PL/SQL procedure successfully completed.
2. Functions
Syntax:
CREATE OR REPLACE
FUNCTION function_name (function_params) RETURN return_type IS
BEGIN
function_body
RETURN something_of_return_type;
END;
Ex1:
CREATE OR REPLACE FUNCTION ADD_TWO (A INT,B INT) RETURN INT IS
BEGIN
RETURN (A + B);
END;
Calling function:
BEGIN
DBMS_OUTPUT.PUT_LINE(’RESULT IS: ’ || ADD_TWO(12,34));
END;
/
RESULT IS: 46
Syntax:
BEGIN
Trigger action;
END;
In trigger two types of pseudo (artificial) (fake) column are available they are
On the Basis of Type of Trigger/Firing or Triggering Transaction
– BEFORE Triggers
– AFTER Triggers
– INSTEAD OF
BEFORE Triggers
BEFORE triggers execute the trigger action before the triggering statement is executed.
It is used to derive specific column values before completing a triggering DML, DDL
statement or to determine whether the triggering statement should be allowed to
complete.
Example
We can define a BEFORE trigger on the passengers detail table that gets fired before
deletion of any row. The trigger will check the system date and if the date is Sunday, it
will not allow any deletion on the table.
The trigger can be created in Oracle The trigger action can be shown. As soon as we try
to delete a record from passenger detail table, the above
trigger will be fired and due to SUNDAY EXP fired, all the changes will be
AFTER Triggers
AFTER triggers execute the trigger action after the triggering statement is
executed. AFTER triggers are used when we want the triggering statement to complete
before executing the trigger action, or to execute some additional logic to the before
trigger action
We can define an AFTER trigger on the reserv det table that gets fired every time one
row is deleted from the table. This trigger will determine the passenger id of the deleted
row and subsequently delete the corresponding row from the passengers det table with
same passenger id.
LOGON and LOGOFF triggers can be associated with the database or with
a schema. Their attributes include the system event and username, and they can specify
simple conditions on USERID and USERNAME.
Example
Let us create a trigger on LOGON event called pub log, which will store
log detail it will show who are all logged into database. The value of the
attribute log times would go on increasing with every login into the database which is
indicated Note The log detail relation is visible only in Administrator login.
This trigger gets fired when DDL statement such as CREATE, ALTER, or
DROP command is issued. DDL triggers can be associated with the database or with a
schema. Moreover depending on the time of firing of trigger, this trigger can be classified
into BEFORE and AFTER. Hence the triggers on
– BEFORE ALTER and AFTER ALTER triggers fire when a schema object
– BEFORE DROP and AFTER DROP triggers fire when a schema object
Example 1
Create or replace trigger abc before insert on dept for each row
Declare
Sdate varchar2(3);
Begin
Sdate:=to_char(sysdate,’dy’);
End if;
End;
Example 2:
Declare
Tday varchar2(10);
Begin
Tday:=to_char(sysdate,’dy’);
If tday=’mon’ then
End if;
End;
Example 3
Begin
If :[Link]>=10000 then
End if;
End;
Example 4:
Begin
End;
This trigger gets fired when DML statement such as INSERT, UPDATE, or
DELETE command is issued. DML triggers can be associated with the database or with a
schema. Depending on the time of firing of trigger, this trigger can be classified into
BEFORE and AFTER.
A row level trigger, as its name suggests, is fired for each row that will be
affected by the SQL statement, which fires the trigger. Suppose for example if an
UPDATE statement updates “N” rows of a table, a row level trigger defined for this
UPDATE on that particular table will be fired once for each of those “N” affected rows. If
a triggering SQL statement affects no rows, a row trigger is not executed at all. To
specify a trigger of row type, FOR EACH ROW clause is used after the name of table.
Unlike row level trigger, a statement level trigger is fired only once on behalf of the
triggering SQL statement, regardless of the number of rows in the table that the
triggering statement affects. Even if the triggering statement affects no rows, the
statement level trigger will execute exactly once. For example, if a DELETE statement
deletes several rows from a table, a statement-level DELETE trigger is fired only once,
regardless of how many rows are deleted from the table.
INSTEAD-OF Triggers
INSTEAD-OF triggers are used to tell Oracle what to do instead of performing the actions
that executed the trigger. It is applicable to both object views and standard relational
database. This trigger can be used to redirect table inserts into a different table or to
update different tables that are the part of the view. This trigger is used to perform any
action instead of the action that executes the trigger.
By default, a trigger is enabled when it is created. Only an enabled trigger gets fired
whenever the trigger restriction evaluates to TRUE. Disabled triggers do not get fired
even when the triggering statement is issued
Syntax
Dropping Triggers
Triggers can be dropped like tables using the drop trigger command. The drop trigger
command removes the trigger structure from the database
A Normal Form is a state of relation that results applying simple rules regarding
functionally dependencies (A constraint between two attributes or two sets of attributes.)
the relation so that we proved a well structured relation with minimal redundancy.
Any Multivalued attribute have been removed, so there is a single value at the
intersection of each row and column of the table.
Any partial functional dependencies have been removed and also it is a first normal
form.
Any transitive dependencies have been removed and also it is second normal form.
Any remaining anomalies that results from functionally dependency have been
removed.
Surveys 10/7/200X
C++ 4/22/200X
Java 8/12/200X
A relation is in second normal form (2NF) if it is first normal form and every non key
attribute is functionally dependent on the primary key. Thus no non key attribute is
functionally dependent on part of the primary key. A relation that is in first normal form will be
in second normal form if any one of the following conditions is applied.
1. The primary key consists of only one attribute (such as the attribute Emp_ID in
Employee1).
2. No non key attributes exists in the relation (thus all of the attributes in the relation are
components of the primary key).
3. Every non key attribute is functionally dependent on the full set of primary key
attribute.
EMP
EID COURSE NAME EPT-NAME SAL DATECOMPLETED
In the above table is not in the second normal form. Because the primary key relation s
the composite key Employee_ID, Course_title. Therefore the non key attributes name,
Dept_name & salary are functionally dependent on part of the primary key (Emp_ID), but not
on Course_title. To convert a relation to second normal form, we decompose two relations.
EMP1
EMPCOURSE
Deletion possible:
Here customer-ID is primary key; all of the remaining attributes are functionally
dependents on this attribute. However, there is a transitive dependency (region) is
functionally dependent on salesperson. There are some problems of the transitive
dependency.
2. Deletion Anomaly: If customer no. is deleted from the table, we loose the information
of salesperson and region.
BCNF is one of the forms of Normalization. A database table is in BCNF if and only if
there are no trivial functional dependencies of attributes on anything other than a superset
of a candidate key. BCNF is also some times referred to as 3.5NF or 3.5 Normal Form.
When a relation has more than one candidate key, anomalies may result even
though that relation is in 3NF.
As shown in fig B-1b, the primary key for this relation is the composite key consisting
of Sid and subject. Thus the 2 attributes lecturers and hour are functionally dependent on this
key this reflects the constraint that although a given student may have more than one subject
, for each subject a student has exactly one lecturer and one hour.
Anomalies in student_advisor:
The student-advisor relation is clearly in 3NF, since there are no partial functional
dependencies and no transitive dependencies. Because of the F.D between subject and
lecturer there are anomalies in this relation.
BCNF:
The anomalies in student_advisor result from the fact that there is a lecturer that is not
a candidate key in the relation. [Link] and [Link] identified this deficiency and
proposed a stronger definition of 3NF that remedies the problem. If and only if every
determinant in the relation is a candidate key. Student_advisor is not in BCNF because
although the attribute lecturer is a determinant, it is not a candidate key. (Only subject is F.D
on lecturer).
1. The relation is modified so, that the determinant in the relation that is not a candidate key
becomes a component of the P.K of the revised relation. The attribute that is F.D on that
determinant becomes a non key attribute. The result of applying this rule to student_advisor
is shown in fig B-2a. The determinant lecturer becomes part of the composite P.K. The
attribute subject, which is F.D on lecturer, becomes a non key attribute.
LECTURER SUBJECT
In general, de-normalization may partition a relation into several physical records, may
combine attributes from several physical records, and may combine attributes from several
relations together into one physical record.
De-normalization can increase the chance of errors and inconsistencies and can force
reprogramming systems if business rules change. The benefits of de-normalization may no
longer exist and almost leads to more storage space for raw data and may be more space for
database indexes.
STUDENT
Student-ID Campus_Addre
s
APPLICATION
De-normalized Relation
STUDENT
In the above example one record could be formed with four fields from the student and
scholarship application normalized relations.
Time: 3 Hours
Section-A
SECTION.B