Bca Dbms Short Notes
Bca Dbms Short Notes
1. What is DBMS and Write about its advantages(OR)objectives and disadvantagesof DBMS?
Ans:
Data
Data
ata is collection of raw facts like numbers
numbers, names and marks. The processed data is called information like
total and average.
Database
The database is a collection of inter-related
related data which is used to retrieve,
retrieve insert and delete the data
efficiently. It is also used to organize the data in the form of a table
table, schema, views, and reports, etc.
DBMS:
o Database management system is a software which is used to manage the database.
database For example: MySQL,
Oracle, etc are a very popular commercial database which is used in different applications
applications.
o DBMS provides an interface to perform various operations like database creation,
creation, storing data in it,
updating data, creating a table in the database and a lot more.
DBMS refers to organized collection of data or programmes. there are four basic functionsperformed by
DBMS. they are: a. create, modify and deletion of tables
b. insert, modifyand deletion of data within a table
c. retrieval of data based on user request
d. generating reports based on data and user requirements
Advantages of DBMS/ objectives of DBMS
1. Improved data sharing: DBMS allows to access the data by different users at a time. so, anytable in the
data base can possible to access the data simultaneously for end users.
2. Data integration: DBMS supports data integration. It represents overall data is located in asingle data
base i.e., it combines the data from different locations.
3. Multiple access: In DBMS, each user can use any application and to operate the data base. DBMS
support multiple accesses.
4. Backup and recovery: DBMS supports backup and recovery facility it can be useful if there is a
problem in the database in case of failure. DBMS supports recovery algorithms. It recovers the data from the
crashed database.
5. Data security: DBMS provides a framework for data privacy each user has a username and password.
So, with the help of username and password functionality, the security can be provided.
6. Concurrent access: DBMS supports various locks for processing the data in a serializable way. So, it
can support concurrent execution for database operation.
7. Efficient access: DBMS strongly provides efficient access because it retrieval of data including large
files in query format.
8. Reduced redundancy: redundancy means the same data and information in different locations. So,
unnecessary to store the extra copies of data. DBMS does not support redundancy so, no data is repeated.
9. Inconsistency: In DBMS, inconsistency is avoided all required data is stored insame location. i.e., no
data is duplicated and changes are made at one location.
10. Mass storage: DBMS can store a lot of data.
11. Platform independent: No particular platform is required to work on DBMS.
Disadvantages of DBMS
o Cost of Hardware and Software: It requires a high speed of data processor and largememory size to
run DBMS software.
o Size: It occupies a large space of disks and large memory to run them efficiently.
o Complexity: Database system creates additional complexity and requirements.
o Higher impact of failure: Failure is highly impacted the database because in most of the organization, all
the data stored in a single database and if the database is damaged due to electric failure or database
corruption then the data may be lost forever.
2. Define file system? Write about drawbacks of file system?
Ans : It is a mechanism of organizing the data in a file by writing programs is called file system. The
purpose of file is used to store the data permanently.
In general, the file containing collection of records. Each record contain collection of fieldsand each field
can store the data. In the file system, the data is stored in different files on the hard disk. so, these files are
not possible to share the data by different users. this type of mechanism is good at that time. But now a days
it is not possible.
Advantages:
1. The file system design is easier to understand.
2. In the file system avoid some problems in DBMS software.
Disadvantages or drawbacks:
The drawbacks of file system is represented as follows
1. No data sharing: The file system does not support data sharing so, we must duplicate every fileto
different users.
2. No data integrity: In the file system, the data files are stored in different location around the disk. So it
is difficult to maintain data files.
3. No data security: In the file system, does not support any security. It cannot controlunauthorized user to
access the data.
4. Increased Redundancy: Redundancy is major problem that occupies more space in disk. Itis maintain
multiple copies of the data.
5. No multiple access: In the file system, it is possible to access the data only one user at a time. Itallows
only a particular program to operate the database.
6. No concurrent access: The file system does not support concurrent access. Because it does notsupport
data sharing.
7. No backup and recovery: in the file system there is any standard method to backup the data.
The copy command is used to copy the required files. It does not contain any predefinedalgorithms for
recover the data.
8. No data models: The file system does not have any data model the records are stored in thedata file
according to the file format.
For example the file system is represented as follows
DATA INFORMATION
1. Data is collection of raw facts. 1. Information is processed data.
2. It is unarranged and unorganized. 2. It is arranged and organized.
3. It is un meaningful 3. It is meaningful.
4.Data is input. 4. Information is output.
5. It represents facts beforeprocessing. 5. It represents results.
6. It is not helpful in decision making. 6. It is helpful in decision making.
7. Data is large amount. 7. Information is small.
8. Data is unprocessed records. 8. Information is processed records.
9. If data is lost, it is very difficult. 9. If information is lost it is easily derived from
10. It is usedless frequently. data.
Ex: -In a student database marks arerepresented 10. It is used frequently
as data. Ex: -In a student database total, average are
represented as information.
4. what is database?
Database is a systematic collection of data. Databases support storage and manipulation of data. Databases
make data management easy. lets discuss few examples.
An online telephone directory would definitely use database to store data pertaining topeople, phone
numbers, other contact details, etc.
DBMS stands for Data Base Management system. It is used to store the data in the form oftables. It stores
thedata in organized manner.
7. Classification Of DBMS:
The classification of DBMS can be divided into 3 types based onfunctionality they are:
1. It is based on data model. 2. It is based on users.
3. It is based on database distribution.
1. Based on datamodel: In this functionality, the database is designed on based on datamodel. It is easy
to understand the meaning of thedata. There are different types of data models for support the
database. for examplethey are:
Hierarchical data model
Network data model
Relational data model
ER data model
Object oriented data model
2. Based on users: In this functionality, the database can be designed based on users. In generally it
can be dividedinto 2types. They are:
Single user database
Multi user database
Single user database: In this functionality, the database operations can beperformed only one user at a
time. It is called as single user database.
Multiuser database: In this functionality, the database operations can be performedmore than oneuser
at a time. It is called as multiuser database.
3. Based on distribution: In this functionality, it can be divided into 4 types they are:
Centralized database
Distributed database
Homogenious database
Hetrogenious database
Centralised database: In this functionality, the database is gathered at one system from differentsystems in
a network. It is called as centralised database.
Distributed database: In this functionality, the database is stored at different systems in anetwork. so, it
can be distributed. It is called as distributed database.
Homogenious Database: In this functionality, the same type of database is stored in a System. It is called
as Homogenious database.
Hetrogeneous database: In this functionality, different types of database is stored in aSystem. It is called as
heterogeneous database.
7. Explain DBMS Approach?Advantages and cost and risks of database approach?
An information system that uses a Database Management System (DBMS) to manage its information
has a particular structure, comprising three components: Data, DBMS, and Application software. This
structure as described below is referred to as the database approach to information system development.
The central component of the database approach is the DBMS. This software is also referred to as the
“database engine” or the “back end. ” With regard to the data it manages, it has several responsibilities
including the following:
Data Definition: providing a way to define and build the database
Data Manipulation: providing a way to insert and update data in the database
Query Execution: retrieving information from the data in the database
Data Integrity: ensuring that data stored is well-formed
Data Security: enforcing restrictions about who is able to access what data Provenance: logging
capabilities to provide an audit trail for data changes Multiuser Concurrency: supporting the activities of
many users at the same time
Advantages:
Ease of application development
Reduced data redundancy
Data can be shared
Data security
Backup and recovery
Multiple access
Data integrity
Disadvantages
Cost of Hardware and Software: It requires a high speed of data processor and largememory size to run
DBMS software.
Size: It occupies a large space of disks and large memory to run them efficiently.
Risks of the database approach
New specialised personnel: Need to hire or train new personnel e. g. databaseadministrators and
application programmers.
Need for explicit backup.
Organisational conflict: Different departments have different information needs and data representation.
Large size: Often needs alarmingly large amounts of processing power.
Expensive: Software and hardware expenses.
High impact of failure
1. A Data Model is a relatively simple representation, usually graphical, of more complex real-world data
structures.
2. The Data Model gives a clear view of database structure included in Databasedesign. Based on the
relationships the data models can be classified as below.
1. Hierarchical Data Model
2. Network Data Model
3. Relational Data Model
4. Object-Oriented Data Model
5. Entity Relational Data Model
1. Hierarchical Data Model: It is an oldest data model. In this model, the files arearranged in a
topdown approach. It represents a tree structured data model.
It contain level or segments. In this functionality, the top file is called as root node, thebottom filesare
called as child nodes and intermediate files are called as parent files. so, it is a parent-child relationship. It
support one-to-many relationship.
Advantages:
Easy to add and delete records.
It is simple to operate the records.
It supports data sharing.
Data can be retrieved easily due to the explicit links present between the table structures.
Disadvantages
o This model could not support many-to-many and many-to-one associations.
o There is no DDL and DML in DBMS.
o Poor flexibility
2. Network Data Model: It is represented in the form of graph. It contain set of points and
associations betweenthe files. It can support types of data structures. They are.
1. record type2. set type
The network database model is a model for modeling the entities in such a way that one child entity can
have more than one parent entity. In 1969, the network model was presented by Charles Bachman.
Advantages:
It is very efficient to retrieve the data.
It is simple and easy to design.
It can support one-to-many and many-to-many relationship.
Many parents can have many children.
Many children can have many parent
It support data integrity.
It has DDL and DML functionality.
Disadvantages:
It requires complex implementation.
Insertion, updating and deletion operations more complex in this model.
we can see that the subject is the child class and student and degree are the parentclasses.
So, the subject has two parent classes. STUDENT has one child and the Degree classalso have one child.
This kind of relationship among entities represents the network model.
3. Relational Data Model: It was introduced by ‘EF codd’, in the year 1970’s. Inthis model, the data is
represented in the form of tables. The table containcollection of rows and columns.
Each row is represented as record or tuple. Each column is representedas attribute or field. It is a2-
dimensional object.
So, in this model, the data is collected in the form of tables. These tables areimplemented using keys
likeprimary key, foreign key and so on.
Advantages:
Relational data model is simpler than hierarchical and network datamodels.
Changes in the structure do not affect the data access.
Easy to design.
Easy to implementation.
It support query feature.
Disadvantages:
Hrdware and software problems.
It may suffer information.
5. Entity Relationship Data Model: ER stands for Entity Relationship. It is a highlevel datamodel. It was
developed by ‘chen’ in 1976. It is used to represent entities, attributes, Relationships and constraints in
symbolic form. Entity is anything in which the data to be collected.
Advantages:
It is easy to view the database.
It contain entities and relationships.
Database designers, programmers and end user are easily understand thegraphical representation.
representation
Disadvantages:
It is a limited Relationship representation
representation.
It is a limited constraint representation.
It cannot support DML functionality.
1. Data:
The word ‘Data’ covers the collection of facts stored in the database data are the rawmaterialfrom which
information is generated.
2. Procedures
Procedures are the instructions and rules that govern the design and use of the databasesystem.
3. Hardware:
Hardware refers to all the system’s physical devices. The database system’smain and most
easily identified hardware component is the computer.
4. Software:
Software refers to the collection of programs used by the computer within thedatabase system.
5. users:
Database Administrator
Database Administrator is a person having central control over data andprograms accessing that data.
Database Designer
Database designer can be either logical database designer or physical databasedesigner.
designer
Database manager
The database manager would translate DML statement into low level file systemcommands forstoring
forstoring,
retrieving, and updating data in the database
database.
Database Users
Database users are the people who need information from the database to carry out theirbusiness
responsibility. The database users can be broadly classified into two categories like application
programmers and end users.
System Analysts
System analysts determine the requirements of end user, and developspecification for canned transaction
that meets this requirement.
1- tier architecture:
One-tier architecture involves putting all of the required components for asoftware application ortechnology
on a single server or platform.
2- tier architecture:
The two-tier is based on Client Server architecture. The two-tier architecture is like client server
application. The direct communication takesplace between client and server. There is no intermediate
between client andserver.
3- Tier Architecture
A 3 Tier Architecture in DBMS is the most popular client server architecture in DBMS in which the
development and maintenance of functional processes, logic, data access, data storage, and user interface
is done independently as separate modules. Three Tier architecture contains a presentation layer, an
application layer, and a database server.
A 3-tier architecture has the following layers:
1. Presentation layer (your PC, Tablet, Mobile, etc. )
2. Application layer (server)
3. Database Server
11. Explain 3 level architecture/ Ansi Spark Data Model/Data Abstraction/3 schemaarchitecture in
DBMS?
The 3level architecture provides an essential details for an operation by hiding complex details from the
user. It is called as Data Abstraction. In DBMS, the data abstraction can be performed through the following
levels. they are:
External/view level
Conceptual/logical level
Physical/internal level
These levels are also called as schema. It represents the design of the database orpart of the database, to store
the information.
1. External level
It is also known as view level.
This is highest level architecture and closest to the user.
The user doesn’t need to know the database schema details such as data structure, table definition etc.
External level is related to the data which is viewed by individual end users.
2. Conceptual level
It is also known as logical level.
The conceptual level is a higher level than the physical level.
This level is maintained by DBA(database administrator).
The whole design of the database such as relationship among data , schema of dataetc. are described in this
level.
It is the middle level between external or internal levels.
3. Internal level
It is also known as physical level.
This is the lowest level of the architecture.
This data is stored in the external hard drives in the form of bits.
This level describes how the data actually stored in the storage device.
This physical level also discuses encryption techniques.
This level is also responsible for allocating space of the data.
UNIT-2
ENTITYRELATIONSHIPMODEL
BUILDINGBLOCKS:
1. The E-R model can be carried out with the help of pictorial representation of entities, attributes
and relationships.
2. The basic building blocks of Entity Relationship diagram are Entity, Attribute andRelationship.
3. The following are the representations.
Entity set:
Entity Set is a collection or a group of ‘entities’ sharing exactly the ‘same set ofattributes’. All
entities can be distinctly identified in an entity set. This is because all the entities have a different set of
value for some set of attributes.
3. Recursive Entity Types: Self When there is a relationship between two entitiesof the same type, it is
known as a recursive relationship.
An employee can supervise multiple employees. Hence, this is a recursive relationship of entity employee
with itself. This is a 1 to many recursive relationship as one employee supervises many employees.
5. Super and subtype entity: A super type is a generic entity. It contain a relationship with
one or more subtypes.
Supertypeentity
1. Simple attributes
2. Composite attributes
3. Single valued attributes
4. Multi valued attributes
5. Derived attributes
6. Key attributes
1. Simple Attributes-
Simple attributes are those attributes which can not be divided further.
Example-
Here, all the attributes are simple attributes as they can not be divided further.
2. Composite Attributes-
Composite attributes are those attributes which are composed of many other simpleattributes.
Example-
Here, the attributes “Name” and “Address” are composite attributes as they arecomposed of many other
simple attributes.
3. Single Valued Attributes-
Single valued attributes are those attributes which can take only one value for a given entity from an entity
set.
Example-
Here, all the attributes are single valued attributes as they can take only one specificvalue for each entity.
4. Multi Valued Attributes-
Multi valued attributes are those attributes which can take more than one value for agiven entity from an
entity set.
Example-Here, the attributes “Mob_no” and “Email_id” are multi valued attributes as they cantake more
than one values for a given entity.
5. Derived Attributes-
Derived attributes are those attributes which can be derived from other attribute(s).
Example-age
6. Key Attributes-
Key attributes are those attributes which can identify an entity uniquely in an entity set.
Example-
Here, the attribute “Roll_no” is a key attribute as it can identify any studentuniquely.
ONE-TO-ONE RELATIONSHIP:
Only one entity of the first set is related to only one entity of the second set, such arelationship is
called one-to-one relationship.
For example a teacher teaches student. Only one teacher is teaching to only one student.
ONE-TO-MANY RELATIONSHIP:
Only one entity of the first set is related to multiple entities of the second set, sucharelationship is
called one-to-many relationship.
For example a teacher teaches students. Only teacher is teaching multiple students.
MANY-TO-ONE RELATIONSHIP:
Multiple entities of the first set are related to only one entity in the second set, sucha relationship iscalled
many-to-one relationship.
For example teachers teach a student. Many teachers are teaching only to onestudent.
MANY-TO-MANY RELATIONSHIP:
Multiple entities of the first set are related to multiple entities of the second set, such a relationshipis called
many-to-many relationship.
For example teachers teach students. Many teachers teaching many students.
2. Binary : A binary relationship exists when two entities are associated in Relationship. For
example, We have two entity type ‘Customer’ and ‘Account’ where each ‘Customer’ has an ‘Account’
which stores the account details of the ‘Customer’.
3. Ternary: A ternary relationship exists when exactly three entity type participates. When such
a relationship is present we say that the degree is 3.
For example, We have three entity type ‘Employee’, ‘Department’ and ‘Location’. The relationship
between these entities are defined as an employee works in a department, an employee works at a particular
location.
Sub class and Super class relationship leads the concept of Inheritance.
The relationship between sub class and super class is denoted with symbol.
1. Super Class
Super class is an entity type that has a relationship with one or more subtypes.
An entity cannot exist in database merely by being member of any super class.
For example: Shape super class is having sub groups as Square, Circle, Triangle.
2. Sub Class
Sub class is a group of entities with unique attributes.
Sub class inherits properties and attributes from its super class.
For example: Square, Circle, Triangle are the sub class of Shape super class.
In the above example, Tiger, Lion, Elephant can all be generalized as Animals.
2. Specialization
Specialization is a process that defines a group entities which is divided into sub groups based on their
characteristic.
It is a top down approach, in which one higher entity can be broken down into two lower level entity.
It maximizes the difference between the members of an entity by identifying the unique characteristic or
attributes of each member. It defines one or more sub class for the super class and also forms the super
class/subclassrelationship.
For example
In the above example, Employee can be specialized as Developer or Tester, based onwhat role they play in
an Organization.
3. Category or Union
Category represents a single super class or sub class relationship with more than one super class.
It can be a total or partial participation.
For example Car booking, Car owner can be a person, a bank (holds a possession on a Car) or a company.
Category (sub class) → Owner is a subset of the union of the three super classes → Company, Bank, and
Person. A Category member must exist in at leastone of its super classes.
4. Aggregration and composition:
Aggregation is a process of relation between two entities is treated as a single entity. It is a special kind
ofrelationship. It may be represented as “IS-A”, ”HAS-A” relationship.
Composition is a special case of aggregation, it is a restricted aggregation. In generally, composition is
definedas an object contain other object for example, it isrepresented as
5. Inheritance: Inheritance is defined as a mechanism where the sub or child class inherits the
properties and characteristics of the super class or other derived classes.
Completeness constraints
Total: Each superclass (higher-level entity) must belong to subclasses (lower-level entity sets), e. g. a
student must be postgrad or undergrad. Torepresent completeness in the specialization/generalization
relationship.
Partial: Some super classes may not belong to subclasses (lower-level entitysets), e. g. some people at
UCT are neither student nor staff. The keyword “Optional” is used to represent a partial
specialization/generalization relationship.
We can show both disjoint and completeness constraints in the ER diagram. Following our examples, we
can combine disjoint and completeness constraints.
Some members of a university are both students and staff. Not all members of theuniversity are staff and
students.
Roll_no City
Rule-04: Translating Relationship Set into
i a Table-Example-
Tables
Keys
Set operators or integrity rules.
Table: A table is a two dimensional object . It stores the data in the form of rows andcolumns. Row is called
as tuple.
sno sname age address
Row orTuple
Column
Keys: The keys are very important component in relational data model. These are used to uniquely identify
the data. These are also used to establish relationship between the tables. for example they are:
Candidate key
Primary key
Secondary key
Super key
Foreign key
Surrogate key
Candidate key: It is used to identify any column it contain a single value. Every table may contain more
than onecandidate key. The best candidate key is selected as primary key.
Primary key: Every table must have a single primary key. In generally, it is the combination of unique and
notnull. The best candidate key is selected as primary key.
Secondary key: This key contain duplicate values. so, it is difficult to identify a particular data.
Super key: It indicates an additional key that allows to identify the particular value i. e. , uniquely identify
eachrow in the table.
Foreign key: It is also called as reference key. It is used to mapping between the fields. The fields may be
twotable or same table.
Surrogate key: It is also called as artificial key. It is used to uniquely identify the data from the table.
3. Write about the concept of Relational Integrity?
Integrity rules or relational integrity:
1. Relational database integrity rules are very important to good database design.
2. Many (but by no means all) RDBMSs enforce integrity rules automatically.
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.
1. Domain Integrity.
2. Entity Integrity.
3. Referential Integrity.
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.
Ex: student relation the domains are regdno, name.
2. Entity Integrity :
1. All primary key entries are unique, and no part of a primary key may be null.
2. Each row will have a unique identity, and foreign key values can properly reference primary key values.
3. A primary key is an attribute in a relation which is used to identify each row in a relation.
4. No. of components of a primary key value may be NULL.
5. This is called as entity integrity.
3. Referential Integrity :
1. A referential integrity is used to implement the foreign key.
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.
4. Explain Set Operations (OR)Relational algebra?
Relational algebra is a procedural query language. It gives a step by step process to obtain the result of the
query. It uses operators to perform queries.
Relational SET OPERATORS (Relational Algebra)
In Oracle database SQL supports 8 types of relational algebra and relational SET operators.
SET operators are used to combine information of similar types from one or more than one table.
Types of SET operators: -
1) UNION
2) INTERSECT
3) MINUS (difference)
4)DIVIDE
5) PRODUC T(Cartesian product)
6)PROJECT
7) SELECT
8) Join
2. INTERSECT : -∩
The INTERSECT operator returns the rows that are common between two sets of rows.
Apply INTERSECT operator on both tables.
Example: -select spec, fee from student intersect select spec, free from admission;
Output:
Spec Fee
BSC 12000
BCOM 10000
BCA 20000
3) MINUS/DIFFERANCE :
(-)
The MINUS operator returns the rows unique to first query.
It combines records from 2 queries and returns the first table records which were not placed in the 2nd table.
Apply MINUS operator on both tables.
example - 1: -select spec, fee from student minus select spec, free from admission;
Output: Spec Fee
BA 8000
2) DIVIDE : -This operator specifies table1 is DIVIDE by table2 to produce table3 whenever both table1 &
table2 using a common field. Table A DIVIDE Table B
Sname Avg Sname
Xyz 70 Xyz
abc 60 Pqr
pqr 50
xyz 50
Pqr 90
The output of a Table A divided by Table B is.
The only value associated with both ‘xyz’ & ‘pqr’ is 50 only
Output: -
Avg
50
3) PRODUCT (or) Cartesian Product : -
This operator returns all the possible pairs of records from the two tables. .
If table1 having 3 records and table2 having 3 records then the product of e tables will return 3 x 3 = 9
records.
Example: Select students. stdno, students. sname, subjects. spec, subjects. subjfrom students,
subjects;
STUDENTS PRODUCT SUBJECTS
Stdno Sname Spec Subj
1 Murthy BSC English
2 Sailu BSC Maths
3 Bharat BSC Computers
OUTPUT:
Stdno Sname Spec Subj
1 Murthy BSC English
1 Murthy BSC Maths
1 Murthy BSC Computers
2 Sailu BSC English
2 Sailu BSC Maths
4) PROJECT : -π
it returns the selected field from the database table. (it returns single or multiple
fields)
Example: select fee from student;
Student table PROJECT fee yields
Stdno Sname Fee Fee
1 Sailu 12000 12000
2 Mounika 10000 10000
3 Ramya 20000 20000
4 Indu 8000 8000
5) SELECT : -σ
The SELECT statement is used to query or retrieve data from a table in the database.
A query may retrieve information from specified columns or all columns in a table.
Display ALL fields Example : -
SQL\>SELECT * FROM STUDENT;
Display some specified fields Example : -
includes only those matching rows from the right hand relation.
Right outer join: αThe functionality of right outer join is used to display all rows in right hand relation and
includes only those matching rows from the left hand relation
Full outer join: The functionality of full outer join is used to display all rows in left hand relation and
display all Rows in right hand relation.
Advantages of Relational Algebra:
1. Easy to use
2. flexibility
3. security
4. Data independence
5. Data manipulation language
6. Relational algebra is a high level language.
Limitations of Relational Algebra:
1. The relational algebra cannot perform aggregates.
2. The relational algebra cannot modify the database.
3. The relational algebra cannot sort or print results in various formats.
4. The relational algebra cannot do arithematic.
5. The query cannot be perform using relational algebra.
5. Explain Relational Integrity?
1. Relational Integrity constraints are the set of rules and restrictions which are used to maintain the data
consistency and integrity of a Relation (Table).
2. A database is only as good as the information stored in it.
3. It prevent the entry of incorrect information (incorrect information is not allowed).
Following are the four main types of Relational Integrity Constraints in the Database Management
System:
1. Key Constraint
2. Referential Integrity constraint
3. Entity Integrity constraint
4. Domain constraint
Key Constraint
A key constraint is that constraint which uniquely identifies the tuple of a relation. A Relation should
haveatleast one key constraint.
Domain Constraint
Domain constraint is that constraint which defines the set of rules for an attribute of 'Relation'. It specifies
that thefield accepts only those values which exist in the defined domain.
Domain Constraints are the user-defined data types such as Date, String, Integer, Currency, character, etc.
Example:
1. ID → Name,
2. Name → DOB
Example:
Key={std, course}
{std, course}teacherafter decompose, the BCNF table is: super key eliminate the redundant data.
Super key
Here there is no transitive dependency . In this table super key is here. so this table is in BCNF
5. Fourth normal form (4NF)
o A relation will be in 4NF if it is in Boyce Codd normal form and has no multi-valued dependency.
o For a dependency A → B, if for a single value of A, multiple values of B exists, then
the relationwill be a multi-valued dependency.
Example
STUD
STU_ID COURSE HOBBY
21 Computer Dancing
21 Math Singing
34 Chemistry Dancing
74 Biology Cricket
59 Physics Hockey
The given STUDENT table is in 3NF, but the COURSE and HOBBY are two independent entity. Hence,
there is no relationship between COURSE and HOBBY.
In the STUDENT relation, a student with STU_ID, 21 contains two courses, Computer and Math and
two hobbies, Dancing and Singing. So there is a Multi-valued dependency on STU_ID, which leads to
unnecessary repetition of data.
So to make the above table into 4NF, we can decompose it into two tables:
STUDENT_COURSE
STU_ID COURSE
21 Computer
21 Math
34 Chemistry
74 Biology
59 Physics
STUDENT_HOBBY
STU_ID HOBBY
21 Dancing
21 Singing
34 Dancing
74 Cricket
59 Hockey
So to make the above table into 5NF, we can decompose it into three relations P1, P2 & P3
P1
SEMESTE SUBJECT
Semester 1 Computer
Semester 1 Math
Semester 1 Chemistry
Semester 2 Math
P2
SUBJECT LECTURER
Computer Anshika
Computer John
Math John
Math Akash
Chemistry Praveen
P3
SEMSTER LECTURER
Semester 1 Anshika
Semester 1 John
Semester 1 John
Semester 2 Akash
Semester 1 Praveen
UNIT-4:SQL
1)SQL (Structured Query Language) INTRODUCTION:
SQL (Structured Query Language) is a domain-specific language used for managing and manipulating
relational databases. It allows users to interact with databases to perform various tasks like querying data,
updating records, and managing database structures.
2)SQL, which stands for Structured Query Language, is a domain-specific language used for managing and
manipulating relational databases. It has a rich history that spans several decades. Here are some key
milestones in the history of SQL:
1. Early Database Management Systems (1960s):
In the 1960s, early database management systems (DBMS) were being developed. However, data
access was primarily done through low-level programming languages, making it cumbersome and
complex.
2. SEQUEL (Structured English Query Language) (1970s):
In the early 1970s, Donald D. Chamberlin and Raymond F. Boyce, working at IBM, developed
SEQUEL as a high-level language for managing data in IBM's System R. SEQUEL was later
renamed SQL due to trademark issues.
3. SQL Standardization (1986):
SQL was standardized for the first time in 1986 by the American National Standards Institute
(ANSI). This standard was later adopted by the International Organization for Standardization (ISO).
4. SQL-89 (SQL1):
In 1989, the first official SQL standard was published, known as SQL-89 or SQL1. It defined the
basic features of SQL and laid the foundation for future versions.
5. SQL-92 (SQL2):
SQL-92, released in 1992, brought significant improvements and added many new features,
including support for integrity constraints, triggers, and more advanced data types.
6. SQL-99 (SQL3):
The SQL-99 standard, also known as SQL3, was a major milestone in the evolution of SQL. It
introduced support for object-oriented features, recursive queries, and several other enhancements.
7. Database Vendors and SQL Implementations:
Over the years, various database vendors, such as Oracle, Microsoft, IBM, and PostgreSQL,
developed their own SQL implementations with proprietary extensions. This led to some
fragmentation in the SQL language.
8. SQL:2003 (SQL3):
SQL:2003 was a significant update to the standard, incorporating many features from commercial
database systems, and introduced the concept of "SQL/XML" for handling XML data.
9. Ongoing Development and Expansions:
Since SQL:2003, the SQL standard has continued to evolve with new versions being released. Each
version brings additional features, enhancements, and clarifications to the language.
10. NoSQL Databases:
In recent years, with the rise of NoSQL databases, which use non-relational data models, SQL faced
competition from alternative query languages specific to each NoSQL database system.
11. SQL:2016 and Beyond:
The SQL:2016 standard introduced JSON support and several other improvements. Subsequent
versions have likely been released (beyond my knowledge cutoff in September 2021), with further
advancements and adaptations to the changing database landscape.
SQL remains one of the most widely used and essential tools in the field of database management and
continues to evolve to meet the needs of modern data management systems.
3)Data Base Language Commands: It Provides Data Definition Language (DDL) and Data Manipulation
Language (DML). DDL supports the database schemas and DML specifies the database queries and updates.
DDL: It defines the skeleton of the schema of the database. A schema is a collection of files with association
between relevant pairs of files. A schema is assigned a name which represents the name of the database.
DDL commands are Create, alter and drop.
DML: It defines on data of the database. Retrieving data from the database such as inserting data, Update
the data i.e. modifying the data and deleting data from the data base.
TCL: TCL means Transaction Control Language. The commands used in TCL are Commit, Savepoint and
roll back.
DCL:Data control language is used to give and take back the previlisation rights to the users on our database
usage by using GRANT AND REVOKE commands
Alter: It is a DDL command used to alter the table. It is of 3 types alter..add, alter..drop, alter..modify.
Syntax:
Alter..Add: It is used to add constraints and also for adding additional columns to an existing table.
SQL> alter table <table name> add constraint <constraint name> constraint type(column name);
Syntax for adding additional columns to an existing table:
SQL> alter table <table_name> add (<coloumn_name> <type>);
Example:
Adding Sub1,Sub2, Sub3,Total, Average fields to stud08 table:
SQL> alter table stud08 add(sub1 number(3),sub2 number(3),sub3 number(3), Total number(3), Average
number(3));
Output: Table altered.
Alter..Modify: It is used to modify the data type or size of column of a table. We cannot add not null
constraint using alter..add. We can add not null constraint using alter..modify.
Syntax:
SQL> alter table <table name> modify <column_name > <datatype> <size>;
Example:
Modifying Not Null Constraint to Stud08:
SQL> alter table stud08 modify(name varchar2(15) not null);
Output: Table altered.
Alter..Drop: It is used to drop the constraint OR column from table.
Syntax:
SQL> alter table <table_name> drop constraint;
Example:
Dropping column from stud08:
SQL> alter table stud08 drop column dob;
Output: Table altered.
Dropping Not null Constraint from stud08:
SQL> alter table stud08 drop constraint name_nn;
Output: Table altered.
Truncate: This Command is used to delete all the rows from a table. This first drops the table and then
recreates the table.
Syntax:
SQL> truncate table table_name;
Example:
SQL> truncate table stud08;
Output: Table truncated.
After using truncate command st08 table:
SQL> select * from st08;
Output: no rows selected
Drop: This command is used to drop or delete the table.
Syntax: SQL> drop table table_name;
Example:
SQL> drop table st08;
Output: Table dropped.
DML COMMANDS
Inserting values into stud08 table:
TCL COMMANDS:
Transaction language commands are savepoint, rollback and commit. By using these commands ,we can
control the transactions and it’s results by saving all the details temporarily and can also go for perminant
save or undo operations, if needed.
Savepoint: Is used to create asavepoint and store the transaction details temporarily
Syntax:
savepoint <savepoint name>;
example:
savepoint incsal;
savepoint created successfully.
Update emp set sal=sal+sal*10/100;
Select * from emp;
Table will display with updated salary to all employees
Rollback:It is used to erase the content from temporary storage space
Syntax:
rollback to savepoint name;
Example:
rollback to incsal;
commit: It is used to save the transaction results permanently in the disk.
Synatax: commit;
o/p:commit completed
4)WRITE A SHORT NOTE ON DATATYPES OF SQL
In SQL (Structured Query Language), data types define the type of data that can be stored in a database
table's columns. Each column in a table is assigned a specific data type, which determines the kind of data it
can hold. SQL supports a wide range of data types, allowing for flexibility in storing and manipulating
different types of data. Here are some commonly used SQL data types:
1. Numeric Data Types:
INTEGER/NUMBER: Used to store whole numbers (e.g., 1, 100, -15).
DECIMAL/NUMERIC: Used to store fixed-point numbers with specified precision and scale (e.g.,
3.14, -123.456).
FLOAT/REAL: Used to store floating-point numbers with approximate precision.
2. Character Data Types:
CHAR: Fixed-length character strings (e.g., 'Hello', 'SQL').
VARCHAR: Variable-length character strings with a maximum length (e.g., 'OpenAI', 'Data').
TEXT: Used for large blocks of text data (e.g., paragraphs, documents).
3. Date and Time Data Types:
DATE: Used to store dates (e.g., '2023-07-26').
TIME: Used to store time of day (e.g., '14:30:00').
TIMESTAMP/DATETIME: Stores both date and time information (e.g., '2023-07-26 14:30:00').
4. Boolean Data Type:
BOOLEAN/BOOL: Represents true or false values.
Database systems may have additional vendor-specific data types or extensions beyond the standard SQL
data types. It's essential to refer to the documentation of the specific database system you are using to
understand the full range of data types available and their characteristics. Choosing the appropriate data
types for your database columns is crucial for efficient storage and retrieval of data and maintaining data
integrity.
2. NON-EQUI JOIN
A join which contains an operator other than equal to ‘=’ in the joins condition.
Ex:SQL> select empno,ename,job,dname,loc from emp e,dept d where e.deptno > d.deptno;
EMPNO ENAME JOB DNAME LOC
222 sudha clerk INVENTORY HYBD
444 madhu engineer INVENTORY HYBD
444 madhu engineer FINANCE BGLR
444 madhu engineer HR MUMBAI
3. SELF JOIN
Joining the table itself is called self join.
Ex: SQL> select e1.empno,e2.ename,e1.job,e2.deptno from emp e1,emp e2 where e1.empno=e2.mgr;
EMPNO ENAME JOB DEPTNO
111 jagan analyst 10
222 madhu clerk 40
333 sudha manager 20
444 saketh engineer 10
4. NATURAL JOIN
Natural join compares all the common columns.
Ex:SQL> select empno,ename,job,dname,loc from emp natural join dept;
EMPNO ENAME JOB DNAME LOC
111 saketh analyst INVENTORY HYBD
333 jagan manager INVENTORY HYBD
222 sudha clerk FINANCE BGLR
5. CROSS JOIN
This will gives the cross product.
Ex:SQL> select empno,ename,job,dname,loc from emp cross join dept;
EMPNO ENAME JOB DNAME LOC
111 saketh analyst INVENTORY HYBD
222 sudha clerk INVENTORY HYBD
333 jagan manager INVENTORY HYBD
444 madhu engineer INVENTORY HYBD
111 saketh analyst FINANCE BGLR
222 sudha clerk FINANCE BGLR
333 jagan manager FINANCE BGLR
444 madhu engineer FINANCE BGLR
111 saketh analyst HR MUMBAI
222 sudha clerk HR MUMBAI
333 jagan manager HR MUMBAI
444 madhu engineer HR MUMBAI
6. OUTER JOIN
Outer join gives the non-matching records along with matching records.
LEFT OUTER JOIN
This will display the all matching records and the records which are in left hand side table those that are not
in right hand side table.
Ex:SQL> select empno,ename,job,dname,loc from emp e left outer join dept d
on(e.deptno=d.deptno); Or
SQL> select empno,ename,job,dname,loc from emp e,dept d where
e.deptno=d.deptno(+);
EMPNO ENAME JOB DNAME LOC
111 saketh analyst INVENTORY HYBD
333 jagan manager INVENTORY HYBD
222 sudha clerk FINANCE BGLR
444 madhu engineer
Example of a Subquery: Suppose we want to retrieve the names of employees who work in the "Marketing"
department. We can use a subquery to achieve this:
SELECT first_name, last_name, salary
FROM employees
WHERE department = 'IT'
AND salary > (SELECT AVG(salary) FROM salaries);
In this examples:
1)select ename from emp where sal=(select
select max(sal) from emp
emp);
2) select name from employees where departmentid = (select
select departmentid from departments where
departmentname = 'marketing')
1. The inner subquery (SELECT DepartmentID FROM Departments WHERE DepartmentName =
'Marketing') retrieves the DepartmentID for the department with the name 'Marketing' from the
"Departments" table.
2. The outer query SELECT Name FROM Employees WHERE DepartmentID = ... filters the rows from
the "Employees" table, matching the DepartmentID obtained from the subquery, and returns the names of
employees who work in the Marketing department.
The subquery is executed first, and its result is used in the outer query to determine which employees' names
to retrieve. Subqueries can be used in various parts of SQL statements, such as the SELECT, FROM,
WHERE, HAVING, and JOIN clauses, depending on the specific requirement.Subqueries allow for a more
modular and organized approach to querying the database, making SQL queries more flexible and powerful.
However, it's essential to use subqueries judiciously and consider their potential impact on performance, as
they can add complexity and overhead to the query execution.
UNIT-5:PL/SQL
INTRODUCTION TO PL/SQL& STRUCTURE OF PL/SQL PROGRAM
PL/SQL (Procedural Language/Structured Query Language) is an extension of SQL used in Oracle Database
systems. It is a powerful and versatile programming language designed to enhance SQL's capabilities by
allowing procedural constructs, such as loops, conditions, and exception handling, to be incorporated
directly into the database environment.
Introduction: It is a development tool that not only supports SQL data manipulation but also provides
facilities of conditional checking, branching and looping. It sends an entire block of SQL statements to the
oracle engine all in one go. It also permits dealings with errors as required and facilitates displaying user-
friendly messages when errors are encountered.
Structure of PL/SQL:
SQL> Declare
Declarations;
Begin
Executable statements;
[Exception
Exception handler;]
End;
Addition is:30
Subtraction is:10
Multiplication is:200
Division is:2
PL/SQL procedure successfully completed.
SHORT NOTE ON DATA TYPES OF PL/SQL
PL/SQL (Procedural Language/Structured Query Language) is an extension of SQL used in Oracle Database
to write procedural code. It supports various data types to store different types of data. Here's a short note on
the data types in PL/SQL:
1. Scalar Data Types:
NUMBER: Used for numeric data, including integers and decimals.
VARCHAR2/CHAR: Used for character strings. VARCHAR2 is variable-length, while CHAR is
fixed-length.
DATE: Used for date and time values.
BOOLEAN: Used for Boolean values (TRUE, FALSE, or NULL).
2. Composite Data Types:
RECORD: Used to hold a related set of variables of different data types, like a structure in other
programming languages.
TABLE: Used to store collections of data. PL/SQL supports nested tables, associative arrays (index-
by tables), and variable-sized arrays.
3. Reference Data Types:
REF CURSOR: Used to reference a cursor variable, enabling dynamic SQL and query result
retrieval.
%TYPE and %ROWTYPE: These are not actual data types but rather placeholders used to define
variables based on the data type of a column or an entire row in a table, respectively.
4. LOB Data Types:
CLOB: Used for large character objects, storing character data up to 4GB.
BLOB: Used for large binary objects, such as images or binary data, up to 4GB.
NCLOB: Used for large character objects with a national character set, up to 4GB.
BFILE: Used to store binary data in operating system files, linked to the database.
Control Structures:The follow of control statements can be classified into the following categories.
1. Conditional control
2. Iterative control
3. Jump statements
1. Conditional control
Conditional control, which run different statements for different data values.
if statement
i. If then statement
ii. If then else statement
iii. If then else if statement
iv. Nested if statement
1. If then 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;/
2. if then else statement
If condition is true it can execute statement 1.
If the condition is false it execute else statement or execute statement 2.
Syntax:
if(condition) then
statement1;
else statement2;
end if; Example:
declare
a number:=&a;
b number:=&b;
begin
if(a>b) then dbms_output.put_line(‘a is
big’);else
dbms_output.put_line(‘b is big’);end if;
end;
3. if then else if statement:
If condition is true it can execute statement 1.
If the condition is false its again check for another condition if it is true it can execute statement 2.
Other execute else statement or execute statement 3.
Syntax:
if(condition) then
statement1;
else if(condition) then
statement2;
else statement3;
end if;
Example:
declare
a number:=&a;b
number:=&b;
c number:=&c;
begin
if(a>b and a>c)
then
dbms_output.put_li
ne(‘a is big’);else
if(b>c) then
dbms_output.put_li
ne(‘b is big’);
else
dbms_output.put_li
ne(‘c is big’);
end if;
end;
4.Nested if statement:
Continue statement:
The CONTINUE statement causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating.
Syntax:Continue; example:
When the above code is executed at the SQL prompt, it produces the following result −
declare
a number(2) :=
10; begin
-- while loop execution
while a < 20 loop
dbms_output.put_line ('value of a: ' ||
a);a := a + 1;
if a = 15 then
-- skip the loop using the continue statement
a := a + 1;
continue
;end if;
end
loop;end;
/
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
begin
c :=a+b;
return( c );
end;
/
Output:
Enter a value:5
Enter b value:2
C:=7
Event Triggers
Timing Triggers