DBMS PDF
DBMS PDF
UNIT II
UNIT V
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 Availability
Now a days database classify as Operational Database, Data warehouse. 5. That is, by simply looking at field is likely to contain.
6. Some software packages place restrictions in the length of field names.
1. Operational Database 7. So it is wise to be as expressive as possible within those restrictions.
8. In addition, very long field names create it difficult to more than a few fields on
A database that is designed primarily to support company’s day to day operations a page
is classified as an Operational Database or Transactional or Production Database. 9. They creating output values a problem.
Those limitations in turn, lead to problems of structural and data dependency. Data anomalies:
1. Data anomalies (difference) exist because any change in any field value
1. STRUCTURAL AND DATA DEPENDENCE: must be correctly made in many places to maintain data integrity.
2. The data anomalies are commonly defined as:
1. A file system show structural dependence,
2. It means that access to a file is dependent on its structure. a. Update anomalies:
3. For example, adding a customer date-of-birth field in CUSTOMER file, 1. Changing any field data, we must change wherever be appear
4. The file system programs must be modified to conform to the new file that field.
structure, 2. In this case a large file system, such changes might occur in
5. They exhibit structural dependence. hundreds or even thousands of records clearly,
6. Even changes in the characteristics of data 3. The possible for data in consistencies is great.
7. Such as changing a field from integer to decimal,
8. It requires all changes in the programs that access the file. b. Insertion anomalies:
9. That is changing the data type etc. 1. To add each new customer in CUSTOMER file,
10.The file system is said to exhibit data dependence. 2. We must also add the corresponding agent data.
3. If we add several hundred new customers,
4. We must also enter several hundred agent names and telephone
1. FIELD DEFINITIONS AND NAMING CONVERTIONS: numbers.
c. Deletion anomalies:
D a t a b a s e S y s t em 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.
OS software manages all hardware components and makes its possible for all – Security enforcement. Unauthorized users are prohibited to view the information
other software to run the computers.
DBMS software manages the database within the database system. Microsoft’s stored in the data base.
Access and SQL server, oracle.
– Backup and recovery. Backup and recovery of database is necessary to ensure
Application programs and utility software’s are used to access and
manipulated the data in the DBMS. Application programs are most commonly that the database must remain consistent despite the fact of failures.
used to access the data found within the database to generate reports,
tabulations and other information to facilitate decision making. Utilities are the Database Users
software tools used to help manage the database system’s computer
components. 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
3. People:
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,
Database Administrator environment modeling system, etc.
Database Administrator is a person having central control over data and programs Naive End Users
accessing that data. The database administrator is a manager whose responsibilities are
focused on management of technical aspects of the database system. 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 Designer database.
Database designer can be either logical database designer or physical database designer. System Analysts
Logical database designer is concerned with identifying the data, the relationships
between the data, and the constraints on the data that is to be stored in the database. System analysts determine the requirements of end user, and develop specification for
The logical database designer must have thorough understanding of the organizations canned transaction that meets this requirement.
data and its business rule.
Canned Transaction
Database Manager
Ready made programs through which na¨ıve end users interact with the database is
Database manager is a program module which provides the interface between the low called canned transaction.
level data stored in the database and the application programs and queries submitted to
the system:
4. Procedures
– The database manager would translate DML statement into low level 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
file system commands for storing, retrieving, and updating data in the 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
database. information that is generated through the use of such data.
Persistent Data File manager establishes and maintains the list of structure and indexes
Persistent data are one, which cannot be removed from the database as a side effect of defined in the internal schema. The file manager can:
some other process. Persistent data have a life span that is not limited to single – Create a file
execution of the programs that use them.
– Delete a file
Functional Components of Database System Structure ?
– Update the record in the file
The functional components of database system structure are:
– Retrieve a record from a file
1. Storage manager.
Buffer
2. Query processor.
The area into which a block from the file is read is termed a buffer
Storage Manager
Buffer Manager
Storage manager is responsible for storing, retrieving, and updating data in the
database. Storage manager components are: 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
1. Authorization and integrity manager. program is given the address of the block in main memory, if it is already present in the
2. Transaction manager. buffer. If the block is not in the buffer, the buffer manager allocates space in the buffer
for the block, replacing some other block
3. File manager.
4. Buffer manager.
DBMS FUNCTIONS ?
Transaction Management
1. A DBMS guarantee the integrity and consistency of the data in the database.
– A transaction is a collection of operations that performs a single logical They include
a. Data dictionary management,
function in a database application. b. Data storage management,
c. Data transformation and presentation,
– Transaction-management component ensures that the database remains in a d. Security managements,
consistent state despite system failures and transaction failure. e. Multi user access control,
f. Backup and recovery management,
– Concurrency control manager controls the interaction among the concurrent g. Data access using a languages
transactions, to ensure the consistency of the database. h. Application programming interfaces
i. And database communication interfaces.
Authorization and Integrity Manager
2. Data dictionary management:
Checks the integrity constraints and authority of users to access data. 1. The DBMS requires that definitions of the data elements and their relationship
(metadata) be stored in a data dictionary.
Final Assembly
Assembly A Advantages:
Assembly B Assembly C
1. Conceptual simplicity is at least equal to that of
2. It handles more relationship types, such as M:N and multi parent.
3. Data access is more flexible than in hierarchical and file system models.
Part A Part B Part C Part D Part E 4. Data Owner/Member relationship promotes data integrity.
1. The hierarchical database model’s have many advantages over the file system 5. There is conformance to standards.
model. 6. It includes data definition language (DDL) and data manipulation language (DML) in
2. Hierarchical database model’s features helped form the foundation for current database DBMS
models,
3. Database application advantages are artificial, even if in different form in current Disadvantages:
database environments. 1. System complexity limits efficiency still a hierarchical model, navigational system.
2. Navigational system yields (give up) complex implementation, application
Advantages are. development, and management.
1. It promotes data sharing. 3. Structural changes require changes in all application programs.
2. Parent/Child relationship promotes conceptual simplicity.
3. Database security is provided and enforced by DBMS 3. The relational database model
4. Parent/Child relationship promotes data integrity. 1. The relational database model is implemented through a very sophisticated
5. It is efficient with 1: M relationships. (difficult or complicated) relational database management system (RDMBS).
2. The RDBMS performs the same basic functions provided by the hierarchical and
Disadvantages: network DBMS systems and add other functions
1. Different parts implementation requires knowledge of physical data storage 3. That makes the relational database model easier to understand and to
characteristics. implement.
2. Navigational systems give up complex application development, management, 4. The RDBMS manages all of the complex physical details
and use; 5. The relational database is perceived (understand) by the user to be a collection
3. It requires knowledge of hierarchical path. of tables in which data are stored.
4. Changes in structure require changes in all application programs. 6. Each ‘table’ is a matrix consisting of a series of row/column intersections.
5. There are implementation limitations (no multi-parent or M:N relationship) 7. Tables also called relations are related to each other by sharing a common entity
6. There is no data definition or data manipulation language in the DBMS characteristic.
7. There is a lack of standards.
Advantages:
2. The network database model 1. Structural independence is promoted by the use of independent tables.
1. The network model was created to represent complex data relationships 2. Changes in a table structure do not affect data access or application programs.
2. It more effectively than the hierarchical model to improve database 3. Table view largely improves conceptual simplicity
performance, and to impose a database standard. 4. They provide easier database design, implementation, management, and use.
3. The network model, the user understanding the network database as a 5. Ad-hoc query capability is based on SQL.
collection of records in 1:M relationships. 6. Powerful RDBMS isolates (suppurate) the end user from physical level details
4. The network model allows network database terminology a relationship is called 7. And improves implementation and management simplicity.
a set.
5. Each set is composed of at least two record types an owner record and a member Disadvantages:
record. 1. The RDBMS requires extensive hardware and system software overhead.
6. A set represents a 1:M relationship between the owner and the member 2. Conceptual simplicity gives relatively untrained people the tools to use a good
system poorly, and if unchecked, it may produce the same data anomalies found in
file systems.
3. It may promote islands of information problems as individuals and departments
can easily develop their own applications.
Entity instance: 1. In the early 1970s the (American National Standards Institute) ANSI (standards
1. Each now in the relational table is known as an entity instance or entity planning and Requirements committee) SPARC defined a framework for data
occurrence in the E-R model. modeling based on degrees of data abstraction.
2. The ANSI/SPARC architecture defines three levels of data abstractions:
Attribute: a. External,
1. An attribute describes a particular characteristic of the entity. b. conceptual and
c. Internal.
Relationship: 3. The ANSI/SPARC framework has been expanded with the addition of a physical
1. Relationships describe associations between two entities. model to explicitly address physical level implementation address physical level
One-to-many (1:M) implementation details of the internal model.
Many-to-many (M:N) and
One-to-many (1:1)
Relationships are represents by a diamond symbol connected with line to the
related entities.
Advantages
1. Visual modeling yields (give up) exceptional conceptual simplicity.
2. Visual representation makes it an effective communication tool
3. It is integrated (include) with main relational model.
Disadvantages
1. There is limited constraint representation
2. There is limited relationship representation.
3. There is no data manipulation language.
4. Loss of information content occurs when attributes are removed from entities to avoid
crowded (full) displays. (This limitation has been addressed in subsequent graphical
versions)
Need for Abstraction
5. The object oriented database model
1. Object oriented data models are typically show using unified modeling The main objective of DBMS is to store and retrieve information efficiently; all the users
language (UML) class diagrams. should be able to access same data. The designers use complex data structure to
2. Unified modeling language is a language based on 00 concepts represent the data, so that data can be efficiently stored and retrieved, but it is not
3. That describes a set of diagrams and symbols that can be used a graphically model necessary for the users to know physical database storage details. The developers hide
system. the complexity from users through several levels of abstraction.
4. UML diagrams are used to represent data and their relationships within the
large UML object oriented systems modeling language.
Data Independence 1. It provides a relatively easily understood macro level view of the data
environment.
Data independence means the internal structure of database should be 2. The conceptual mode is independent of both software and hardware’s.
3. Software independence means that model.
unaffected by changes to physical aspects of storage. Because of data independence, the 4. Does not depend on the DBMS software
Database administrator can change the database storage structures without affecting the 5. It used to implement the model
users view. 6. Hardware independence means that mode doesn’t depend on the hardware.
7. Used in the implementation of the model.
The different levels of data abstraction are: 8. Therefore charge in either the hardware or the DBMS software will have
no effect on the database design at the conceptual level.
1. Physical level or internal level
3. The Internal Model:
2. Logical level or conceptual level 1. The internal model map (record) the conceptual model to the DBMS.
2. The conceptual models are mapped to tables in the relational model.
3. View level or external level 3. A relational database has been selected the internal schema is expressed using
SQL, the standard Query Language for relational databases.
4. The development of a detailed internal model is especially important to database
1. External model:
designers who work with hierarchical or network models.
5. The internal model depends on specify database software.
1. The external model is the end user’s view of the data environment.
6. It is said to software dependent.
2. The term end user refers to people who use the application programs to
7. A change in DBMS software requires that the internal model be changed
manipulate the data and generate information.
8. User can change the internal model without affecting the conceptual model.
3. Each business unit is subject to specific constrains and requirements
9. A change in storage devices or even a change in operating system will not effect the
4. And each one uses a data subset of the overall data in the organization.
internal model.
5. Therefore, end users working those business units view
6. ER diagrams will be used to represent the external views.
4. The Physical model:
7. A specific representation of an external view known as an external schema.
1. The Physical model operates at the lowest level of abstraction (idea)
8. The use of external view representing subsets of the database.
2. It describing the way data is saved storage in disks or tapes.
3. The physical model requires the definition of both the physical storage devices and
Advantages
the (physical) access methods
4. It required storage devices, creating it both software and hardware dependent.
1. It creates easy to identify specific data
5. The storage structures used are dependent on the software
2. It required to supports each business unit’s operations.
6. The physical model is dependent on the DBMS,
3. It creates the easy designer’s
7. Methods of accessing files and types of hardware storage devices supported
4. It provides feedback about the model’s adequacy (capability).
by the operating system.
5. It helps to ensure security constraints in the database design.
8. User can change the physical model without affecting the internal model.
6. Damaging an entire database is more difficult but data cannot be loss
because
Explain Database Architecture
7. It creates application program development much simpler.
1. Database architecture essentially explains the location of all the pieces of
information that create the database application.
2. Conceptual model:
2. The database architecture can be classified into
1. A conceptual model is used, graphically represented by an ERD
a. Two-Tier,
2. To integrate (mix) all external views into single view.
b. Three-Tier, and
3. The conceptual model represents a global view of the entire database and
c. Multitier architecture.
organization.
4. That is the conceptual model integrates all external views (entities, relationships,
Two-Tier Architecture
constraints and processes) into a single global view of the entire data in the
1. The two-tier architecture is a client–server architecture
enterprise.
2. The client contains the presentation code and the SQL statements for data access.
5. Also known as conceptual schema,
3. The database server processes the SQL statements and sends query results back to
6. It is the basis for the identification and high-level description of the main data
the client.
objects.
4. The client, or first tier, is primarily responsible for the presentation of data to the user to
7. The most widely used conceptual model is E-R model.
the server
8. The E-R model is illustrated with the help of the ERD.
5. The server, or the second tier, is primarily responsible for supplying data services to the
9. The ERD is used to graphically represent the conceptual schema.
client.
Presentation Services
1. “Presentation services” refers to the portion of the application which presents data to the
user.
2. It also provides for the mechanisms in which the user will interact with the data.
Business Services/objects
1. “Business services” are a category of application services.
2. Business services summarize an organizations business processes and
requirements.
3. These rules are derived from the steps necessary to carry out day-today business
in an organization.
4. These rules can be validation rules
5. It used to be sure that the incoming information is of a valid type and format
Application Services
1. “Application services” provide other functions necessary for the Application.
Multitier Architecture
1. A multi-tier, three-tier, or N-tier implementation employs a three-tier logical
Data Services
architecture superimposed on a distributed physical model.
1. “Data services” provide access to data independent of their location.
2. Application Servers can access other application servers in order to supply
2. The data can come from legacy mainframe, SQL RDBMS, or proprietary data access
services to the client application as well as to other Application Servers.
systems.
3. The multiple-tier architecture is the most general client–server architecture.
4. It can be most difficult to implement because of its generality
Advantages:
5. A good design and implementation of multiple-tier architecture can provide the
1. The two-tier architecture is a good approach for systems with stable requirements
most benefits in terms of scalability, interoperability, and flexibility.
and a moderate number of clients.
2. The two-tier architecture is the simplest to implement, due to the number of good
commercial development environments.
Disadvantages:
1. Software maintenance can be difficult because PC clients contain a mixture of
presentation, validation, and business logic code.
2. To make a significant change in the business logic, code must be modified on many PC
clients.
3. Moreover the performance of two-tier architecture can be poor when a large
number of clients submit requests because the database server may be
overwhelmed with managing messages.
Which Situations where DBMS is not Necessary
Three-tier Architecture
1. It is also necessary to specify situations where it is not necessary to use a DBMS.
1. A “Multitier,” often referred to as “three-tier” or “N-tier,” architecture provides
2. If traditional file processing system is working well
greater application scalability, lower maintenance, and increased reuse of
3. It takes more money and time to design a database,
components.
1. Increased costs
2. Management complexity
3. Maintaining currency
4. Vendor dependency
Increased costs:
1. Database system requires sophisticated (difficult) hardware and software and
highly skilled personnel.
2. The cost of maintaining the hardware , software can be large
3. And personnel required to operate and manage a database system can be also
large.
Management complexity:
1. Database system interface with many different technologies
2. It has a significant (major) impact on a company resources and culture.
Maintaining currency:
1. To maximize the efficiency of the database system you must keep your system
current.
2. Therefore user must update all the components
3. Because database technologies are rapidly changes, personal training is very cost.
Pin No
ATM card
card
Single valued attribute
1. Domain Multivalued attribute
2. Composite and simple attributes
3. Single-valued attribute
4. Multivalued attribute
5. Derived attribute
6. Identifiers 1. Multivalve attributes are attributes that may take on more than one value for a
7. Composite primary keys given entity instance.
2. A multi value attribute with an ellipse with double lines.
Domains
1. Attribute have a domain. Ename
2. A domain is the ser of possible values for a given attribute. skill
3. For example the domain for the gender attribute consists of only two possible: M Eno
or F.
EMPLOYEE
Male Female
Derived attributes
Gender
Age Vehicle
Ename
Required attribute optional attribute skill
Eno
Composite and simple attributes:
1. A composite attribute is an attribute that can be further subdivided to yield (give EMPLOYEE Join_date
up) additional attributes. Experience
Many_to_many (N – N)
Mandatory:
More than one instant of entity type
1. Mandatory participation means that one entity occurrence requires a associated with more than one
corresponding entity occurrence in a particular relationship. Has-
instant of the same entity then it is
2. Some Lecturers may not Teach any Students I Each Student must be taught by at ITEM components
called many-to-many relationship
least one Lecturer
M N
Lecturer Teaches Student
same entity then it is called One to many (1-N): One instance of the one entity type can be associated with
number of instances of other entity type.
one-to-one relationship
Eg: PRODUCT
In this Eg is_married_to is shown as a 1-1 relationship between instances of the PRODUCT LINE Contains
Many-to-many: The number of instances of one entity type can associated with RELATIONSHIPS WITHIN THE RELATIONAL DATABASE
number of instances of other entity type. A relationship is an association among the instance of one or more entity types. The
relationship are classified as one-to-one (1: 1), one-to-many (1: M), and many to many
(M: N or M: M)
Eg: STUDENT Registers-
_for COURSE The 1:M Relationship:
The 1: M relationship is the relational database norm. consider the PAINTER paints
This eg indicated that an employee may complete more than one course and then PAINTING example.
each course may have many employees.
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
VENDOR Supplies WAREHOUSE
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:
Shipping mode
unitcost
1. In this eg vendor can supply various parts to warehouse. As the 1: 1 table implies, in this relationship, one entity can be related to only one
2. The relationship supply is used to record to specific parts that are supplied by a other entity, and vice-versa. For example, one department chair – a professor – can
given vendor to a particular warehouse. chair only one department can have only one department chair. The entities PROFESSOR
3. Thus there is three-entity type VENDOR, PARTS, WAREHOUSE. and DEPARTMENT thus exhibit a 1: 1 relationship.
4. There are two attributes are relationship is shipping code and unit-cost.
Quaternary Relationships The preceding “PROFESSOR chairs DEPARTMENT” example illustrates a proper 1:
1 relationship. In fact, the use of a 1:1 relationship ensures that two entity sets are not
Quaternary relationships involve four entities. The example of quaternary placed in the same table when they should not be.
relationship is “A professor teaches a course to students using slides.” Here the four
entities are PROFESSOR, SLIDES, COURSE, and STUDENT. The relationships between
PROFESS DEPARTMENT
the entities are “Teaches.” Chairs
The M : N Relationship
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 Mapping Algorithm
index key and a set of pointers.
The mapping algorithm gives the procedure to map ER diagram to tables.
DBMS use index for many different purposes. An index can be used to retrieve The rules in mapping algorithm are given as:
data more efficiently. But indexes can also be used by a DBMS to retrieve data ordered
by a specific attribute or attributes. – For each strong entity type say E, create a new table. The columns of the table are the
attribute of the entity type E.
For example, creating an index on a customer’s last name will allow you to – For each weak entity W that is associated with only one 1–1 identifying
retrieve the customer data alphabetically by the customer’s last name.
owner relationship, identify the table T of the owner entity type. Include
Index play an important role in DBMSs for the implementation of primary keys, as columns of T, all the simple attributes and simple components of the
when you define a table’s primary key column(s). The DBMS automatically creates a composite attributes of W.
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. – For each weak entity W that is associated with a 1–N or M–N identifying
relationship, or participates in more than one relationship, create a new
Symbols Used in ER Diagram
1. The elements in ER diagram are Entity, Attribute, and Relationship. table T and include as its columns, all the simple attributes and simple
2. The different types of entities like strong, weak, and associative entity, components of the composite attributes of W. Also form its primary key
3. Different types of attributes like multivalued and derived attributes and identifying
relationship and their corresponding symbols by including as a foreign key in R, the primary key of its owner entity
– For each binary 1–1 relationship type R, identify the tables S and T of
the participating entity types. Choose S, preferably the one with total
Strong entity Associate entity
participation. Include as foreign key in S, the primary key of T. Include
as columns of S, all the simple attributes and simple components of the
composite attributes of R.
Week entity
Attribute – For each binary 1–N relationship type R, identify the table S, which is at
N side and T of the participating entities. Include as a foreign key in S, the primary key
of T. Also include as columns of S, all the simple attributes and simple components of
composite attributes of R.
Multivalue attri. – For each M-N relationship type R, create a new table T and include as
Relation ship
columns of T, all the simple attributes and simple components of composite attributes of
R. Include as foreign keys, the primary keys of the participating entity types. Specify as
the primary key of T, the list of
foreign keys.
– For each multivalued attribute, create a new table T and include as
Identify Rel.Ship Derive Attribute
columns of T, the simple attribute or simple components of the attribute
A. Include as foreign key, the primary key of the entity or relationship
type that has A. Specify as the primary key of T, the foreign key and the
columns corresponding to A.
Regular Entity
Regular entities are entities that have an independent existence and generally
Example
In this example the composite attribute is the Customer address, which consists of
Street, City, State, and Zip.
Converting “Weak Entities” in ER Diagram to Tables
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.
Converting Binary Relationship to Table
Mapping Multivalued Attributes in ER Diagram to Tables
A relationship which involves two entities can be termed as binary relationship.
What is an extended entity relationship model? Explain entity super types and
sub types? Or THE EXTENDED ENTITY RELATONSHIP MODEL (EER model)
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 V-name
Cab Type
1. The property of inheritance enables (allow) an entity subtype to inherit the V-ID
attributes and relationships of the super type.
2. A super type contains those attributes that are common to all of its subtype.
Truck Capacity
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. Price Engine Displacement
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 Make Model
process of viewing an object as a more refined, specialized object.
V-name
V-ID
Vehicle
Engine Displacement
Price
Cab Type
Car Truck
Capacity
No. of passengers
The process of defining a more general entity type from a set of more specialized entity
types. Thus generalization is a “Bottom up process”.
Ex:
In the above diagrams car, truck and motor cycle contains a no. of attributes in
Description Location
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 Part-no Quantity
Part S-ID
general entity types. This more general entity type (vehicle) together with the resulting on Hand
supertype / subtype relationships is shown in above fig b.
The entity car has the specific attribute, no. of passengers, while truck has 2 Routing-No Supplier
specific attributes capacity and cab type. Thus generalization has allowed us to group Unit
entity types along with their common attributes and at the same time preserve specific Price
Specialization:
In the above ex entity type part having attributes partno, description, unit price,
The process of defining one or more subtypes of the supertype and forming
location, quality on hand, routing no and supplier.(a supplier attribute is Multivalued
supertype/subtype relationships.
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.
Price ISA Relationship and Attribute Inheritance
Supplier
Description
Supplier-ID
IS A relationship supports attribute inheritance and relationship participation.
Part-no
Part
Routing-No In the EER diagram, the subclass relationship is represented by ISA
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.
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. With total
Constraints on Specialization and Generalization specialization, an instance of the supertype must be a member of at least one
The constraints on specialization and generalization can be broadly classified into subtype.
disjointness and completeness. The dis jointness constraint allows us to specify
whether an instance of a super type may simultaneously be a member of two or
more subtypes. In dis jointness we have two categories (1) Overlap and
(2) Disjoint. In completeness we have two categories
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 Partial Specialization
and Crocodile which can live in both land and water hence the division of Partial completeness refers to the fact that an entity instance in the superclass
ANIMAL into LAND and WATER animals is an example of overlap constraint. 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 Entity Clusters
subtype. EER diagrams are difficult to read when there are many entities and relationships.
Example of Partial Specialization One possible solution is to group entities and relationships into entity clusters.
Consider the PERSON specialization into EMPLOYEE and STUDENT. This Entity cluster is a set of one or more entity types and associated relationships
is an example of partial specialization because there can be a person who is grouped into a single abstract entity type.
unemployed and does not study.
Connection Traps
Fan Trap
Fan trap occurs when the model represents a relationship between entity types
but the pathway between certain entity occurrences is ambiguous. Fan trap occurs
when 1–M relationships fan out from a single entity. In order to understand the
concept of Fan trap, consider the following example
Contractor works in a team. . . . . . . . . Statement (1)
Team develops projects. . . . . . . . . . . . Statement (2)
Statement (1) represents M–1 relationship. Statement (2) represents 1–M
Composition is a stronger form of aggregation where the part cannot exist relationship. But the information about which contractors are involved in
without its containing whole entity type and the part can only be part of one entity developing which projects is not clear.
type.Consider the example of DEPARTMENT has PROJECT. Each project is
Consider another example of Fan trap.
associated with a particular DEPARTMENT. There cannot be a PROJECT without
DEPARTMENT. Hence DEPARTMENT has PROJECT is an example of composition. Department is on Site. . . . . . . . . Statement (1)
Site employs Staff. . . . . . . . . . . . . . . Statement (2)
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
12. Non – Subversion Rule: This rule states that different levels of the language can
Foreign key: not subvert or bypass the integrity rules and constraints.
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 Integrity rules or relational integrity:
PRIMARY KEY in another table. 1. Relational database integrity rules are very important to good database design.
4. The table containing the foreign key is called the child table, and the table 2. Many (but by no means all) RDBMSs enforce integrity rules automatically.
containing the candidate key is called the referenced or parent table. 3. The set of rules which are used to maintain the accuracy of the data and to
integrate (add) the data in database is called as integrity constraints.
CREATE TABLE BABA1 ( 1. Domain Integrity.
Sno int PRIMARY KEY, 2. Entity Integrity.
Sna varchar2(20) NOT NULL, 3. Referential Integrity.
SID int FOREIGN KEY REFERENCES JDC(ID)
); 1. Domain Integrity:
1. A domain is a set of values which is assigned to an attribute.
Explain Dr. E.F.CODD Rules 2. The components of the domain are domain name, meaning, data type, size and
[For any RDBMS to be accepted as full fledged RDBMS it has to follow the 12 CODD range of the values.
rules . The rules are] There are 12 CODD rules.
Ex: student relation the domains are regdno, name.
1. The information Rule: it is used to be represented all information as a data values
in the rows and columns of tables. This is the basis of the relational model. 2. Entity Integrity :
1. All primary key entries are unique, and no part of a primary key may be null.
2. The guaranteed access Rule: Every data value in a relational database should be 2. Each row will have a unique identity, and foreign key values can properly
logically accessible by specifying a combination of the table name, the primary key reference primary key values.
value on column name. 3. A primary key is an attribute in a relation which is used to identify each row in a
relation.
3. Systematic Treatment of NULL values: DBMS must support NULL values to 4. No. of components of a primary key value may be NULL.
represent missing or inapplicable information. They must be distinct from zero or 5. This is called as entity integrity.
spaces. 6. A NULL is an undefined value. One NULL is not equal to another NULL.
NOT NULL: its not supports empty value in attribute. The NOT NULL constraint ex: σ subject = "database"(Books)
can be placed a value for that column.
P_CODE P_DESCRIPT PRICE
UNIQUE: The UNIQUE constraint is used to not support duplicate values exists 123456 Flash light 5.26
column. 123457 Lamp 25.15
123458 Box Fan 10.99
123459 9v battery 1.92
What is a Relational Algebra 123455 100W bulb 1.47
1. The relational algebra is a notional language with operations 123454 Powerdrill 34.99
2. That work on one or more relations to define another relation without changing
the original relation. SELECT only PRICE less than Rs. 2.00 yields P_CODE P_DESCRIPT PRICE
3. The both the operands and the results are relations; 123459 9v battery 1.92
4. The output from one operation can become the input to another operation. 123455 100W bulb 1.47
5. This allows expressions to be nested in the relational algebra. This property is called 1. b. Projection Operation
closure. 2. The projection operation works on a single relation R
6. Relational algebra is an abstract language, 3. And defines a relation that contains a vertical subject of R,
7. It means that the queries formulated in relational algebra are not intended to be 4. And extracting the values of specified attributes and elimination duplicates.
executed on a computer. 5. The projection operation can be considered as column wise filtering.
8. Relational algebra consists of group of relational operators that can be used to It’s creates all values for selected attributes. In other words, project creates
manipulate relations to obtain a desired result. a vertical subset of a table.
9. Knowledge about relational algebra allows us to understand query execution and
optimization in relational database management system. Syntax
a1,a2,......an (R).
Explain Relational Algebra Operations (Relational Set operators) [Where a1, a2, . . . . . . an are attributes and R stands for relation To illustrate
Operations in relational algebra can be classified into set operation and database projection operation consider the relation STAFF, with the attributes Staff number,
operations. Name, Gender, Date of birth, and Salary.]
1. Unary and Binary Operations SALES:
1. Unary operation involves one operand,
a. selection P_CODE PRICE
b. Projection P_DESCRIPT PRICE
2. Binary operation involves two operands. 123456 Flashlight 5.26 5.26
PROJECT PRICE yields
a. Union operation 123457 Lamp 25.15 25.15
b. Difference operation 123458 Box Fan 10.99 10.99
c. Cartesian product operation 123459 9v battery 1.92 Select price from sales; 1.92
d. Intersection operation 123455 100w bulb 1.47 1.47
e. Division operation 123454 Power drill 34.99 34.99
f. Join operations operation
2. Relational algebra operations PRICE
P_DESCRIPT
3. Set Operations Database operations Flashlight 5.26
PROJECT P_DESCRIPTand PRICE yields Lamp 25.15
Three main database operations are SELECTION, PROJECTION, and JOIN. Box Fan 10.99
9v battery 1.92
1. a. Selection Operation 100w bulb 1.47
1. The selection operation works on a single relation R Select components, price, from sales; Power drill 34.99
2. And it defines a relation that contains only those tuples of R
3. That satisfies the specified condition (Predicate).
2. a. Union Operation
Notation: R __ S
A conditional join in which we impose condition other than equality condition. If equality Example of Full Outer Left Outer and Right Outer Join
condition is imposed then theta join become equi join. The symbol θ stands for the
comparison operator which could be >, <, >=, <=. Consider two relations PEOPLE and MENU determine the full outer, left
σθ(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
left null.
Types of Outer Join
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
UNIT IV 3. It includes the sign and the decimal place. Examples: 12.32, -134.23
4. L means length, D means Decimal numbers
Syntax:
Column-name data-type (L);
or
Introduction to ORACLE Column-name data-type (L, D)
Ex:
1. Oracle is a Relational Database Management System (RDBMS). Sno number (3);
2. Oracle being RDBMS, stored data in tables called relations. or
3. These relations are data can be representation in two-dimensional sno number(7,2);
4. The rows are called tuples it represents records
5. The columns called attributes it represents pieces of information contained in the b. Integer:
record. 1. It may be abbreviated as INT
2. Integers are (whole) counting numbers,
Benefits of Standardized Relational Language 3. So they cannot be used to store numbers that require decimal places
The main advantages of standardized language are given below. Syntax:
1. Reduced training cost Column-name data-type (L);
2. Enhanced productivity Ex:
3. Application portability Sno integer (3);
a. Application portability means applications can be moved from machine to
machine when each machine uses SQL. c. Smallint:
4. Application longevity: 1. Like Integer, but limited to integer values up to six digits.
a. A standard language tends to remain so for a long time,
2. If your integer values are relatively small, use smallint instead of Int.
b. There will be little pressure to rewrite old applications.
5. Reduced dependence on a single vendor SQL language development is given in a Syntax:
nutshell below: Column-name data-type (L);
a. In 1970 E.F. Codd of IBM released a paper “A relational model of data for Ex:
large shared data banks.” Sno smallint(3);
b. IBM started the project System R to demonstrate (show) the feasibility
(possibility) of implementing the relational model in a database d. Decimal(l,d)
management system. 1. Like the number specification, but the storage length is a minimum
c. The language used in system R project was SEQUEL.
specification.
d. SEQUEL was renamed SQL during the project, which took place from 1974 to
1979. 2. That is, greater lengths are acceptable, but smller ones are not.
6. The first commercial RDBMS from IBM was SQL/DS. It was available in 1981. 3. Decmal (9,2), decimal(9), and decimal are all acceptable.
7. Oracle from relational software (now Oracle Corporation) was on the market
before SQL/DS, i.e., 1979. Syntax:
8. Other products included INGRES from relational Technology Sybase from Sybase, Column-name data-type (L);
Inc. (1986), DG/SQL from Data General Corporation (1984). or
Column-name data-type (L, D)
DATA TYPES: Ex:
It specified which type data and size can be stored in a specific field or it specified the Sno decimal (3);
field size and type in a file. or
Numeric: sno decimal (7,2);
1. The number data type is used to store zero, positive and negative values.
2. User can specify a fixed point number using the following form Character
3. There are different types of data types The character data type is used to store character ( alphanumeric) data. This can
a. Number(L,D) be fixed length or variable length
b. Integer 1. Char(L)
c. Smallint 2. Varchar(L) or Varchar2(L)
d. Decimal(l,d)
a. Char(L)
a. Number(L,D): 1. Fixed-length character data fro up to 255 characters.
1. The declaration Number (7,2) indicates numbers
2. If you store strings that are not as long as the char parameter value
2. That will be stored with two decimal places and may be up to seven digits
long, 3. The remaining spaces are left unused.
4. Therefore, if you specify char (25), each stored as 25 characters
Commands in SQL 1. To change (alter) table structure by changing attribute character and by adding
SQL commands can be classified in to different types: columns.
2. All changes in the table structure are made by using the ALTER TABLE command.
1. Data Definition Language commands (DDL) 3. ADD, MODIFY and DROP keywords
2. Data Manipulation Language commands (DML) 4. That produces the specific change user want to create
3. Transaction Control Language (TCL)
5. Use ADD to add a column, MODIFY to change column characteristics and DROP
to delete a column from a table SQL> alter table student modify(sname varchar2(15));
6. Most RDBMSs do not allow you to delete a column (unless the column does not
contain any value). Table altered.
7. The alter table command can also be used to add table constraints.
/* SQL> desc student;
Syntax: Name Null? Type
Alter table table-name ADD constraint [ADD constraint]; ----------------------------------------- -------- ----------------------------
SNO NUMBER(3,1)
ADDING A COLUMN: SNAME VARCHAR2(15)
SADD VARCHAR2(10) */
Alter an existing table by adding one or more columns
DROPPING A COLUMN: (REMOVE A COLUMN AND REMOVE TABLE)
Syntax:
Alter table table-name add (column name <data type> 1. User wants to delete a table column by using drop
(size)); 2. User also remove the table using drop command
3. Some RDBMSs impose restrictions on attribute deletion.
SQL> alter table student add(totalmarks number(3)); 4. The attribute that are involved in foreign key relationships not delete an
attribute of table that contains only that one attribute.
Table altered.
Syntax: Alter table-table-name drop column column-name;
/* SQL> desc student;
Name Null? Type Ex: SQL> alter table student drop column sadd;
----------------------------------------- -------- ----------------------------
SNO NUMBER(3,1) Syntax: drop table tablename;
SNAME VARCHAR2(15)
SADD VARCHAR2(10) Ex: SQL> drop table stu;
TOTALMARKS NUMBER(3) */
o RESTRICTION ON ALTER COMMAND:
CHANGING (MODIFY) A COLUMNS DATA TYPE: The alter table command cannot perform the following
1. Change the name of the table
Some RDBMSs such as oracle, do not let you change data type unless the column 2. Change the name of the column
to be changed is empty. 3. Decrease the size of a column it table data exists.
Syntax: Alter table table-name add (column name <data type> (size));
RENAMING TABLES:
SQL> alter table student modify(sno decimal(3,1)); Changing the table name from old to new name is called rename a table.
SQL> insert into student (sno,sname)values(9,'saran'); 1. Any changes made to the table contents are not saved on disk until user close
the database,
UPPDATE (UPDATING TABLE ROWS) 2. To change the database to use the COMMIT command
1. The update command to modify data in a table. Syntax: COMMIT [WORK]; Ex: COMMIT;
The COLUMNLIST represents one or more attributes, separated by commas. Syntax: savepoint <savepointname>;
Ex:
SELECT ENO,ENAME FROM EMP; or SELECT * FROM EMP; Ex: savepoint s1;
/*Ex: SQL> insert into emp values(12,’manju’);
The * specifies that all columns appears in the EMP table. SQL>insert into emp values(13,’sai’);
Syntax: Ex:
grant privilegesname on <object name> to <username> SQL> Select distinct sname from std;
Select deptno, job, avg(sal), from emp group by deptno,job; SQL> SELECT COUNT (EMPNO) FROM EMP;
Rows may be pre exclude with WHERE clause, before dividing them into groups. /* COUNT(EMPNO)
------------
Ex: 14 */
To show the average salary for each JOB excluding manager.
SQL> SELECT COUNT (*) FROM EMP WHERE SAL < =1500;
Select job, avg(sal) from emp where job!=’MANAGER’ group by job;
/* COUNT(*)
Having Clause --------
1. It works like a where clause, except that its logic is only related to the results of 7 */
group functions as opposite (different) to columns or expressions for individual Count (*) returns the number of total rows returned by the query, including the
rows, which can still be selected with where clause. rows that contain nulls.
Ex: b. MAX:
Select deptno,sum(sal) from emp group by deptno having sum(sal)>1000; 1. The aggregate function Max (column) can be used only in the column list of a select
statement.
Select deptno,avg(sal) from emp group by deptno having coun(*)>3; 2. It returns a minimum value of a expression.
Select job, avg(sal) from emp where job!=’MANAGER’ group by job; SQL> SELECT MAX (SAL) FROM EMP;
Or
Select job,avg(sal) from emp having job!=’MANAGER’ group by job;
Or c. MIN:
Select job,avg(sal) from emp group by job having job!=”MANAGER’; 1. The aggregate function Min (column) can be used only in the column list of a select
statement.
PROJECTION OPERATION 2. It returns min value of a given expression
1. The projection operation performs column wise filtering.
2. Specific columns are selected in projection operation. SQL> SELECT MIN (SAL) FROM EMP;
/*
Syntax: MIN(SAL)
--------
SELECT column-name1, column-name2, Column-name N FROM table-name; 800 */
d. SUM:
If all the columns of the table are selected, then it cannot be considered as PROJECTION. 1. The sum function computes the total sum fro any specified attribute, using whatever
condition.
1. The SQL command to perform PROJECTION operation on the relation PEAKS and
the corresponding results SQL> SELECT SUM (SAL) FROM EMP;
2. it is clear that only three columns are selected in the result.
e. AVG:
Ex: select sno,sname from std; The avg function format is similar to that of min and max. it returns an average
value of given column name
GROUP FUNCTIONS: OR AGGREGATE FUNCTIONS:
1. These functions can be used for calculations on groups of selected records. SQL> SELECT AVG(SAL) FROM EMP
2. Group functions can appear in select lists, GROUP BY and/or HAVING clauses.
They are, SINGLE ROW FUNCTIONS:
a. Count The no. of rows containing non-null values 1. The single row functions can appear in a select command and can also be
b. Min The minimum attribute value encountered in a given column included in where class.
c. Max The mximum attribute value encountered in a given column 2. The single row functions classified as
d. Sum The sum of all valued for given column a. Date ,
e. Avg The arithmetic mean (average) from specified column b. Numeric
c. Character
a. COUNT: d. Mislenious
1. The count function is used to tally (count) the number of non-null values of an
attribute.
3. The examples which are not based on a particular table use the system table SQL> Select abs(-12.3467) from dual ;
‘dual’.
4. It is a table which is automatically created by oracle along with the data /* ABS(-12.3467)
dictionary. -------------
5. DUAL is a table owned by SYS. 12.35 */
6. SYS owns the data dictionary, and DUAL is part of the data dictionary.
7. Dual is a small oracle worktable, which consists of only one row and one Power ( ): - It returns the power value to the base value.
column
8. It contains the value X in that column. SQL> Select power (3,4) from dual;
9. Besides arithmetic calculations, is also supports date retrieval and it’s
formatting. /* POWER(3,4)
----------
DATE FUNCTIONS: - 81 */
They operate on date values producing O/P which also belongs to date, Trunc ( ): - It returns truncated values
Data type except for months between date function which returns a number.
SELECT TRUNC(12.3456,2) FROM DUAL;
1. Add – months: It returns a date data type as a result format add-months date,
number. /* TRUNC(12.3456,2)
----------------
Eg: - Select add_months ('27-Aug-04',2) from dual; 12.34 */
/* ADD_MONTH Round ( ): - It returns a number which is rounded upto some decimal points.
---------
27-OCT-04 */ SQL> SELECT ROUND (12.3456,2) FROM DUAL;
2. Months-between: /* ROUND(12.3456,2)
a. It returns a number date type as a result. Formate: - moths-between ----------------
date1, date2; 12.35*/
NUMERIC FUNCTIONS: - initcap ( ): - It returns first letter as a capital letter of the string.
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. Eg: - Select initcap ('ram') from dual
3. Numeric functions are:
/* INI
Abs( ): - It returns absolute value ---
Ram */
Upper ( ): - It convert all lower case letters into upper case. /* GREATEST(100,200,300)
---------------------
SQL> Select upper ('good') from dual; 300 */
Lower ( ): - It converts all the uppercase letters into lower case. /* LEAST(100,200)
--------------
SQL> SELECT LOWER ('RAM') FROM DUAL; 100 */
Lpad ( ): - It adds the string to the left side of the string1 /* USER
-----------
Eg: - Select Lpad (‘good’,12,’day’) from dual; SCOTT */
Rpad ( ): - It add the string2 to the right side of the string1. /* UID
Eg: - Select Rpad (‘good’,12,’day’) from dual; ----------
66 */
/* RPAD('GOOD',
------------
Gooddaydayda */
/* RTR
---
Sai */
/* C
EXPLAIN DIFFERENT TYPES OF CONSTRAINTS. 3. It is also used to set the relations between the tables.
1. Constraint is a rule that can be applied on a table or a column of a table. 4.
2. Constraints can also be used to prevent (check) mistakes in data entry. Syntax:
3. Constraints can be categorized into following, Create table <table name> (<column name> <data type>
constraint <constraint name> primary key);
1. Domain Integrity Constraints Ex:
a. Not null b. Check Create table student(sno number(10) constraint P primary key, sname
varchar2(10));
2. Entity Integrity Constraints.
a. Primary key b. Unique 3. Default constraint:
1. Its read automatically value when user not enter value
3. Referential Constraint
a. Foreign key Syntax:
Create table <table name> (<Column name> <data type>
Domain Integrity constraints <Default> <value>)
1. Not Null: Ex:
1. By default all columns in a table allow NULL values. CREATE TABLE Persons (id number (3), name varchar2 (20) default
2. When a NOT NULL constraint is enforced on a column in a table, ‘abhyudaya’);
3. It will not allow NULL values into that column. Referential Integrity Constraints
1. Foreign key Constraint
Syntax: 1. The referential integrity constraints enforce (impose) the relationship between the
Create table <table name> (<column name> <data type> tables
constraint <constraint name> NOT NULL); 2. Tables are used primary key
Example: 3. It helps in creating a parent child relation ships between the tables.
Create table tab (no number(3) constraint C NOT NULL); 4. A referential integrity constraint assigns a column as a foreign key.
5. Child table primary key is called foreign key
2. Check constraint
6. Parent table primary key is called referenced key is called parent table.
1. These are rules govern logical expressions or Boolean expressions.
Syntax:
Syntax:
Create table <table name> (<column name> <data type>,
Create table <table name> (<column name> <data type>
constraint <constraint name> references
constraint <constraint name> check
<table name> (column name));
(column name with condition));
Ex:
Example:
Create table emp1 (eno number(3) constraint P1 primary key,
ename varchar2(20));
Ex1: Create table stud (marks number (5) constraint c1 check (marks>35));
Create table dept (eno number(3), dname varchar2(20));
Ex2: alter table emp add constraint ck_emp check (sal + comm <10000);
Now connecting the dept and emp using foreign key
Entity Integrity Constraints
1. Unique Constraint:
Create table dept1(eno number(3) references emp1(eno),
1. This constraint allows only unique values to be stored in the column.
dname varchar2(20));
2. Oracle rejects duplication of records when the unique key constraint is used.
3. It can also allow NULL values. Since two NULL values are not allowed because
DELETING, ADDING A CONSTRAINT IN TABLES
it is duplicate.
1. The user can disable or remove or enable constraints attached to the column
with the help of alter command.
Syntax:
Create table <table name> (<column name> <data type>
Syntax:
constraint <constraint name> unique
Alter table <table name> disable|enable constraint <constraint name>;
(column name));
Ex:
Alter table <table name> modify (<column name> <data type>
Create table JDC (sno number(10) , sname varchar2(10), sphno number(15)
constraint <constraint name> <constrain type>);
unique);
Removing a Constraint:
1. To remove constraint attached to a column name alter with drop constraint
2. Primary key constraint:
is used.
1. It avoids duplication of rows and does not allow NULL values.
2. Primary key is the combination of NOT NULL and UNIQUE.
Syntax:
b. UNION ALL: /* To display employee name, job, department no, department name and
location in which the employees work. */
The UNION ALL operator written all rows selected by either query including
duplicates. b. Non Equi Join :
A non equi join specifies the relationship between column belonging to different
Syntax: tables.
Select query
Union all Ex:
Select query; Select ename,sal,losal,hisal,grade From emp,salgrade Where sal between losal
Ex: and hisal;
Select *from emp UNION ALL select *from std; /* To display the grades of the employees based on salary. */
Select ename, job, dname from emp e, dept d Where d.deptno(+)=e.deptno ; b. less complexity,
c. better convenience, and
/*To which department name , job and location from department that does d. Customization.
not corresponding employees*/
1. Improved security:
EXPLAIN VIEWS OR VIRTUAL TABLES a. We can restrict the user to access on the data that are appropriate for the
1. A view is a virtual table based on select query. user.
2. The query contain column, computed column and aggregated functions from one b. Hence views provide improved security.
or more tables.
3. The tables on which the view is based are called base tables. 2. Less complexity:
a. A view can simplify queries,
Syntax: b. By getting data from several tables into a single table
c. Transforming multi table queries into a single table queries.
Create view <view name> as select query;
3. Convenience:
Characteristics a. A database may contain much information.
1. You can use the name of view any where a table name is expected in SQL b. All the information will not be useful to the users.
statements. c. The users are provided with only the part of the database
2. Views are dynamically updated. i.e. the view is recreated on demand each time is d. That is relevant to them rather than the entire database;
invoked. e. Hence views provide great convenience to the users.
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. Customization:
4. View may also be used as the basis for reports. a. Views provide a method to customize the appearance of the database
5. It use little storage space. b. So that the users need not see full complexity of database.
6. It establishes physical data Independency. c. View creates the illusion of a simpler database customized to the needs of a
Disadvantages particular category of users.
1. Use processing time, each time the view is referenced.
2. It may or may not be directly updatable. Drawback of VIEW
1. If the base table is modified by adding one or more columns
Drop View command 2. Then the columns added will not be available in the view unless it is recreated.
To delete a view from the database we use the drop view command. 3. When a view is created from the base table, it is to be noted that all the views are
not updatable.
Syntax: 4. Views created from multiple tables are in general not updatable when there is a
group function, a GROUP BY clause, or restriction operators.
Drop view <view name>;
Explain Sub queries and Correlated sub queries
Updatable Views
1. User can’t join tables in the update statement. SUBQUERY: (BASIC CHARACTERSTICS OF A SUB QUERY)
2. To solve that problem, users have to create update view. 1. A Sub query is a query inside a query.
3. An update view is a view that can be used to update attributes in the base table 2. A sub query is normally expressed inside parentheses.
that are used in the views. 3. The first query in the SQL statement is known as the outer query.
4. The query inside the SQL statement is known as the inner query .
Restrictions: 5. The inner query is executed first.
6. The outer query of an inner query is used as the input for the outer query.
1. Group by expressions of aggregate functions can not be used in the update views. 7. The entire SQL statements are sometimes referred to as a nested query.
2. User can’t use set operators.
3. Most restrictions are base on the use of joins or group operators in view. Sub queries are 2 types.
1. single row sub queries,
Materialized Views 2. multiple row sub queries
1. A materialized view is a physical copy of the base table
2. The results moved to another schema object. Single row sub queries
3. Materialized views are also called snapshots It returns only one row from the inner select statements.
4. Because they are a kind of photograph of the base table.
Multiple row sub queries
Advantage of VIEW It returns more then one row from the inner select statements.
1. The main advantages of view are
a. Improved security, Rules
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.
UNIT V
Syntax:
Declare
Variable declaration
Begin
Process statements
Or execution statement
[Exception
Exception statement]
End;
Ex: A PL/SQL block can be divided into four sections. They are
Sql> select ename from emp 1. Declaration section
Where not exists (Select eid from dep 2. Begin section
Where dept.eid=emp.eid); 3. Exception section
Correlated sub query: 4. End section
1. The subquery , the inner subquery executes first,
2. Its output is used by the outer query, 1. Declaration Section:
3. Which then executes until the last outer query executes. 1. Code blocks start with a declaration section
4. A correlated subquery that executes once for each row in the outer query. 2. In this block memory variable and other oracle objects can be declared
Embedded SQL 3. They can be used in SQL statements for data manipulation.
SQL can be used in conjunction with a general purpose programming language such as
PASCAL, C, C++, etc. The programming language is called the host language. Embedded Example:
SQL statements are SQL statements written within application programming languages Declare
such as C and Java First_name varhcar2(10);
Dynamic SQL Num number(10);
Programs containing embedded dynamic SQL statements must be precompiled like those
containing static SQL, but unlike static SQL, the dynamic SQL statements are 2. Begin Section:
constructed and prepared at run time. The SQL statement text is prepared and executed 1. It consists of a set of SQL and PL/SQL statements
using either the PREPARE and EXECUTE statements, or the EXECUTE IMMEDIATE 2. It describes process that has to be applied to table data.
statement. The statement can also be executed with cursor operations if it is a SELECT 3. Actual data manipulation, retrieval, looping and branching constructs are
statement specified in this section.
1. Sequential control statements, which are not crucial (central or Main) to PL/SQL Cursor process commands open, fetch (get) and close any where between begin and
programming. end keywords of PL/SQL block.
2. The sequential control statements are
a. GOTO Command Explanation
It goes to a specified statement, and NULL, which does nothing.
1. Open the cursor, execute the SQL command and
Goto statement: populate the cursor with data.
1. The Oracle PL/SQL GOTO statement is a sequential control structure available in Open 2. Before you can use a cursor, you need to open it.
Oracle. Syntax:
2. The GOTO statement immediately transfers program control (called "branching") open <cursor name>;
using with label or block label. 1. The fetch command to retrieve data from the cursor
3. The statement or label name must be unique in the block. and copy it to the PL/SQL variables for processing.
Fetch
Syntax:
Syntax: fetch <cursor name> into <var list>;
<<Lable>> 1. The close command closes the cursor for processing.
Statement 1; Close Syntax:
………….. close <cursor name>;
Statement n;
if(condition) then Syntax:
Goto label; Declare
end if; Cursor <cursorname> is <select statement>;
Ex: Variable declaration;
declare Begin
n integer:=&n; Open <cursorname>
i integer:=1; Fetch <cursorname> into variablename1…..;
begin close <cursorname>;
<<p>> End;
dbms_output.put_line(i);
i:=i+1; Cursor Attributes
if(i<=n) then
goto p; Attribute Description
end if;
Keeps the count of record for each fetch when the cursor is
end; %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
Explain processing with cursors in PL/SQL. otherwise FALSE.
1. PL/SQL provides to access more than one record from database Returns TRUE if cursor is open otherwise FALSE if the cursor
%isopen
2. This method is a combination of select statement and memory management is closed.
routines from PL/SQL
3. To retrieve records from database using select statement and places them with in Example:
memory known as cursor. Declare
a emp%rowtype;
There are two types of cursors. cursor c2 is select * from emp where deptno=&deptno;
begin
Implicit Cursor – open c2;
1. It is automatically created in PL/SQL when the SQL statement returns only loop
one value. fetch c2 into a;
if c2%found then
Explicit Cursor – dbms_output.put_line(a.empno||’ ‘||a.ename||’
1. It is created to hold the output of an SQL statement that may return two or ‘||a.sal);
more rows. else
exit;
Syntax: end if;
Cursor <cursor name> is select query; end loop;
close c2;
2. It modifies one routine to eliminate duplicate testing. 9. The package specification does not contain any procedures or functions.
3. It avoids PL/SQL parsing at runtime by parsing at compile time. 10.Applications or users can call packaged procedures and functions
4. It reduces the number of calls to the database
5. Database network traffic by bundling (collecting) the commands Advantages of Packages
6. User-defined functions cannot be used in situations Packages offer a lot of advantages. They are as follows.
7. That requires an unchanging definition. 1. User can create package to store all related functions and procedures are grouped
8. Thus, you cannot use user-defined functions: together into single unit called packages.
a. In a CHECK constraint clause of 2. Package is reused.
a CREATE TABLE or ALTER TABLE statement 3. All function and procedure within a package can share variable among them
b. In a DEFAULT clause of a CREATE TABLE or ALTER TABLE statement 4. Packages are support overloading to overload functions and procedures.
5. Package are improve the performance to loading the multiple object into memory at
Difference Between Function and Procedure once, therefore, subsequent calls to related program doesn't required to calling
Function: physically I/O.
1. Functions must always return a value. 6. Packages are reduced the traffic because all block execute all at once.
2. Functions cannot alter data or objects in a server. 7. Packages enable the organization of commercial applications into efficient modules.
3. You can embed functions within a SELECT statement. 8. Each package is easily understood
4. Functions can accept input parameters but can return only a single return 9. Packages interfaces between packages are simple, clear and well defined.
value. 10.Packages allow granting of privileges efficiently.
5. TEMP tables can’t be used in functions. 11.Packages promote code reuse through the use of libraries
6. user-defined functions cannot be used in CHECK or DEFAULT constraints 12.That contain stored procedures and functions, thereby reducing redundant coding .
7. and cannot manipulate database values 13.Each package is easy to understand, and the interfaces between packages are simple,
8. It is mandatory for a function to have at least one RETURN statement clear, and well defined.
9. It will not allow to do the DML on existing tables. But still we can do the DML 14.Easier Application Design it stored programs and subprograms
operation only on the table variable inside the user defined functions. 15.Packages can specify which types, items, and subprograms are public (visible and
10.The transaction statement cannot be used in the function. Normally we won't accessible) or private (hidden and inaccessible).
do any DML operations in the function. 16.For example, if a package contains four subprograms, three might be public and one
11.The parameters for the stored procedures can be any data types which are private.
available on the sql server. 17.The package hides the implementation of the private subprogram so that only the
package (not your application) is affected if the implementation changes.
18.They can be shared by all subprograms that execute in the environment.
Procedures: 19.To maintain data across transactions without having to store it in the database.
1. Stored procedures do not have this requirement. 20.User call a packaged subprogram for the first time, the whole package is loaded into
2. Stored procedures can alter data and objects in database and server. memory.
3. Stored procedures cannot be embedded within a SELECT statement. 21.To related subprograms in the package require no disk I/O.
4. Stored procedures can also accept OUTPUT parameters. 22.Packages stop cascading dependencies and thereby avoid unnecessary recompiling.
5. Both TEMP tables and Table variables can be used in stored procedures. 23.Change the implementation of a packaged function
6. It is not mandatory for a procedures to have at least one RETURN statement
7. In case of procedures with RETURN statement, simply the control of execution Units of Packages
is transferred back to the portion of code that called the procedure.
8. The stored procedures can do all the DML operations like insert the new record, As described earlier, a package is used to store together, the logically related PL/SQL
update the records and delete the existing records. units.
9. The transaction statement can be used inside the stored procedures. 1. Procedures
10.The function won't allow several data types of the sql server as a parameter. 2. Functions
3. Triggers
Explain Packages 4. Cursors
1. A package can be defined as a collection of related program objects. 5. Variables
2. Such as procedures, functions, and associated cursors and variables together as a
unit in the database. Parts of Package
3. A package is a group of related procedures and functions A Package has two parts. They are:
4. It stored together and sharing common variables, as well as local procedures and 1. Package specification
functions. 2. Package body
5. A package contains two separate parts:
a. The package specification and 1. Package Specification
b. The package body. 1. The specification declares the types, variables, constants, exceptions, cursors,
6. The package specification and package body are compiled separately and subprograms
7. And stored in the data dictionary as two separate objects. 2. These are public and thus available for use outside the package.
8. The package body is optional and need not to be created
Syntax: END;
CREATE [OR REPLACE] PACKAGE <package name>
[AS/IS]
DROP PACKAGE <PACKAGE NAME>; 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
Triggers: 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
Example
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
the number, date, and user of login done by different user in that particular database.
The trigger will store this information in a table called log detail. The table log detail
must be created before trigger creation by logging into Administrator login. The trigger
can be created After logging into another login, if we see the content of the relation
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.
If tday=’mon’ then
This trigger gets fired when DDL statement such as CREATE, ALTER, or End;
DROP command is issued. DDL triggers can be associated with the database or with a Example 3
schema. Moreover depending on the time of firing of trigger, this trigger can be classified
into BEFORE and AFTER. Hence the triggers on Create or replace trigger strig
DDL statements can be as follows: Before update on emp for each row
– BEFORE CREATE and AFTER CREATE triggers fire when a schema Begin
– BEFORE ALTER and AFTER ALTER triggers fire when a schema object Raise_application_error(-20001,’salary not > 10000 update’);
– BEFORE DROP and AFTER DROP triggers fire when a schema object End;
Create or replace trigger abc before insert on dept for each row Before delete on emp for each row
Declare Begin
Sdate:=to_char(sysdate,’dy’); End;
End if;
End; This trigger gets fired when DML statement such as INSERT, UPDATE, or
Example 2: 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
Create or replace trigger etrig BEFORE and AFTER.
Tday varchar2(10);
Begin A row level trigger, as its name suggests, is fired for each row that will be
Tday:=to_char(sysdate,’dy’); 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
c_name customerS.No.ame%type;
c_addr customers.address%type;
BEGIN
SELECT name, address INTO cname, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/