1. Assistant Professor(Gajendra Jingar) 1
BCA Examination 2015
DBMS
1. Answer the following Questions?
a. What Is The RDBMS?
Ans: A relational database management system (RDBMS) is a database management
system (DBMS) based on the relational model invented by Edgar F. Codd, of IBM's San
Jose Research Laboratory fame. Most databases in widespread use today are based on his
relational database model.
RDBMS stands for Relational Database Management System. RDBMS data is
structured in database tables, fields and records. Each RDBMS table consists of database
table rows. Each database table row consists of one or more database table fields.
RDBMS store the data into collection of tables, which might be related by common fields
(database table columns). RDBMS also provide relational operators to manipulate the
data stored into the database tables. Most RDBMS use SQL as database query language.
b. Name Of Any Four Math Function?
Ans: SQRT,LOG,ABS,ROUND
c. What You Mean By Cursor?
Ans: Cursor is a database object to retrieve data from a result set one row at a time,
instead of the T-SQL commands that operate on all the rows in the result set at one time.
We use cursor when we need to update records in a database table in singleton fashion
means row by row.
ITS two type
1.Explicit Cursor
2.Implicit Cursor
d. What Do You Mean By Equi Join?
Ans:An equijoin is a join with a join condition containing an equality operator.
An equijoin returns only the rows that have equivalent values for the specified columns.
An inner join is a join of two or more tables that returns only those rows (compared using
a comparison operator) that satisfy the join condition.
e. What Do You Mean By Mapping Constraint?
Ans: Mapping Constraints
An E-R scheme may define certain constraints to which the contents of a database must
conform.Mapping Cardinalities: express the number of entities to which another entity
can be associated via a relationship. For binary relationship sets between entity sets A and
B, the mapping cardinality must be one of:
1.One-to-one: An entity in A is associated with at most one entity in B, and an entity in B
is associated with at most one entity in A.
2.One-to-many: An entity in A is associated with any number in B. An entity in B is
associated with at most one entity in A.
3.Many-to-one: An entity in A is associated with at most one entity in B. An entity in B is
associated with any number in A.
4.Many-to-many: Entities in A and B are associated with any number from each other.
2. Assistant Professor(Gajendra Jingar) 2
The appropriate mapping cardinality for a particular relationship set depends on the real
world being modeled. (Think about the CustAcct relationship...)
Existence Dependencies: if the existence of entity X depends on the existence of
entity Y, then X is said to be existence dependent on Y. (Or we say that Y is
the dominant entity and X is the subordinate entity.)
f. What Is Use Of GROUP BY Clause?
Ans: Group by clause is used to group the results of a SELECT query based on one or more
columns. It is also used with SQL functions to group the result from one or more tables.
SELECT column_name, function(column_name)
FROM table_name
WHERE condition
GROUP BY column_name
g. What is concept of null value?
Ans: The SQL NULL is the term used to represent a missing value. A NULL value in a table
is a value in a field that appears to be blank. A field with a NULL value is a field with
no value. It is very important to understand that a NULL value is different than a
zero value or a field that contains spaces. A value of NULL indicates that the value is
unknown. A value of NULL is different from an empty or zero value. No two null values
are equal. Comparisons between two null values, or between a NULL and any other value,
return unknown because the value of each NULL is unknown.
Null values generally indicate data that is unknown, not applicable, or that the
data will be added later. For example, a customer's middle initial may not be known at
the time the customer places an order.
h. What is Kernal?
Ans: Two important pieces of RDBMS architecture are the Kernel, which is the software,
and the data dictionary, which consists of the system-level data structures used by the
kernel to manage the database You might think of an RDBMS as an operating system (or
set of subsystems), designed specifically for controlling data access; its primary functions
are storing, retrieving, and securing data. An RDBMS maintains its own list of authorized
users and their associated privileges; manages memory caches and paging; controls
locking for concurrent resource usage; dispatches and schedules user requests; and
manages space usage within its table-space structures.
**************************************
3. Assistant Professor(Gajendra Jingar) 3
Q.2 a).What do you mean by DBMS? Explain the purpose of DBMS.
Ans: A database management system (DBMS) is a software package designed to define,
manipulate, retrieve and manage data in a database. A DBMS generally manipulates the data
itself, the data format, field names, record structure and file structure. It also defines rules to
validate and manipulate this data. A DBMS relieves users of framing programs for data
maintenance. Fourth-generation query languages, such as SQL, are used along with the DBMS
package to interact with a database.
Some dbms examples are: MySQL, SQL Server, Oracle, dBASE, and FoxPro.
Purpose of DBMS to resolve file System Drawbacks.
1. To see why database management systems are necessary, let's look at a typical ``file-
processing system'' supported by a conventional operating system.
The application is a savings bank:
o Savings account and customer records are kept in permanent system files.
o Application programs are written to manipulate files to perform the following
tasks:
Debit or credit an account.
Add a new account.
Find an account balance.
Generate monthly statements.
2. Development of the system proceeds as follows:
o New application programs must be written as the need arises.
o New permanent files are created as required.
o but over a long period of time files may be in different formats, and
o Application programs may be in different languages.
3. So we can see there are problems with the straight file-processing approach:
o Data redundancy and inconsistency
Same information may be duplicated in several places.
All copies may not be updated properly.
o Difficulty in accessing data
May have to write a new application program to satisfy an unusual request.
E.g. find all customers with the same postal code.
Could generate this data manually, but a long job...
o Data isolation
Data in different files.
Data in different formats.
Difficult to write new application programs.
o Multiple users
Want concurrency for faster response time.
Need protection for concurrent updates.
E.g. two customers withdrawing funds from the same account at the same
time - account has $500 in it, and they withdraw $100 and $50. The result
could be $350, $400 or $450 if no protection.
o Security problems
Every user of the system should be able to access only the data they are
permitted to see.
E.g. payroll people only handle employee records, and cannot see customer
accounts; tellers only access account data and cannot see payroll data.
4. Assistant Professor(Gajendra Jingar) 4
Difficult to enforce this with application programs.
o Integrity problems
Data may be required to satisfy constraints.
E.g. no account balance below $25.00.
Again, difficult to enforce or to change constraints with the file-processing
approach.
These problems and others led to the development of database management systems.
b)What You mean by E-R Model ? explain with Example.
Ans: E-R Model: As we described in the tutorial Database models, Entity-relationship model is a
model used for design and representation of relationships between data.
The main data objects are termed as Entities, with their details defined as attributes, some of
these attributes are important and are used to identity the entity, and different entities are
related using relationships.
to understand about the ER Model, we must understand about:
Entity and Entity Set
What are Attributes? And Types of Attributes.
Keys
Relationships
Entity and Entity Set
Considering the above example, Student is an entity, Teacher is an entity, similarly, Class, Subjectetc are
also entities.
An Entity is generally a real-world object which has characteristics and holds relationships in a DBMS.
If a Student is an Entity, then the complete dataset of all the students will be the Entity Set
Attributes
If a Student is an Entity, then student's roll no., student's name, student's age, student's gender etc will
be its attributes.
An attribute can be of many types, here are different types of attributes defined in ER database model:
Simple attribute: The attributes with values that are atomic and cannot be broken down further are
simple attributes. For example, student's age.
Composite attribute: A composite attribute is made up of more than one simple attribute. For example,
student's address will contain, house no., street name, pincode etc.
Derived attribute: These are the attributes which are not present in the whole database management
system, but are derived using other attributes. For example, average age of students in a class.
Single-valued attribute: As the name suggests, they have a single value.
Multi-valued attribute: And, they can have multiple values.
Keys
If the attribute roll no. can uniquely identify a student entity, amongst all the students, then the
attribute roll no. will be said to be a key.
Following are the types of Keys:
Super Key
Candidate Key
Primary Key
5. Assistant Professor(Gajendra Jingar) 5
Relationships
When an Entity is related to another Entity, they are said to have a relationship. For example,
A ClassEntity is related to Student entity, becasue students study in classes, hence this is a relationship.
Depending upon the number of entities involved, a degree is assigned to relationships.
For example, if 2 entities are involved, it is said to be Binary relationship, if 3 entities are involved, it is
said to be Ternary relationship, and so on.
Working with ER Diagrams
ER Diagram is a visual representation of data that describes how data is related to each other. In
ER Model, we disintegrate data into entities, attributes and setup relationships between entities,
all this can be represented visually using the ER diagram.
For example, in the below diagram, anyone can see and understand what the diagram wants to
convey: Developer
develops a website,
whereas a Visitor visits a
website.
Q.3 a). Explain the Role of DBA?
Ans: A Database Administrator
Deciding the hardware device
Depending upon the cost, performance and efficiency of the hardware, it is DBA who
have the duty of deciding which hardware devise will suit the company requirement. It is
hardware that is an interface between end users and database so it needed to be of best
quality.
Managing Data Integrity
6. Assistant Professor(Gajendra Jingar) 6
Data integrity should be managed accurately because it protects the data from
unauthorized use. DBA manages relationship between the data to maintain data
consistency.
Decides Data Recovery and Back up method
If any company is having a big database, then it is likely to happen that database may fail
at any instance. It is require that a DBA takes backup of entire database in regular time
span. DBA has to decide that how much data should be backed up and how frequently
the back should be taken. Also the recovery of data base is done by DBA if they have lost
the database.
Tuning Database Performance
Database performance plays an important role for any business. If user is not able to
fetch data speedily then it may loss company business. So by tuning an modifying sql
commands a DBA can improves the performance of database.
Capacity Issues
All the databases have their limits of storing data in it and the physical memory also has
some limitations. DBA has to decide the limit and capacity of database and all the issues
related to it.
Database design
The logical design of the database is designed by the DBA. Also a DBA is responsible for
physical design, external model design, and integrity control.
Database accessibility
DBA writes subschema to decide the accessibility of database. He decides the users of the
database and also which data is to be used by which user. No user has to power to access
the entire database without the permission of DBA.
Decides validation checks on data
DBA has to decide which data should be used and what kind of data is accurate for the
company. So he always puts validation checks on data to make it more accurate and
consistence.
Monitoring performance
If database is working properly then it doesn’t mean that there is no task for the DBA. Yes
f course, he has to monitor the performance of the database. A DBA monitors the CPU
and memory usage.
Decides content of the database
A database system has many kind of content information in it. DBA decides fields, types
of fields, and range of values of the content in the database system. One can say that DBA
decides the structure of database files.
7. Assistant Professor(Gajendra Jingar) 7
Provides help and support to user
If any user needs help at any time then it is the duty of DBA to help him. Complete
support is given to the users who are new to database by the DBA.
Database implementation
Database has to be implemented before anyone can start using it. So DBA implements
the database system. DBA has to supervise the database loading at the time of its
implementation.
Improve query processing performance
Queries made by the users should be performed speedily. As we have discussed that
users need fast retrieval of answers so DBA improves query processing by improving their
performance.
*********************
Q.3 b) what you mean aggregation ? explain with suitable example?
Ans: The E-R model cannot express relationships among relationships.
When would we need such a thing?
Consider a DB with information about employees who work on a particular project and
use a number of machines doing that work. We get the E-R diagram shown in
Figure 2.20.
Figure 2.20: E-R diagram with
redundant relationships
Relationship sets work and uses could be combined into a single set. However, they
shouldn't be, as this would obscure the logical structure of this scheme.
The solution is to use aggregation.
An abstraction through which relationships are treated as higher-level entities.
For our example, we treat the relationship set work and the entity
sets employee and project as a higher-level entity set called work.
Figure 2.21 shows the E-R diagram with aggregation.
8. Assistant Professor(Gajendra Jingar) 8
Figure 2.21: E-R diagram with aggregation
Transforming an E-R diagram with aggregation into tabular form is easy. We create a
table for each entity and relationship set as before.
The table for relationship set uses contains a column for each attribute in the primary
key of machinery and work.
Aggregation is the process of compiling information on an object, thereby
abstracting a higher level object.
Another Example of Aggregation :
10. Assistant Professor(Gajendra Jingar) 10
Q.4 a) what do you mean by RDBMS ? Explain Oracle utilities.
Ans: RDBMS: Simply put, an RDBMS is a type of DBMS that organizes data into a series of
records held in linked tables. While there are other types of database management approaches,
the relational approach is the most common in many applications, including GIS. The
organization around linked tables aids in data access and transformation because the linkages
based on record values are very flexible. That is, to say, the rules for linkages are established and
the actual association of records is based on values.
There are several fundamental definitions to consider when thinking about RDBMS
•Domain – a pool of values from which specific attributes of specific relations draw their actual
values
•Tuple – an ordered list of values
•Primary key – a unique identifier for a table; any column or combination of columns with the
property that no two rows of the table have the same value in that column or columns
The relational model originated from a paper authored by Dr.codd entitled “A Relational
Model of Data for Large Shared Data Banks”, written in 1970. This paper included the following
concepts that apply to database management systems for relational databases. The relation is
the only data structure used in the relational data model to represent both entities and
relationships between them.
Oracle's database utilities let you perform the following tasks:
High-speed movement of data and metadata from one database to another using Data
Pump Export and Import
Extract and manipulate complete representations of the metadata for database objects,
using the Metadata API
Move all or part of the data and metadata for a site from one database to another, using the
Data Pump API
Load data into Oracle tables from operating system files using SQL*Loader or from
external sources using external tables
Query redo log files through a SQL interface with LogMiner
Perform physical data structure integrity checks on an offline (for example, backup)
database or datafile with DBVERIFY.
Maintain the internal database identifier (DBID) and the database name (DBNAME) for an
operational database, using the DBNEWID utility
And also on
https://docs.oracle.com/cd/B19306_01/server.102/b14220/utility.htm
***************
Q. 4.b) Explain Data Manipulation commands?
Ans: DML commands: A data manipulation language (DML) is a family of syntax elements
similar to a computer programming language used for Selecting , inserting, deleting and updating
data in a database. Performing read-only queries of data is sometimes also considered a
component of DML.
11. Assistant Professor(Gajendra Jingar) 11
A data manipulation language (DML) is a family of computer languages including commands
permitting users to manipulate data in a database. This manipulation involves inserting data into
database tables, retrieving existing data, deleting data from existing tables and modifying
existing data. DML is mostly incorporated in SQL databases.
DML resembles simple English language and enhances efficient user interaction with the
system. The functional capability of DML is organized in manipulation commands like SELECT,
UPDATE,INSERT INTO and DELETE FROM, as described below:
1. SELECT: This command is used to retrieve rows from a table. The select syntax is SELECT
[column name(s)] from [table name] where [conditions]. Select is the most widely used DML
command in SQL.
Syntax
SELECT [DISTINCT|ALL]{*|column|column_expression [AS new_name][,…]}
FROM table_name [alias] [, … ]
[WHERE condition]
[GROUP BY column_list]
[HAVING condition]
[ORDER BY column_list [ASC|DESC]];
column represents a column name.
column_expression represents an expression on a column.
table_name is the name of an existing database table or view.
FROM specifies the table(s) to be used.
WHERE filters the rows subject to some condition.
GROUP BY forms groups of rows with the same column name.
SELECT specifies which column are to appear in the output.
ORDER BY specifies the order of the output.
Order of the clauses in the SELECT statement can not be changed.
The result of a query is another table.
Asterisk (*) means all columns.
12. Assistant Professor(Gajendra Jingar) 12
Five aggregation functions defined in SQL:
COUNT returns the number of rows in a specified column.
SUM returns the sum of the values in a specified column.
AVG returns the average of the values in a specified column.
MIN returns the smallest value in a specified column.
MAX returns the largest value in a specified column.
2.UPDATE: This command modifies data of one or more records. An update command syntax is
UPDATE table name SET column name = value where [condition].
Syntax
UPDATE table_name
SET column_name1 = data_value1 [, column_namei = data_valuei ...]
[WHERE search_condition]
table_name may be either a base table or an updatable view.
The SET clause specifies the names of one or more columns that are updated for
all rows in the table.
Only rows that satisfy the search_condition are updated.
data_values must be compatible with the data types for the corresponding
columns.
3.INSERT: This command adds one or more records to a database table. The insert command
syntax is INSERT INTO table name [column(s)] VALUES [value(s)].
Eg: INSERT INTO Emp VALUES('E101', 'Aamir', 10, 7000');
4.DELETE: This command removes one or more records from a table according to specified
conditions. Delete command syntax is DELETE FROM table name where [condition].
Eg: DELETE FROM emp where ename=’ram’;
********************
13. Assistant Professor(Gajendra Jingar) 13
Q.5 Explain Block Diagram of PL/SQL?
Ans: PL/SQL blocks have a pre-defined structure in which the code is to be grouped. Below are
different sections of PL/SQL blocks
1. Declaration section
2. Execution section
3. Exception-Handling section
Declaration Section
This is the first section of the PL/SQL blocks. This section is an optional part. This is the section in
which the declaration of variables, cursors, exceptions, subprograms, pragma instructions and
collections that are needed in the block will be declared. Below are few more characteristics of this
part.
This particular section is optional and can be skipped if no declarations are needed.
This should be the first section in a PL/SQL block, if present.
This section starts with the keyword 'DECLARE' for triggers and anonymous block. For other
subprograms this keyword will not be present, instead the part after the subprogram name definition
marks the declaration section.
This section should be always followed by execution section.
Execution Section
Execution part is the main and mandatory part which actually executes the code that is written inside
it. Since the PL/SQL expects the executable statements from this block this cannot be an empty block,
i.e., it should have at least one valid executable code line in it. Below are few more characteristics of
this part.
This can contain both PL/SQL code and SQL code.
14. Assistant Professor(Gajendra Jingar) 14
This can contain one or many blocks inside it as a nested blocks.
This section starts with the keyword 'BEGIN'.
This section should be followed either by 'END' or Exception-Handling section (if present)
Exception-Handling Section:
The exception are unavoidable in the program which occurs at run-time and to handle this Oracle has
provided an Exception-handling section in blocks. This section can also contain PL/SQL statements.
This is an optional section of the PL/SQL blocks.
This is the section where the exception raised in the execution block is handled.
This section is the last part of the PL/SQL block.
Control from this section can never return to the execution block.
This section starts with the keyword 'EXCEPTION'.
This section should be always followed by the keyword 'END'.
******************************
Q.5 b) What Do You Mean By Database Connections?
Ans: Database connectivity are used with application software and website with different
connectivity standard with specific programming languages.
Database Connectivity ODBC, JDBC and SQLJ
ODBC is (Open Database Connectivity):A standard or open application programming interface
(API) for accessing a database.SQL Access Group, chiefly Microsoft, in 1992 By using ODBC
statements in a program, you can access files in a number of different databases, including
Access, dBase, DB2, Excel, and Text.
It allows programs to use SQL requests that will access databases without having to know the
proprietary interfaces to the databases. ODBC handles the SQL request and converts it into a
request the individual database system understands.
JDBC is: Java Database
Connectivity is a Java API for connecting programs written in Java to the data in relational
databases. consists of a set of classes and interfaces written in the Java programming language.
15. Assistant Professor(Gajendra Jingar) 15
provides a standard API for tool/database developers and makes it possible to write database
applications using a pure Java API. The standard defined by Sun Microsystems, allowing
individual providers to implement and extend the standard with their own JDBC drivers
establishes a connection with a database sends SQL statements processes the results. ODBC is
used between applications JDBC is used by Java programmers to connect to databases With a
small "bridge" program, you can use the JDBC interface to access ODBC accessible databases.
JDBC allows SQL-based database access for EJB persistence and for direct manipulation from
CORBA, DJB or other server objects
JDBC API :The JDBC API supports both two-tier and three-tier models for database access. Two-
tier model -- a Java applet or application interacts directly with the database. Three-tier model
-- introduces a middle-level server for execution of business logic: the middle tier to maintain
control over data access. the user can employ an easy-to-use higher-level API which is
translated by the middle tier into the appropriate low-level calls.
The JDBC Steps
1. Importing Packages
2. Registering the JDBC Drivers
3. Opening a Connection to a Database
4. Creating a Statement Object
5. Executing a Query and Returning a Result Set Object
6. Processing the Result Set
7. Closing the Result Set and Statement Objects
8. Closing the Connection
SQLJ is a set of programming extensions that allow a programmer using the Java programming
language to embed statements that provide SQL database requests. SQLJ is similar to existing
16. Assistant Professor(Gajendra Jingar) 16
extensions for SQL that are provided for C, FORTRAN, and other programming languages. IBM,
Oracle, and several other companies are proposed SQLJ as a standard and as a simpler and
easier-to-use alternative to JDBC.
The SQLJ specifications are in several parts:
SQLJ: Embedded SQL...Specifications for embedding SQL statements in Java methods.
SQLJ: SQL Routines...Specifications for calling Java static methods as SQL stored procedures and
user-defined functions.
SQLJ: SQL Types...Specifications for using Java classes as SQL user-defined data types.
***************
Q.6 a) What you mean by cursor and explain cursor management?
Ans: Oracle creates a memory area, known as context area, for processing an SQL statement,
which contains all information about the statement, for example, number of rows processed, etc.
Cursor is nothing but a pointer to this context area. PL/SQL allows the programmer to control the
context area through the cursor. A cursor holds the rows returned by the SQL statement. The set of
rows the cursor holds is referred as active set. These cursors can also be named so that they can be
referred from other place of the code. The cursor is of two types.
Implicit Cursor
Explicit Cursor
IMPLICIT CURSOR :- It is declared by PL/SQL implicitly when DML statements like INSERT,
UPDATE and DELETE statements are executed. They are also declared when a SELECT
statement that returns just one row is executed.
When the executable part of a PL/SQL block issues a SQL statement, PL/SQL
creates an implicit cursor, which PL/SQL manages automatically.
IMPLICIT CURSOR ATTRIBUTES :-Oracle provides few attributes for implicit cursor called as
implicit cursor attributes to check the status of DML operations.
These attributes are :-
(1) %FOUND
(2) %NOTFOUND
(3) %ROWCOUNT
(4) %ISOPEN
The status of the cursor for each of these attributes is defined in the below table :-
Attribute Return Value Example
%FOUND The return value is TRUE, SQL%FOUND
if the DML statements like
INSERT, DELETE and
UPDATE affect at least
one row and if
SELECT...INTO statement
return at least one row.
18. Assistant Professor(Gajendra Jingar) 18
INSERT, DELETE and
UPDATE do not affect any
row and if SELECT ….
INTO statement does not
return a row.
%NOTFOUND The return value is FALSE, SQL%NOT FOUND
if the DML statements like
INSERT, DELETE and
UPDATE affect at least
one row and if SELECT …
INTO statement return at
least one row.
The return value is TRUE,
if the DML statements like
INSERT, DELETE and
UPDATE do not affect any
row and if SELECT …..
INTO statement does not
return a row.
%ROWCOUNT Return the number of rows SQL%ROWCOUNT
affected by the DML
operations INSERT,
DELETE , UPDATE , or
single row SELECT.
%ISOPEN THe return value is always SQL%ISOPEN
FALSE because Oracle
automatically closes an
Implicit Cursor after
executing its SQL
statement.
Declare
var_rows number(5);
BEGIN
UPDATE BCA
SET ID = 9;
IF SQL%NOTFOUND THEN
20. Assistant Professor(Gajendra Jingar) 20
Syntax :-
FETCH <cursor_name> INTO <variables>;
For each column value returned by the query associated with the cursor, there must
be a corresponding variable in the INTO list. Also their data types must be compatible
EXAMPLE :-
declare
stu_id bca.id%type;
stu_name bca.name%type;
stu_gender bca.gender%type;
cursor c1 IS Select id,name,gender from bca where id=6;
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO stu_id, stu_name,stu_gender;
EXIT WHEN c1%NOTFOUND;
dbms_output.put_line(stu_id||' '||stu_name ||' '||stu_gender);
END LOOP;
END;
/
(4) Closing an Explicit Cursor :- Close the cursor after completing the processing of the
SELECT statement. This step allows the cursor to be reopened, if required. Therefore, you can
establish an active set several times. The CLOSE statement is used to close an explicit cursor.
Syntax :-
CLOSE <cursor_name>;
EXPLICIT CURSOR ATTRIBUTES :
ORACLE provides some attributes known as Explicit Cursor Attributes to control the
data processing while using cursors. We use these attributes to avoid errors while accessing
cursors through OPEN, FETCH and CLOSE statements. These are the attributes available to
check the status of an explicit cursor.
Attribute Return Value Example
%FOUND TRUE, if fetch statement Cursor_name%FOUND
return at least one row.
FALSE, if fetch statement
does not return a row.
21. Assistant Professor(Gajendra Jingar) 21
%NOTFOUND TRUE, if each fetch Cursor_name%NOTFOUN
statement doesn’t return a D
row.
FALSE, if each fetch
statement returns at least
one row.
%ROWCOUNT Returns the number of Cursor_name%ROWCOU
rows fetched by the fetch NT
statement
If no row is returned, the
PL/SQL statement returns
an error
%ISOPEN TRUE if the cursor is Cursor_name%ISOPEN
already open in the
program
FALSE, if the cursor is not
opened in the program.
****************************
Q.6 b) Explain database Locking?
Ans: Locks are mechanism used to ensure data integrity. The oracle engine automatically locks
j tabledata while executing SQL statements like Select/insert/UPDATE/DELETE. This K type of
locking is called implicit locking
There are two types of Locks
1. Shared lock
2. Exclusive lock
Shared lock:
Shared locks are placed on resources whenever a read operation (select) is performed. Multiple
shared locks can be simultaneously set on a resource.
Exclusive lock:
Exclusive locks are placed on resources whenever a write operation (INSERT, UPDATE And
DELETE) are performed. Only one exclusive lock can be placed on a resource at a time. i.e. the
first user who acquires an exclusive lock will continue to have the sole ownership of the
resource, and no other user can acquire an exclusive lock on that resource
Levels of Locks:
22. Assistant Professor(Gajendra Jingar) 22
Oracle does not provide a field level lock.Oracle provides the following three levels of Locking.
Row level
Page level
Table level
Row Level locking
If the WHERE clause evaluates to only one row in the table, a row level lock is used.
Page Level locking
If the WHERE clause evaluates to a set of data, a page level lock is used.
Table Level locking
If there is no WHERE clause, the query accesses the entire table, a table level lock is used.
Can't update entire table data when update is done by other user.
Syntax:
LOCK TABLE <tablename> [<tablename>]….. IN { ROW SHARE / ROW EXCLUSIVE / SHARE
UPDATE / SHARE / SHARE ROW EXCLUSIVE / EXCLUSIVE}[NOWAIT]
Exclusive lock:
They allow query on the locked resource but prohibit any other activity
Example:
Run SQL Command Line
SQL> Lock table client_master IN Exclusive Mode NOWAIT;
Table(s) Locked.
Deadlock:
In a deadlock, two database operations wait for each other to release a lock.
A deadlock occurs when two users have a lock, each on a separate object, and, they want to
acquire a lock on each other's object.
When this happens, the first user has to wait for the second user to release the lock, but the
second user will not release it until the lock on the first user's object is freed. At this point, both
the users are at an impasse and cannot proceed with their business.
23. Assistant Professor(Gajendra Jingar) 23
In such a case, Oracle detects the deadlock automatically and solves the problem by aborting
one of the two transactions.
example :
Transaction 1
BEGIN
UPDATE client_master SET salary = 500 WHERE client_no=’c1’;
UPDATE client_master SET salary = 500 WHERE client_no=’c2’;
END
Transaction 2
BEGIN
UPDATE client_master SET salary = 5000 WHERE client_no=’c2’;
UPDATE client_master SET salary = 500 WHERE client_no=’c1’;
END
Assume that Transaction 1 and Transaction2 begin exactly at the same time.
By default Oracle automatically places exclusive lock on data that is being updated.
This causes Transaction 1 to wait for Transaction2 to complete but in turn Transaction2 has to
wait for Transaction 1 to complete.
*******************
Q.7 A) What Do You Mean By Join ? Explain All Type Of Join With Suitable
Example?
Ans: Joins can be simply defined as the combining or merging the related tuples from
the two different relations into a single type. It can be said that it is similar to cartesian
product except the fact that in cartesian product, we get all the possible combinations of
relations while in join only those combinations can be formed that satisfies some
matching conditions. A cartesian product is followed by a selection process results in
join. We can classify joins basically into two types
1. INNER JOINS: These joins are the one that has the tuples that satisfy some
conditions and rest are discarded . Further they are classified as
24. Assistant Professor(Gajendra Jingar) 24
Theta join
Equi join
Natural join
2. OUTER JOINS: These have all the tuples from either or both the relations.
Further they are classified as
Left outer join
Right outer join
Full outer join
Let us now move on to the study the classified types with examples in detail.
INNER JOINS
1. Theta join(θ) – They have tuples from different relations if and only if they
satisfy the theta condition, here the comparison operators (≤, ≥, ˂, ˃, =, ̚ )come
into picture. Let us consider simple example to understand in a much better way,
suppose we want to buy a mobile and a laptop, based on our budget we have
thought of buying both such that mobile price should be less than that of laptop.
Look at the tables below,
Now, we have considered the condition as the cost of the mobile should be less than that
of laptop so our resulting table will have only those tuples that satisfy this condition.
AFTER JOINS
25. Assistant Professor(Gajendra Jingar) 25
2. Equi join – As the name itself indicates, if suppose the join uses only the equality
operator then it is called as equi join.
3. Natural join – It does not utilize any of the comparison operator. Here the
condition is that the attributes should have same name and domain. There has to be at
least one common attribute between between two relations. It forms the cartesian
product of two arguments, performs selection forming equality on those attributes that
appear in both relations and eliminates the duplicate attributes. Consider the example,
where two tables namely employment table and department table have been shown. e
Looking at above tables we realize that they have a common attribute called
DPT_NAME, thus after the natural join the table becomes
as
26. Assistant Professor(Gajendra Jingar) 26
Outer join
1. Left outer join – All the tuples of left table is displayed irrespective of whether
it satisfies the matching conditions. Thus in the left all the tuples have been
displayed but in the right only those are present that satisfy the matching
conditions. For example consider below example of two tables – country table
that has 3 records and state table that has 4 records. Country names are given the
country_id that has to match with the country_id in the state table. India’s state
is Karnataka and Tamil Nadu, state of Pakistan is Islamabad but Nepal does not
have state in the given table so right part will be null.
So for left join, left side table have all the values but right side only has those whose
COUNTRY_ID has been matched.
27. Assistant Professor(Gajendra Jingar) 27
LEFT OUTER JOIN
Bangladesh has not occurred since there is no match found.
2. Right outer join – All the tuples of right table are displayed irrespective of whether it
satisfies the matching conditions or not.. Thus in the right, all the tuples have been displayed
but in the left only those are present that satisfy the matching conditions. The previous
example can be implemented here as well.
RIGHT OUTER JOIN
2. Full outer join– Tuples from both the relations takes part irrespective of
whether it
has the
matching or
non-
matching
conditions.
Example is
as shown
FULL
OUTER
JOIN
29. Assistant Professor(Gajendra Jingar) 29
Q.7 b) what do you mean by database writer and log writer?
Ans: Database Writer Process (DBWn)
The database writer process (DBWn) writes the contents of buffers to datafiles. The
DBWn processes are responsible for writing modified (dirty) buffers in the database buffer
cache to disk. Although one database writer process (DBW0) is adequate for most systems, you
can configure additional processes (DBW1 through DBW9 and DBWa through DBWj) to improve
write performance if your system modifies data heavily. These additional DBWnprocesses are
not useful on uniprocessor systems.
When a buffer in the database buffer cache is modified, it is marked dirty. A cold buffer
is a buffer that has not been recently used according to the least recently used (LRU) algorithm.
The DBWn process writes cold, dirty buffers to disk so that user processes are able to find cold,
clean buffers that can be used to read new blocks into the cache. As buffers are dirtied by user
processes, the number of free buffers diminishes. If the number of free buffers drops too low,
user processes that must read blocks from disk into the cache are not able to find free buffers.
DBWn manages the buffer cache so that user processes can always find free buffers.
By writing cold, dirty buffers to disk, DBWn improves the performance of finding free buffers
while keeping recently used buffers resident in memory. For example, blocks that are part of
frequently accessed small tables or indexes are kept in the cache so that they do not need to be
read in again from disk. The LRU algorithm keeps more frequently accessed blocks in the buffer
cache so that when a buffer is written to disk, it is unlikely to contain data that will be useful
soon.
The initialization parameter DB_WRITER_PROCESSES specifies the number of
DBWn processes. The maximum number of DBWn processes is 20. If it is not specified by the
user during startup, Oracle determines how to set DB_WRITER_PROCESSES based on the
number of CPUs and processor groups.
The DBWn process writes dirty buffers to disk under the following conditions:
When a server process cannot find a clean reusable buffer after scanning a threshold
number of buffers, it signals DBWn to write. DBWn writes dirty buffers to disk
asynchronously while performing other processing.
DBWn periodically writes buffers to advance the checkpoint, which is the position in the
redo thread (log) from which instance recovery begins. This log position is determined
by the oldest dirty buffer in the buffer cache.
Log Writer Process (LGWR)
The log writer process (LGWR) is responsible for redo log buffer management—writing the
redo log buffer to a redo log file on disk. LGWR writes all redo entries that have been copied
into the buffer since the last time it wrote.
The redo log buffer is a circular buffer. When LGWR writes redo entries from the redo log buffer
to a redo log file, server processes can then copy new entries over the entries in the redo log
buffer that have been written to disk. LGWR normally writes fast enough to ensure that space is
always available in the buffer for new entries, even when access to the redo log is heavy.
LGWR writes one contiguous portion of the buffer to disk. LGWR writes:
30. Assistant Professor(Gajendra Jingar) 30
A commit record when a user process commits a transaction Redo log buffers
o Every three seconds
o When the redo log buffer is one-third full
o When a DBWn process writes modified buffers to disk, if necessary
***************************
Q.8 Short notes(any Four)
1)Control files: Every Oracle Database has a control file, which is a small binary file that
records the physical structure of the database. The control file includes:
The database name
Names and locations of associated datafiles and redo log files
The timestamp of the database creation
The current log sequence number
Checkpoint information
The control file must be available for writing by the Oracle Database server whenever the
database is open. Without the control file, the database cannot be mounted and recovery is
difficult.
The control file of an Oracle Database is created at the same time as the database. By default,
at least one copy of the control file is created during database creation. On some operating
systems the default is to create multiple copies. You should create two or more copies of the
control file during database creation. You can also create control files later, if you lose control
files or want to change particular settings in the control files.
2)Any string function:
UPPER(string), LOWER(string), INITCAP(string)
Returns string in all upper case, all lower case, first letter of each word capitalized,
respectively.
LPAD(string, length, pad), RPAD(string, length, pad)
Returns string padded on left or right to length characters using the pad string as
padding. Pad may be omitted: defaults to single space.
LTRIM(string,trimlist), RTRIM(string,trimlist)
Returns string with the leftmost or rightmost characters that match the characters
in trimlist removed. Trimlist may be omitted: defaults to single space.
REPLACE(string,target,replacement)
Returns string with all occurances of target replaced with replacement. If replacement is
omitted, occurances are deleted.
SUBSTR(string,pos,len)
Returns the substring of string which begins at pos and is len characters long. If pos is
negative, pos is counted from the end of string. The first position in string is 1 not 0.
TRANSLATE(string,fromlist,tolist)
Returns string with each character in the fromlist replaced with the corresponding
character in the tolist.
31. Assistant Professor(Gajendra Jingar) 31
TO_CHAR(number,'format')
formats the number according to the format string (which must be within single quotes.
3)PGA :PGA stands for Process Global Area. This is memory reserved for each process that
uses Oracle. It contains the context area. Oracle sets this area's size based on the values of the
initialization parameters:
OPEN_LINKS. The number of database links allowed open per user.
DB_FILES. The number of database files allowed for the database (up to the value of
MAX_DATAFILES).
LOG_FILES. The maximum number of redo log file groups (up to the value of
MAX_LOGFILES).
The PGA also contains session-related information if MTS is not used. In environments where
MTS is used, the session information is placed in the SHARED_POOL region of the SGA if the
LARGE POOL (in Oracle8,8i and 9i) is not configured. This session information consists of the
user's private SQL area and other session-specific data. The PGA will always hold the user's
stack information. The section of the shared or LARGE POOL allocated for the user is called the
UGA, which stands for Users Global Area.
4)Alter query
This SQL Server tutorial explains how to use the ALTER TABLE statement in SQL Server
(Transact-SQL) to add a column, modify a column, drop a column, rename a column or rename
a table with syntax and examples.
Description
The SQL Server (Transact-SQL) ALTER TABLE statement is used to add, modify, or drop columns
in a table.
Add column in table
You can use the ALTER TABLE statement in SQL Server to add a column to a table.Syntax
The syntax to add a column in a table in SQL Server (Transact-SQL) is:
ALTER TABLE table_name
ADD column_name column-definition;
Add multiple columns in table
You can use the ALTER TABLE statement in SQL Server to add multiple columns to a table.
Syntax
The syntax to add multiple columns to an existing table in SQL Server (Transact-SQL) is:
ALTER TABLE table_name
ADD column_1 column-definition,
column_2 column-definition,
...
column_n column_definition;
32. Assistant Professor(Gajendra Jingar) 32
Drop column in table
You can use the ALTER TABLE statement in SQL Server to drop a column in a table.
Syntax
The syntax to drop a column in an existing table in SQL Server (Transact-SQL) is:
ALTER TABLE table_name
DROP COLUMN column_name;
5)DDL and DML
Data Definition Language (DDL) and Data Manipulation Language (DML) together
forms a Database Language. The basic difference between DDL and DML is
that DDL (Data Definition Language) is used to Specify the database schema
database structure. On the other hand, DML (Data Manipulation Language) is used
to access, modify or retrieve the data from the database. Let us discuss the
differences between DDL and DML, with the help of comparison chart shown below.
BASIS FOR
COMPARISON
DDL DML
Basic DDL is used to create the
database schema.
DML is used to populate and
manipulate database
Full Form Data Definition Language Data Manipulation Language
Classification DDL is not classified further. DML is further classified as
Procedural and Non-Procedural
DMLs.
Commands CREATE, ALTER, DROP, TRUNCATE
AND COMMENT and RENAME, etc.
SELECT, INSERT, UPDATE,
DELETE, MERGE, CALL, etc.