DBMS-Question and Answer Bank - SOCET-CE-Department - 211127 - 223259
DBMS-Question and Answer Bank - SOCET-CE-Department - 211127 - 223259
SR.NO and
Questions
ANSWERS Unit
No.
1
Compare Basis File System DBMS
Traditional
File File system is a software
processing that manages and
system and organizes the files in a DBMS is a software
database storage medium within a for managing the
management 1. Structure computer. database.
system.
2. Data Redundant data can be In DBMS there is no
Redundancy present in a file system. redundant data.
It has more
complexity in
handling as
It is less complex as compared to file
6. Complexity compared to DBMS. system.
This architecture has three levels:
1. External level
2. Conceptual level
3. Internal level
1. External level
It is also called view level. The reason this level is called “view” is because several users can view
their desired data from this level which is internally fetched from database with the help of
conceptual and internal level mapping.
The user doesn’t need to know the database schema details such as data structure, table definition
etc. user is only concerned about data which is what returned back to the view level after it has been
fetched from database (present at the internal level).
External level is the “top level” of the Three Level DBMS Architecture.
2. Conceptual level
It is also called logical level. The whole design of the database such as relationship among data,
schema of data etc. are described in this level.
2.
Draw and Database constraints and security are also implemented in this level of architecture. This level is
explain maintained by DBA (database administrator).
1
three level
architecture 3. Internal level
of DBMS This level is also known as physical level. This level describes how the data is actually stored in the
storage devices. This level is also responsible for allocating space to the data. This is the lowest
level of the architecture.
A Database Administrator (DBA) is individual or person
responsible for controlling, maintenance, coordinating, and operation
of database management system. Managing, securing, and taking
care of database system is prime responsibility.
They are responsible and in charge for authorizing access to
database, coordinating, capacity, planning, installation, and
monitoring uses and for acquiring and gathering software and
hardware resources as and when needed. Their role also varies from
configuration, database design, migration, security, troubleshooting,
backup, and data recovery. Database administration is major and
key function in any firm or organization that is relying on one or more
databases. They are overall commander of Database system.
Role and Duties of Database Administrator (DBA) :
• Decides hardware –
They decides economical hardware, based upon cost,
performance and efficiency of hardware, and best suits
organisation. It is hardware which is interface between end
users and database.
• Manages data integrity and security –
3 Data integrity need to be checked and managed accurately
Who is DBA? as it protects and restricts data from unauthorized use. DBA
Discuss the eyes on relationship within data to maintain data integrity.
role of • Database design – 1
Database DBA is held responsible and accountable for logical,
Administrator physical design, external model design, and integrity and
(DBA) security control.
• Database implementation –
DBA implements DBMS and checks database loading at
time of its implementation.
• Query processing performance –
DBA enhances query processing by improving their speed,
performance and accuracy.
• Tuning Database Performance –
If user is not able to get data speedily and accurately then it
may loss organization business. So by tuning SQL
commands DBA can enhance performance of database.
There are mainly 3 levels of data abstraction:
Physical: This is the lowest level of data abstraction. It tells us how
the data is actually stored in memory. The access methods like
sequential or random access and file organization methods like B+
trees, hashing used for the same. Usability, size of memory, and the
number of times the records are factors that we need to know while
designing the database.
Suppose we need to store the details of an employee. Blocks of
storage and the amount of memory used for these purposes are kept
hidden from the user.
Logical: This level comprises the information that is actually stored
in the database in the form of tables. It also stores the relationship
among the data entities in relatively simple structures. At this level,
the information available to the user at the view level is unknown.
We can store the various attributes of an employee and
relationships, e.g. with the manager can also be stored.
o All the command of DDL are auto-committed that means it permanently save all the changes in the
database.
o CREATE
o ALTER
o DROP
o TRUNCATE
1. Syntax:
examples:
b. DROP: It is used to delete both the structure and record stored in the table.
DDL, DML,
and DCL
Syntax
Example
c. ALTER: It is used to alter the structure of the database. This change could
be either to modify the characteristics of an existing attribute or probably to
add a new attribute.
Syntax:
Syntax:
Example:
o INSERT
o UPDATE
o DELETE
a. INSERT: The INSERT statement is a SQL query. It is used to insert data into the
row of a table.
Syntax:
Or
For example:
For example:
1. UPDATE students
2. SET User_Name = 'Sonoo'
3. WHERE Student_Id = '3'
Syntax:
For example:
o Grant
o Revoke
Example
Example
One-to-one
As its name implies, it maps one entity of the first entity set with another one
in the second one entity set. In the below image this has depicted that one
entity from entity set A is associated with at most one entity of other one
entity set B.
6.
List various
mapping If a single instance of an entity is connected with one instances of another 2
cardinalities entity, then it is called a relationship between one and many.
of
One-to-many
E-R Diagram
An entity from set A can be aligned with more than one entity from set B,
but an entity from set B can be associated with a limit of one entity.
For example - a customer may place many orders, but many customers do not place
an order.
Many-to-one
More than one entity from set A could be paired with a maximum of one entity from
set B, but more than one entity from set B can be paired with a maximum of one
entity from set A.
If more than one instance of the first entity is connected with more than one
instance of the second entity, it is called a many to many relationships.
An Entity Relationship (ER) Diagram is a type of flowchart that illustrates how
“entities” such as people, objects or concepts relate to each other within a system
Generalization
It's more like Superclass and Subclass system, but the only
7. difference is the approach, which is bottom-up. Hence, entities
Define E-R are combined to form a more generalised entity, in other words,
diagram.
Discuss sub-classes are combined to form a super-class.
generalization,
specialization,
With E-R
diagram
Specialization
2. Management complexity:
• Database systems interface with many different technologies and have a significant impact
on a company’s resources and culture.
• The changes introduced by the adoption of a database system must be properly managed
to ensure that they help advance the company’s objectives. Given the fact that database
systems hold crucial company data that are accessed from multiple sources, security
issues must be assessed constantly.
3. Maintaining currency:
• To maximize the efficiency of the database system, you must keep your system current.
• Therefore, you must perform frequent updates and apply the latest patches and security
measures to all components.
• Because database technology advances rapidly, personnel training costs tend to be
significant. Vendor dependence.
• Given the heavy investment in technology and personnel training, companies might be
reluctant to change database vendors.
1
A table can have more than one primary key. Primary key can be defined at
the column or the table level. If you create a composite primary key, it
should be defined at the table level.
Foreign Key
Foreign key is a column that creates a relationship between two tables.
The purpose of the Foreign key is to maintain data integrity and allow
10.
Define navigation between two different instances of an entity. It acts as a cross-
Primary Key, reference between two tables as it references the primary key of another
Foreign Key, table. Every relationship in the database should be supported by a foreign
NOT NULL
constraints key.
and referential 2
NOT NULL Constraint in SQL
constraints
By default, the columns are able to hold NULL values. A NOT NULL constraint in SQL is
used to prevent inserting NULL values into the specified column, considering it as a not
accepted value for that column. This means that you should provide a valid SQL NOT NULL
value to that column in the INSERT or UPDATE statements, as the column will always
contain data.
Referential Constraints
A table can have more than one primary key. Primary key can be defined
at the column or the table level. If you create a composite primary key, it
12.
Define the
should be defined at the table level.
terms
(i) Primary
key
Foreign Key
(ii) Second
ary key Foreign key is a column that creates a relationship between two tables.
(iii) Foreign The purpose of the Foreign key is to maintain data integrity and allow
key
navigation between two different instances of an entity. It acts as a
cross-reference between two tables as it references the primary key of
another table. Every relationship in the database should be supported by
a foreign key.
2
Secondary Key
Secondary Key is the key that has not been selected to be the primary key.
However, it is considered a candidate key for the primary key.
Therefore, a candidate key not selected as a primary key is called secondary
key. Candidate key is an attribute or set of attributes that you can consider as
a Primary key.
Network model
This is an extension of the hierarchical model, allowing many-to-many
13
Explain relationships in a tree-like structure that allows multiple parents
network
model and
Object
Oriented
model in brief
Object-Oriented Model
• This data model is another method of representing real
world objects.
• It considers in the world as objects and isolates it from
2
each other
• It groups its related functionalities together and allows
inheriting its functionalities to other related sub-groups.
14.
List the relational algebra operators. Discuss any one such algebra operator
with suitable example
• Relational algebra is a language for expressing relational database
queries.
• Relational algebra is a procedural query language.
• Relational algebraic operators are as follows:
1. Selection
2. Projection
3. Division
4. Cartesian product
5. Rename
6. Set difference
7. Join and its types
❖ Selection:-
• Operation: selects tuples from a relation that satisfy a
given condition. It is used to select particular tuples from a
relation. It selects particular tuples but all attributes from a
relation
• Symbol : sigma
• Notation: sigmacondition<relation>
• Operators : the following operators can be used in a
condition.
=,!=,<,>,<=,>=,^(AND), V(OR)
• Consider the following table
RNO NAME DEPT CPI
101 DHWIJA CC 10
102 HARSH CS 10
103 JAYRAJ CS 10
104 HETVI MLAI 10
105 SHIVAM CS 10
106 BHAVESH CC 10
107 MEENAKSHI B.SC 10
Inner Joins
The INNER JOIN keyword selects all rows from the tables as long as
a join condition satisfies. This keyword will create a result-set made
up of combined rows from both tables where a common field exists.
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
Right outer Joins
This join statement takes all the records from Table B whether or not
they have NULL values and the matching columns from Table A.
Right join returns all the rows of the rightmost table of and the
matching rows for the leftmost table. RIGHT JOIN is also known as
RIGHT OUTER. Here is the syntax:
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
Left join is similar to right join. Left join returns all the rows of the
leftmost table and the matching rows for the rightmost table. Below is
the syntax:
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
Full Joins
Full joins are also known as full outer joins. This basically means that a
query would combine data and return records from both tables no
matter if they had NULL values.
FULL JOIN creates a result-set by combining the results of the left and
right joins, including all the rows. For the rows that do not match. the
result-set (joined table) will shows NULL values. The syntax is as
follows:
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;
20. LIST THE STEPS FOR CONVERT E-R DIAGRAM INTO
TABLE
o Entity type becomes a table.
In the STUDENT table, Age is the derived attribute. It can be calculated at any point
of time by calculating the difference between current date and Date of Birth.
21. • Functional Dependency is when one attribute determines another
WHAT IS attribute in a DBMS system.
• Axiom, Decomposition, Dependent, Determinant, Union are key terms
FUNCTIONAL
for functional dependency
DEPENDENCY? • Four types of functional dependency are 1) Multivalued 2) Trivial 3)
EXPLAIN ITS Non-trivial 4) Transitive
TYPES IN DETAIL
Types of Functional Dependencies in DBMS
There are mainly four types of Functional Dependency in DBMS. Following
are the types of Functional Dependencies in DBMS:
• Multivalued Dependency
• Trivial Functional Dependency
• Non-Trivial Functional Dependency
• Transitive Dependency
22.
Primary key:
GIVE A BRIEF
ABOUT • A primary key is a special relational database table column (or combination
of columns) designated to uniquely identify all table records.
PRIMARY KEY
• A primary key’s main features are:
AND FOREIGN o It must contain a unique value for each row of data.
KEY o It cannot contain null values.
• A primary key is either an existing table column or a column that is
specifically generated by the database according to a defined sequence.
• For example, students are routinely assigned unique identification (ID)
numbers, and all adults receive government-assigned and uniquely-
identifiable Social Security numbers.
Foreign Key:
• A foreign key is a field (or collection of fields) in one table that uniquely
identifies a row of another table. In simpler words, the foreign key is
defined in a second table, but it refers to the primary key in the first table.
• For example, a table called Employee has a primary key called
employee_id. Another table called Employee Details has a foreign key
which references employee_id in order to uniquely identify the relationship
between both the tables.
• A foreign key is a column or group of columns in a relational database table
that provides a link between data in two tables. It acts as a cross-reference
between tables because it references the primary key of another table,
thereby establishing a link between them.
23.
EXPLAIN THE
CLOUSRE OF
FOLLOWING SET
F OF
FUNCTIONAL
DEPENDENCY
FOR RELATION
SCHEMA
R(A,B,C,D,E).
A->BC,
CD->E,
B->D,
E->A
LIST THE
CANDIDATE S
KEYS FOR R
First Normal Form (1NF):
If a relation contains a composite or multi-valued attribute, it violates
the first normal form, or the relation is in first normal form if it does
not contain any composite or multi-valued attribute. A relation is
in first normal form if every attribute in that relation is singled valued
attribute.
A table is in 1 NF iff:
1. There are only Single Valued Attributes.
2. Attribute Domain does not change.
3. There is a unique name for every Attribute/Column.
4. The order in which data is stored does not matter.
ID Name Course
------------------
1 A c1
1 A c2
2 E c3
3 M c2
3 M c3
In the above relation, AB is the only candidate key and there is no partial dependency, i.e.,
any proper subset of AB doesn’t determine any non-prime attribute.
To move our 2NF table into 3NF, we again need to again divide our
table.
s
26. Explain armstrong’s axioms
• Armstrong's Axioms is a set of rules.
• It provides a simple technique for reasoning about functional
dependencies.
• It was developed by William W. Armstrong in 1974.
• It is used to infer all the functional dependencies on a relational
database.
Rule 1 Reflexivity
If A is a set of attributes and B is a subset of A, then A holds B. { A → B }
Rule 2 Augmentation
If A hold B and C is a set of attributes, then AC holds BC. {AC → BC}
It means that attribute in dependencies does not change the basic dependencies.
Rule 3 Transitivity
If A holds B and B holds C, then A holds C.
If {A → B} and {B → C}, then {A → C}
A holds B {A → B} means that A functionally determines B.
B. Secondary Rules
Rule 1 Union
If A holds B and A holds C, then A holds BC.
If{A → B} and {A → C}, then {A → BC}
Rule 2 Decomposition
If A holds BC and A holds B, then A holds C.
If{A → BC} and {A → B}, then {A → C}
A set of functional dependencies with the above three properties are also
called as Canonical or Minimal.
• Translate the query into its internal form. This is then translated into relational algebra.
• Parser checks syntax, verifies relation.
2. Optimization
3. Evaluation
• The query evaluation engine takes a query evaluation plan, executes that plan and returns the answer to that
29. WHAT IS A VIEW? EXPLAIN HOW TO CREATE, ITS TYPES AND SIGNIFICANC
DBMS
ANS: Views in SQL
o Views in SQL are considered as a virtual table. A view also contains rows and columns.
o To create the view, we can select the fields from one or more tables present in the database.
o A view can either have specific rows based on certain condition or all the rows of a table.
Sample table:
Student_Detail
1 Stephan Delhi
2 Kathrin Noida
3 David Ghaziabad
4 Alina Gurugram
Student_Marks
2 Kathrin 86 21
3 David 74 18
4 Alina 90 20
5 John 96 18
1. Creating view
A view can be created using the CREATE VIEW statement. We can create a view from a single table or multiple
Syntax:
Query:
Just like table query, we can query the view to view the data.
Output:
NAME ADDRESS
Stephan Delhi
Kathrin Noida
David Ghaziabad
In the given example, a view is created named MarksView from two tables Student_Detail and Student_Marks.
Query:
Stephan Delhi 97
Kathrin Noida 86
David Ghaziabad 74
Alina Gurugram 90
4. Deleting View
A view can be deleted using the Drop View statement.
Syntax
Example:
Properties of B-tree
B-tree satisfies the following properties −
• The number of keys in a node (non leaf node) is one less than the number of its children (and these key
the keys of children like a binary search tree).
• The root has a minimum one key to maximum (m-1) keys. So, root has minimum two children to m
children.
• Any node (non-leaf node) except the root has minm([m/2]-1) to maxm(m-1) keys. So, they have minm [ m/2
to maxm m children.
Example
A B-tree of order 3 (i.e a node can have maxm 3 children) satisfy following properties −
• The root has minimum one key to maximum 2 keys. So root has minimum two children to maximum 3 c
• Any node (non-leaf node) except the root has minm 1 to maxm 2 keys. So, they have minm 2 children
children.
Hashing
In a huge database structure, it is very inefficient to search all the index values and reach the desired data
technique is used to calculate the direct location of a data record on the disk without using index structure.
In this technique, data is stored at the data blocks whose address is generated by using the hashing function. Th
location where these records are stored is known as data bucket or data blocks.
In this, a hash function can choose any of the column value to generate the address. Most of the time, the has
uses the primary key to generate the address of the data block. A hash function is a simple mathematical funct
complex mathematical function. We can even consider the primary key itself as the address of the data block. T
each row whose address will be the same as a primary key stored in the data block.
The above diagram shows data block addresses same as primary key value. This hash function can also b
mathematical function like exponential, mod, cos, sin, etc. Suppose we have mod (5) hash function to dete
address of the data block. In this case, it applies mod (5) hash function on the primary keys and generates 3, 3,
respectively, and records are stored in those data block addresses.
31. EXPLAIN INDICES WITH EXAMPLE
ANS: Indexing is a data structure technique to efficiently retrieve records from the database files based
attributes on which the indexing has been done. Indexing in database systems is similar to what we see in bo
Indexing is defined based on its indexing attributes. Indexing can be of the following types −
• Primary Index − Primary index is defined on an ordered data file. The data file is ordered on a key field
field is generally the primary key of the relation.
• Secondary Index − Secondary index may be generated from a field which is a candidate key and has
value in every record, or a non-key with duplicate values.
• Clustering Index − Clustering index is defined on an ordered data file. The data file is ordered on a non
Ordered Indexing is of two types −
• Dense Index
• Sparse Index
Dense Index
In dense index, there is an index record for every search key value in the database. This makes searching
requires more space to store index records itself. Index records contain search key value and a pointer to
record on the disk.
Sparse Index
In sparse index, index records are not created for every search key. An index record here contains a search k
actual pointer to the data on the disk. To search a record, we first proceed by index record and reach at the actu
of the data. If the data we are looking for is not where we directly reach by following the index, then the sys
sequential search until the desired data is found.
Multilevel Index
Index records comprise search-key values and data pointers. Multilevel index is stored on the disk along with
database files. As the size of the database grows, so does the size of the indices. There is an immense nee
the index records in the main memory so as to speed up the search operations. If single-level index is used, th
size index cannot be kept in memory which leads to multiple disk accesses.
14.6M
293
History of Java
Next
Stay
Example: If Remo has account A having $30 in his account from which he wishes to send $10 to Sheero's acco
is B. In account B, a sum of $ 100 is already present. When $10 will be transferred to account B, the sum will bec
Now, there will be two operations that will take place. One is the amount of $10 that Remo wants to trans
debited from his account A, and the same amount will get credited to account B, i.e., into Sheero's account.
happens - the first operation of debit executes successfully, but the credit operation, however, fails. Thus,
account A, the value becomes $20, and to that of Sheero's account, it remains $100 as it was previously presen
In the above diagram, it can be seen that after crediting $10, the amount is still $100 in account B. So, it is not
transaction.
The below image shows that both debit and credit operations are done successfully. Thus the transaction is ato
Thus, when the amount loses atomicity, then in the bank systems, this becomes a huge issue, and so the atom
main focus in the bank systems.
2) Consistency: The word consistency means that the value should remain preserved always. In DBMS, the i
the data should be maintained, which means if a change in the database is made, it should remain preserved
the case of transactions, the integrity of the data is very essential so that the database remains consistent befor
the transaction. The data should always be correct.
Example:
In the above figure, there are three accounts, A, B, and C, where A is making a transaction T one by one to b
There are two operations that take place, i.e., Debit and Credit. Account A firstly debits $50 to account B, and th
in account A is read $300 by B before the transaction. After the successful transaction T, the available amount in B
$150. Now, A debits $20 to account C, and that time, the value read by C is $250 (that is correct as a debit of $5
successfully done to B). The debit and credit operation from account A to C has been done successfully. We ca
the transaction is done successfully, and the value is also read correctly. Thus, the data is consistent. In case the
by B and C is $300, which means that data is inconsistent because when the debit operation executes, it w
consistent.
4) Isolation: The term 'isolation' means separation. In DBMS, Isolation is the property of a database where no d
affect the other one and may occur concurrently. In short, the operation on one database should begin when the
on the first database gets complete. It means if two operations are being performed on two different databases
not affect the value of one another. In the case of transactions, when two or more transactions occur simultan
consistency should remain maintained. Any changes that occur in any particular transaction will not be seen
transactions until the change is not committed in the memory.
Example: If two operations are concurrently running on two different accounts, then the value of both accou
not get affected. The value should remain persistent. As you can see in the below diagram, account A is making
transactions to account B and C, but both are executing independently without affecting each other. It is
Isolation.
4) Durability: Durability ensures the permanency of something. In DBMS, the term durability ensures that the
the successful execution of the operation becomes permanent in the database. The durability of the data sho
perfect that even if the system fails or leads to a crash, the database still survives. However, if gets lost, it be
responsibility of the recovery manager for ensuring the durability of the database. For committing the values, th
command must be used every time we make changes.
Therefore, the ACID property of DBMS plays a vital role in maintaining the consistency and availability of d
database.
Active state
o The active state is the first state of every transaction. In this state, the transaction is being executed.
o For example: Insertion or deletion or updating a record is done here. But all the records are still not saved to the
Partially committed
o In the partially committed state, a transaction executes its final operation, but the data is still not saved to the da
o In the total mark calculation example, a final display of the total marks step is executed in this state.
Committed
A transaction is said to be in a committed state if it executes all its operations successfully. In this state, all the
now permanently saved on the database system.
Failed state
o If any of the checks made by the database recovery system fails, then the transaction is said to be in the failed sta
o In the example of total mark calculation, if the database is not able to fire a query to fetch the marks, then the tran
fail to execute.
Aborted
o If any of the checks fail and the transaction has reached a failed state then the database recovery system will ma
the database is in its previous consistent state. If not then it will abort or roll back the transaction to bring the da
a consistent state.
o If the transaction fails in the middle of the transaction then before executing the transaction, all the executed tran
rolled back to its consistent state.
o After aborting the transaction, the database recovery module will select one of the two operations:
1. Re-start the transaction
2. Kill the transaction
ANS: B+ Tree
o The B+ tree is a balanced binary search tree. It follows a multi-level index format.
o In the B+ tree, leaf nodes denote actual data pointers. B+ tree ensures that all leaf nodes remain at the same heig
o In the B+ tree, the leaf nodes are linked using a link list. Therefore, a B+ tree can support random access as well a
access.
Structure of B+ Tree
o In the B+ tree, every leaf node is at equal distance from the root node. The B+ tree is of the order n where n is fix
B+ tree.
o It contains an internal node and leaf node.
Internal node
o An internal node of the B+ tree can contain at least n/2 record pointers except the root node.
o At most, an internal node of the tree contains n pointers.
Leaf node
o The leaf node of the B+ tree can contain at least n/2 record pointers and n/2 key values.
o At most, a leaf node contains n record pointer and n key values.
o Every leaf node of the B+ tree contains one block pointer P to point to next leaf node.
So, in the intermediary node, we will find a branch between 50 and 75 nodes. Then at the end, we will be redirec
third leaf node. Here DBMS will perform a sequential search to find 55.
B+ Tree Insertion
Suppose we want to insert a record 60 in the below structure. It will go to the 3rd leaf node after 55. It is a bala
and a leaf node of this tree is already full, so we cannot insert 60 there.
In this case, we have to split the leaf node, so that it can be inserted into tree without affecting the fill factor, b
order.
Keep Watching
Competitive questions on Structures in Hindi
00:00/03:34
Keep Watching
Competitive questions on Structures in Hindi
00:00/03:34
Keep Watching
Competitive questions on Structures in Hindi
Keep Watching
Keep Watching
The 3rd leaf node has the values (50, 55, 60, 65, 70) and its current root node is 50. We will split the leaf node
in the middle so that its balance is not altered. So we can group (50, 55) and (60, 65, 70) into 2 leaf nodes.
If these two has to be leaf nodes, the intermediate node cannot branch from 50. It should have 60 added to it
we can have pointers to a new leaf node.
This is how we can insert an entry when there is overflow. In a normal scenario, it is very easy to find the node w
and then place it in that leaf node.
B+ Tree Deletion
Suppose we want to delete 60 from the above example. In this case, we have to remove 60 from the intermed
as well as from the 4th leaf node too. If we remove it from the intermediate node, then the tree will not satisfy
the B+ tree. So we need to modify it to have a balanced tree.
After deleting node 60 from above B+ tree and re-arranging the nodes, it will show as follows:
35. DEFINE HASHING AND ITS TYPES.
ANS: Hashing
In a huge database structure, it is very inefficient to search all the index values and reach the desired data
technique is used to calculate the direct location of a data record on the disk without using index structure.
In this technique, data is stored at the data blocks whose address is generated by using the hashing function. Th
location where these records are stored is known as data bucket or data blocks.
In this, a hash function can choose any of the column value to generate the address. Most of the time, the has
uses the primary key to generate the address of the data block. A hash function is a simple mathematical funct
complex mathematical function. We can even consider the primary key itself as the address of the data block. T
each row whose address will be the same as a primary key stored in the data block.
The above diagram shows data block addresses same as primary key value. This hash function can also b
mathematical function like exponential, mod, cos, sin, etc. Suppose we have mod (5) hash function to dete
address of the data block. In this case, it applies mod (5) hash function on the primary keys and generates 3, 3,
respectively, and records are stored in those data block addresses.
Skip Ad
Types of Hashing:
Static Hashing
In static hashing, the resultant data bucket address will always be the same. That means if we generate an a
EMP_ID =103 using the hash function mod (5) then it will always result in same bucket address 3. Here, there
change in the bucket address.
Hence in this static hashing, the number of data buckets in memory remains constant throughout. In this examp
have five data buckets in the memory used to store the data.
Dynamic Hashing
o The dynamic hashing method is used to overcome the problems of static hashing like bucket overflow.
o In this method, data buckets grow or shrink as the records increases or decreases. This method is also known as
hashing method.
o This method makes hashing dynamic, i.e., it allows insertion or deletion without resulting in poor performance.
ANS:
Difficult to achieve.
For a transaction T1 writing value A that no one else reads If a transaction T1 writes a value A that no other
but later some other transactions say T2 write it own value
of A, W(A) cannot be places under positions where it is Transaction reads W(A) can be placed in position
never read.
Of the schedule where it is never read.
Log-Based Recovery
o The log is a sequence of records. Log of each transaction is maintained in some stable storage so that if any fai
then it can be recovered from there.
o If any operation is performed on the database, then it will be recorded in the log.
o But the process of storing the logs should be done before the actual transaction is applied in the database.
Let's assume there is a transaction to modify the City of a student. The following logs are written for this transa
1. <Tn, Start>
o When the transaction modifies the City from 'Noida' to 'Bangalore', then another log is written to the file.
1. <Tn, Commit>
There are two approaches to modify the database:
1. If the log contains the record <Ti, Start> and <Ti, Commit> or <Ti, Commit>, then the Transaction Ti needs to be
2. If log contains record<Tn, Start> but does not contain the record either <Ti, commit> or <Ti, abort>, then the Tra
needs to be undone.
For example: Suppose there are two transactions T1 and T2 which have some operations. If it has no inter
operations, then there are the following two possible outcomes:
1. Execute all the operations of T1 which was followed by all the operations of T2.
2. Execute all the operations of T1 which was followed by all the operations of T2.
o In the given (a) figure, Schedule A shows the serial schedule where T1 followed by T2.
o In the given (b) figure, Schedule B shows the serial schedule where T2 followed by T1.
2. Non-serial Schedule
o If interleaving of operations is allowed, then there will be non-serial schedule.
o It contains many possible orders in which the system can execute the individual operations of the transa
o In the given figure (c) and (d), Schedule C and Schedule D are the non-serial schedules. It has inter
operations.
3. Serializable schedule
o The serializability of schedules is used to find non-serial schedules that allow the transaction to execute co
without interfering with one another.
o It identifies which schedules are correct when executions of the transaction have interleaving of their op
o A non-serial schedule will be serializable if its result is equal to the result of its transactions executed ser
Here,
ANS: When multiple transactions are running concurrently then there is a possibility that the data
be left in an inconsistent state. Serializability is a concept that helps us to check which sche
serializable. A serializable schedule is the one that always leaves the database in consistent state.
Conflicting operations
Two operations are said to be in conflict, if they satisfy all the following three conditions:
View Serializability is a process to find out that a given schedule is view serializable or not.
To check whether a given schedule is view serializable, we need to check whether the given schedule
Equivalent to its serial schedule. Lets take an example to understand what I mean by that.
Given Schedule:
T1 T2
----- ------
R(X)
W(X)
R(X)
W(X)
R(Y)
W(Y)
R(Y)
W(Y)
Serial Schedule of the above given schedule:
As we know that in Serial schedule a transaction only starts when the current running transaction is f
So the serial schedule of the above given schedule would look like this:
T1 T2
----- ------
R(X)
W(X)
R(Y)
W(Y)
R(X)
W(X)
R(Y)
W(Y)
If we can prove that the given schedule is View Equivalent to its serial schedule then the given schedu
called view Serializable.
For example: In the student table, transaction T1 holds a lock on some rows and needs to update some rows in
table. Simultaneously, transaction T2 holds locks on some rows in the grade table and needs to update the r
Student table held by Transaction T1.
Now, the main problem arises. Now Transaction T1 is waiting for T2 to release its lock and similarly, transa
waiting for T1 to release its lock. All activities come to a halt state and remain at a standstill. It will remain in
until the DBMS detects the deadlock and aborts one of the transactions.
Deadlock Avoidance
o When a database is stuck in a deadlock state, then it is better to avoid the database rather than aborting or re
database. This is a waste of time and resource.
o Deadlock avoidance mechanism is used to detect any deadlock situation in advance. A method like "wait for gra
for detecting the deadlock situation but this method is suitable only for the smaller database. For the large
deadlock prevention method can be used.
41. Explain the concurrency problem. How does the strict two phase
Example
Lock-based Protocols
Database systems equipped with lock-based protocols use a mechanism by which any transaction cannot rea
data until it acquires an appropriate lock on it. Locks are of two kinds −
• Binary Locks − A lock on a data item can be in two states; it is either locked or unlocked.
• Shared/exclusive − This type of locking mechanism differentiates the locks based on their uses. If
acquired on a data item to perform a write operation, it is an exclusive lock. Allowing more than one tr
to write on the same data item would lead the database into an inconsistent state. Read locks are shared
no data value is being changed.
There are four types of lock protocols available −
Simplistic Lock Protocol
Simplistic lock-based protocols allow transactions to obtain a lock on every object before a 'write' operation is p
Transactions may unlock the data item after completing the ‘write’ operation.
Pre-claiming Lock Protocol
Pre-claiming protocols evaluate their operations and create a list of data items on which they need locks. Befor
an execution, the transaction requests the system for all the locks it needs beforehand. If all the locks are gr
transaction executes and releases all the locks when all its operations are over. If all the locks are not gr
transaction rolls back and waits until all the locks are granted.
Two-Phase Locking 2PL
This locking protocol divides the execution phase of a transaction into three parts. In the first part, when the tr
starts executing, it seeks permission for the locks it requires. The second part is where the transaction acqui
locks. As soon as the transaction releases its first lock, the third phase starts. In this phase, the transacti
demand any new locks; it only releases the acquired locks.
Two-phase locking has two phases, one is growing, where all the locks are being acquired by the transactio
second phase is shrinking, where the locks held by the transaction are being released.
To claim an exclusive (write) lock, a transaction must first acquire a shared (read) lock and then upgrade it to an
lock.
Shared locks
Shared locks support read integrity. They ensure that a record is not in the process of being updated during a read
request. Shared locks can also be used to prevent updates of a record between the time that a record is read and th
syncpoint.
A shared lock on a resource can be owned by several tasks at the same time. However, although several tasks can o
shared locks, there are some circumstances in which tasks can be forced to wait for a lock:
• A request for a shared lock must wait if another task currently owns an exclusive lock on the resource.
• A request for an exclusive lock must wait if other tasks currently own shared locks on this resource.
• A new request for a shared lock must wait if another task is waiting for an exclusive lock on a resource that
has a shared lock.
43. What is locking? Explain Two phase locking and its types.
Ans:
A lock is a variable associated with a data item that describes the status of the item with respect to possible o
that can be applied to it. Generally, there is one lock for each data item in the database. Locks are used as a
synchronizing the access by concurrent transactions to the database item.
Exclusive locks
Exclusive locks protect updates to file resources, both recoverable and non-recoverable. They can be owned by on
transaction at a time. Any transaction that requires an exclusive lock must wait if another task currently owns an e
lock or a shared lock against the requested resource.
Shared locks
Shared locks support read integrity. They ensure that a record is not in the process of being updated during a read
request. Shared locks can also be used to prevent updates of a record between the time that a record is read and th
syncpoint.
A shared lock on a resource can be owned by several tasks at the same time. However, although several tasks can o
shared locks, there are some circumstances in which tasks can be forced to wait for a lock:
• A request for a shared lock must wait if another task currently owns an exclusive lock on the resource.
• A request for an exclusive lock must wait if other tasks currently own shared locks on this resource.
• A new request for a shared lock must wait if another task is waiting for an exclusive lock on a resource that
has a shared lock.
Ans: DAC is a type of access control in which the owner of a resource restricts access to the resource based o
identity of the users. MAC is a type of access control that restricts the access to the resources based on the cle
the subjects.
The DAC stands for Discretionary Access Control (DAC) and the MAC stands for Mandatory Access Control.
Basis
In DAC, the resource owner determines who can access and what privileges they have. MAC provides acc
users depending on the clearance level of the users. Access is determined by the system.
Flexibility
Furthermore, DAC is more flexible than MAC.
Security
Also, MAC is more secure than DAC.
Implementation
Moreover, DAC is easier to implement than MAC.
Conclusion
The main difference between DAC and MAC is that the DAC is an access control method in which the ow
resource determines the access while the MAC is an access control method that provides access to the
depending on the clearance level of the user. In brief, DAC is suitable
46. Write SQL statements (Query) for following tables: T1(roll_no, stuname,
Grant: specially used to provide privileges to database objects for a user. This command also allows
Users to grant permissions to other users too.
Revoke: revoke command withdraw user priviliges on database objects if any granted. It does
Operations opposite to the grant command. When a privilege is revoked from a particular user U,
A COMMIT is the SQL command used in the transaction tables or database to make the current tran
database statement as permanent. It shows the successful completion of a transaction. If we have successfully
the transaction statement or a simple database query, we want to make the changes permanent. We need t
the commit command to save the changes, and these changes become permanent for all users. Furthermore
commit command is executed in the database, we cannot regain its previous states in which it was earlier
execution of the first statement.
Syntax
1. COMMIT;
The SQL ROLLBACK command is used to roll back the current transaction state if any error occurred during the
of a transaction. In a transaction, the error can be a system failure, power outage, incorrect execution of the tr
system crash, etc. Generally, a rollback command performs the current transaction's rollback action to
transaction on its previous state or the first statement. A rollback command can only be executed if the us
performed the COMMIT command on the current transaction or statement.
Syntax
1. ROLLBACK;
AVG Function
This function returns the average value of the numeric column that is supplied as a parameter.
Example: Write a query to select average salary from employee table.
Select AVG(salary) from Employee
COUNT Function
The count function returns the number of rows in the result. It does not count the null values.
Example: Write a query to return number of rows where salary > 20000.
Select COUNT(*) from Employee where Salary > 20000;
Types −
• COUNT(*): Counts all the number of rows of the table including null.
MAX Function
The MAX function is used to find maximum value in the column that is supplied as a parameter. It can be us
type of data.
Example − Write a query to find the maximum salary in employee table.
Select MAX(salary) from Employee
SUM Function
This function sums up the values in the column supplied as a parameter.
Example: Write a query to get the total salary of employees.
Select SUM(salary) from Employee
STDDEV Function
The STDDEV function is used to find standard deviation of the column specified as argument.
Example − Write a query to find standard deviation of salary in Employee table.
Select STDDEV(salary) from Employee
VARIANCE Function
The VARIANCE Function is used to find variance of the column specified as argument.
Example −
Select VARIANCE(salary) from Employee
• Implicit cursors
• Explicit cursors
Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed, when there is
cursor for the statement. Programmers cannot control the implicit cursors and the information in it.
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is associated
statement. For INSERT operations, the cursor holds the data that needs to be inserted. For UPDATE and
operations, the cursor identifies the rows that would be affected.
In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which always has attrib
as %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT. The SQL cursor has
attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS, designed for use with the FORALL statemen
Explicit Cursors
Explicit cursors are programmer-defined cursors for gaining more control over the context area. An explicit cur
be defined in the declaration section of the PL/SQL Block. It is created on a SELECT Statement which returns
one row.
The syntax for creating an explicit cursor is −
CURSOR cursor_name IS select_statement;
Working with an explicit cursor includes the following steps −
Triggers are programs that are available in the memory, with unique names made up of SQL queri
we need to fire on our database on and off.
Triggers can be made to insert, update and delete statements in SQL
DML triggers are executed when a DML operation like INSERT, UPDATE OR DELETE is fired on a Table or View.
AFTER Triggers are executed after the DML statement completes but before it is committed to the datab
Triggers if required can rollback it’s actions and source DML statement which invoked it.
INSTEAD OF Triggers
INSTEAD OF Triggers are the triggers which gets executed automatically in place of triggering DML (i.e. INSER
and DELETE) action. It means if we are inserting a record and we have a INSTEAD OF trigger for INSERT then
INSERT whatever action is defined in the trigger that gets executed.
▪ Data Definition Language (DDL) Triggers
DDL Triggers are executed when a DDL Statements like CREATE, ALTER, DROP, GRANT, DENY, REVOKE, an
STATISTICS statements are executed. Certain system stored procedures that perform DDL like operations c
DDL triggers.
DDL triggers can be DATABASE scoped or SERVER scoped. The DDL triggers with Server level scope gets fired i
to a DDL statement with server scope like CREATE DATABASE, CREATE LOGIN, GRANT_SERVER, ALTER DATAB
LOGIN etc. Where as DATABASE scoped DDL triggers fire in response to DDL statement with DATABASE SCOPE l
TABLE, CREATE PROCEDURE, CREATE FUNCTION, ALTER TABLE, ALTER PROCEDURE, ALTER FUNCTION etc.
▪ LOGON Triggers
Logon Triggers gets executed automatically in response to a LOGON event. They get executed only after the
authentication but before the user session is established. If authentication fails the logon triggers will not be f
▪ CLR Triggers
CLR Triggers are based on the Sql CLR. We can write DML and DDL triggers by using the Supported .NET CLR
like C#, VB.NET etc. CLR triggers will useful if require heavy computation in the trigger or require referenc
outside SQL.
, Python
, PHP
, etc. It can support almost all relational database systems.
SQL Server
builds an execution plan when the stored procedure is called the first time and stores them in the cache memory. The plan is reuse
Server in subsequent executions of the stored procedure, allowing it to run quickly and efficiently.
Features of Stored Procedures in SQL Server
The following are the features of stored procedure in SQL Server:
o Reduced Traffic: A stored procedure reduces network traffic between the application and the database server,
increased performance. It is because instead of sending several SQL
statements, the application only needs to send the name of the stored procedure and its parameters.
o Stronger Security: The procedure is always secure because it manages which processes and activities we can
removes the need for permissions to be granted at the database object level and simplifies the security layers.
o Reusable: Stored procedures are reusable. It reduces code inconsistency, prevents unnecessary rewrites of the
and makes the code transparent to all applications or users.
o Easy Maintenance: The procedures are easier to maintain without restarting or deploying the application.
o Improved Performance: Stored Procedure increases the application performance. Once we create the stored
and compile them the first time, it creates an execution plan reused for subsequent executions. The procedur
processed quicker because the query processor does not have to create a new plan.
17.8M
368
HTML Tutorial
53. write a PL/SQL code to print sum of the odd numbers between 1 to 100
Ans:
NUM
Sum
begin
loop
NUM1 :=
Sum:=Sum+Num1;
exit when
end
dbms_output.put_line
end;
Output:
54. write a PL/SQL code to print sum of the even numbers between 1 to 100
Ans: declare
NUM number:=0;
Sum number:=0;
begin
loop
NUM1 := NUM+2;
Sum:=Sum+Num1;
exit when NUM1=100;
end loop;
dbms_output.put_line (sum);
end;
46
Write short note on with examples
50
1. Cursor with types
2. Trigger with advantage
Explain Different Types of Triggers.
51
53 Write A PL/SQL Code to Print Sum Of The Odd Numbers Between 1 to 100.
54 Write a PL/SQL code to print sum of the even numbers between 1 to 100
55