DBMS Questions: Ramesh 1 Ramesh
DBMS Questions: Ramesh 1 Ramesh
1. What is DBMS?
A database is a logically coherent collection of data with some inherent meaning, representing some
aspect of real world and which is designed, built and populated with data for a specific purpose.
4. Advantages of DBMS?
Redundancy is controlled.
Unauthorised access is restricted.
Providing multiple user interfaces.
Enforcing integrity constraints.
Providing backup and recovery.
Ramesh 1 Ramesh
DBMS Questions
used in a real life environment to solve real life problems, with performance at least comparable to that of
existing system.
Its two subsystems are
Research Storage
System Relational Data System.
10. How is the data structure of System R different from the relational structure?
Unlike Relational systems in System R
Domains are not supported
Enforcement of candidate key uniqueness is optional
Enforcement of entity integrity is optional
Referential integrity is not enforced
Ramesh 2 Ramesh
DBMS Questions
Ramesh 3 Ramesh
DBMS Questions
29. What is DML (Data Manipulation Language)?
This language that enable user to access or manipulate data as organised by appropriate data model.
Procedural DML or Low level: DML requires a user to specify what data are needed and how to get
those data.
Non-Procedural DML or High level: DML requires a user to specify what data are needed without
specifying how to get those data.
38. How does Tuple-oriented relational calculus differ from domain-oriented relational calculus
The tuple-oriented calculus uses a tuple variables i.e., variable whose only permitted values are tuples
of that relation. E.g. QUEL
The domain-oriented calculus has domain variables i.e., variables that range over the underlying domains
instead of over relation. E.g. ILL, DEDUCE.
Ramesh 4 Ramesh
DBMS Questions
for any two tuples t1 and t2 in r if t1[X] = t2[X] then they have t1[Y] = t2[Y]. This means the value of X
component of a tuple uniquely determines the value of component Y.
Ramesh 5 Ramesh
DBMS Questions
X is a super key.
52. What are partial, alternate,, artificial, compound and natural key?
Partial Key:
It is a set of attributes that can uniquely identify weak entities and that are related to same owner
entity. It is sometime called as Discriminator.
Alternate Key:
All Candidate Keys excluding the Primary Key are known as Alternate Keys.
Artificial Key:
If no obvious key, either stand alone or compound is available, then the last resort is to
simply create a key, by assigning a unique number to each record or occurrence. Then this is known as
developing an artificial key.
Compound Key:
If no single data element uniquely identifies occurrences within a construct, then combining
multiple elements to create a unique identifier for the construct is known as creating a compound key.
Natural Key:
When one of the data elements stored within a construct is utilized as the primary key, then it
is called the natural key.
53. What is indexing and what are the different kinds of indexing?
Indexing is a technique for determining how quickly specific data can be found.
Types:
Binary search style indexing
B-Tree indexing
Inverted list indexing
Memory resident table
Table indexing
54. What is system catalog or catalog relation? How is better known as?
A RDBMS maintains a description of all the data that it contains, information about every relation
and index that it contains. This information is stored in a collection of relations maintained by the system
called metadata. It is also called data dictionary.
Ramesh 6 Ramesh
DBMS Questions
Join Dependency:
A Join dependency is generalization of Multivalued dependency.A JD {R1, R2, ...,
Rn} is said to hold over a relation R if R1, R2, R3, ..., Rn is a lossless-join decomposition of R . There is no
set of sound and complete inference rules for JD.
Inclusion Dependency:
An Inclusion Dependency is a statement of the form that some columns of a relation are
contained in other columns. A foreign key constraint is an example of inclusion dependency.
Ramesh 7 Ramesh
DBMS Questions
65. What is a query?
A query with respect to DBMS relates to user commands that are used to interact with a data base.
The query language can be classified into data definition language and data manipulation language.
67. What are the primitive operations common to all record management systems?
Addition, deletion and modification.
68. Name the buffer in which all the commands that are typed in are stored
‘Edit’ Buffer
70. Are the resulting relations of PRODUCT and JOIN operation the same?
No.
PRODUCT: Concatenation of every row in one relation with every row in another.
JOIN: Concatenation of rows from one relation and related rows from another.
73. Which part of the RDBMS takes care of the data dictionary? How
Data dictionary is a set of tables and database objects that is stored in a special area of the database
and maintained exclusively by the kernel.
Ramesh 8 Ramesh
DBMS Questions
The information in the data dictionary validates the existence of the objects, provides access to them,
and maps the actual physical storage location.
77. Define SQL and state the differences between SQL and other conventional programming Languages
SQL is a nonprocedural language that is designed specifically for data access operations on
normalized relational database structures. The primary difference between SQL and other conventional
programming languages is that SQL statements specify what data operations should be performed rather than
how to perform them.
78. Name the three major set of files on disk that compose a database in Oracle
There are three major sets of files on disk that compose a database. All the files are binary. These are
Database files
Control files
Redo logs
The most important of these are the database files where the actual data resides. The control files and
the redo logs support the functioning of the architecture itself.
All three sets of files must be present, open, and available to Oracle for any data on the database to be
useable. Without these files, you cannot access the database, and the database administrator might have to
recover some or all of the database using a backup, if there is one.
Ramesh 9 Ramesh
DBMS Questions
80. What are the four Oracle system processes that must always be up and running for the database to be
useable
The four Oracle system processes that must always be up and running for the database to be useable
include DBWR (Database Writer), LGWR (Log Writer), SMON (System Monitor), and PMON (Process
Monitor).
81. What are database files, control files and log files. How many of these files should a database have at
least? Why?
Database Files
The database files hold the actual data and are typically the largest in size. Depending on their
sizes, the tables (and other objects) for all the user accounts can go in one database file—but that's not an
ideal situation because it does not make the database structure very flexible for controlling access to storage
for different users, putting the database on different disk drives, or backing up and restoring just part of the
database.
You must have at least one database file but usually, more than one files are used. In terms of
accessing and using the data in the tables and other objects, the number (or location) of the files is
immaterial.
The database files are fixed in size and never grow bigger than the size at which they were
created
Control Files
The control files and redo logs support the rest of the architecture. Any database must have at
least one control file, although you typically have more than one to guard against loss. The control file
records the name of the database, the date and time it was created, the location of the database and redo logs,
and the synchronization information to ensure that all three sets of files are always in step. Every time you
add a new database or redo log file to the database, the information is recorded in the control files.
Redo Logs
Any database must have at least two redo logs. These are the journals for the database; the
redo logs record all changes to the user objects or system objects. If any type of failure occurs, the changes
recorded in the redo logs can be used to bring the database to a consistent state without losing any committed
Ramesh 10 Ramesh
DBMS Questions
transactions. In the case of non-data loss failure, Oracle can apply the information in the redo logs
automatically without intervention from the DBA.
The redo log files are fixed in size and never grow dynamically from the size at which they
were created.
83. What is Oracle Block? Can two Oracle Blocks have the same address?
Oracle "formats" the database files into a number of Oracle blocks when they are first created—
making it easier for the RDBMS software to manage the files and easier to read data into the memory areas.
The block size should be a multiple of the operating system block size. Regardless of the block size,
the entire block is not available for holding data; Oracle takes up some space to manage the contents of the
block. This block header has a minimum size, but it can grow.
These Oracle blocks are the smallest unit of storage. Increasing the Oracle block size can improve
performance, but it should be done only when the database is first created.
Each Oracle block is numbered sequentially for each database file starting at 1. Two blocks can have
the same block address if they are in different database files.
85. Name two utilities that Oracle provides, which are use for backup and recovery.
Along with the RDBMS software, Oracle provides two utilities that you can use to back up and
restore the database. These utilities are Export and Import.
The Export utility dumps the definitions and data for the specified part of the database to an operating
system binary file. The Import utility reads the file produced by an export, recreates the definitions of objects,
and inserts the data
If Export and Import are used as a means of backing up and recovering the database, all the changes
made to the database cannot be recovered since the export was performed. The best you can do is recover the
database to the time when the export was last performed.
86. What are stored-procedures? And what are the advantages of using them.
Ramesh 11 Ramesh
DBMS Questions
Stored procedures are database objects that perform a user defined operation. A stored procedure can
have a set of compound SQL statements. A stored procedure executes the SQL commands and returns the
result to the client. Stored procedures are used to reduce network traffic.
87. How are exceptions handled in PL/SQL? Give some of the internal exceptions' name
PL/SQL exception handling is a mechanism for dealing with run-time errors encountered during
procedure execution. Use of this mechanism enables execution to continue if the error is not severe enough to
cause procedure termination.
The exception handler must be defined within a subprogram specification. Errors cause the program
to raise an exception with a transfer of control to the exception-handler block. After the exception handler
executes, control returns to the block in which the handler was defined. If there are no more executable
statements in the block, control returns to the caller.
User-Defined Exceptions
PL/SQL enables the user to define exception handlers in the declarations area of subprogram
specifications. User accomplishes this by naming an exception as in the following example:
ot_failure EXCEPTION;
In this case, the exception name is ot_failure. Code associated with this handler is written in the
EXCEPTION specification area as follows:
EXCEPTION
when OT_FAILURE then
out_status_code := g_out_status_code;
out_msg := g_out_msg;
The following is an example of a subprogram exception:
EXCEPTION
when NO_DATA_FOUND then
g_out_status_code := 'FAIL';
RAISE ot_failure;
Within this exception is the RAISE statement that transfers control back to the ot_failure exception handler.
This technique of raising the exception is used to invoke all user-defined exceptions.
System-Defined Exceptions
Exceptions internal to PL/SQL are raised automatically upon error. NO_DATA_FOUND is a
system-defined exception. Table below gives a complete list of internal exceptions.
Ramesh 12 Ramesh
DBMS Questions
VALUE_ERROR ORA-06502
ZERO_DIVIDE ORA-01476
In addition to this list of exceptions, there is a catch-all exception named OTHERS that traps all errors
for which specific error handling has not been established.
(a) i & iii because theta joins are joins made on keys that are not primary keys.
Ramesh 13 Ramesh
DBMS Questions
c) relations in ERD has 1 to 1 correspondence to processes in DFD
d) relationships in ERD has 1 to 1 correspondence to flows in DFD
94. Select 'NORTH', CUSTOMER From CUST_DTLS Where REGION = 'N' Order By
CUSTOMER Union Select 'EAST', CUSTOMER From CUST_DTLS Where REGION = 'E' Order By
CUSTOMER
The above is
a) Not an error
b) Error - the string in single quotes 'NORTH' and 'SOUTH'
c) Error - the string should be in double quotes
d) Error - ORDER BY clause
(d) Error - the ORDER BY clause. Since ORDER BY clause cannot be used in UNIONS
Ramesh 14 Ramesh
DBMS Questions
of procedures are not available for reference from other Oracle tools. Another limitation of stand-alone
procedures is that they are compiled at run time, which slows execution.
102. What is cold backup and hot backup (in case of Oracle)?
Cold Backup:
It is copying the three sets of files (database files, redo logs, and control file) when the
instance is shut down. This is a straight file copy, usually from the disk directly to tape. You must shut down
the instance to guarantee a consistent copy.
If a cold backup is performed, the only option available in the event of data file loss is
restoring all the files from the latest backup. All work performed on the database since the last backup is lost.
Hot Backup:
Some sites (such as worldwide airline reservations systems) cannot shut down the
database while making a backup copy of the files. The cold backup is not an available option.
So different means of backing up database must be used — the hot backup. Issue a SQL
command to indicate to Oracle, on a tablespace-by-tablespace basis, that the files of the tablespace are to
backed up. The users can continue to make full use of the files, including making changes to the data. Once
the user has indicated that he/she wants to back up the tablespace files, he/she can use the operating system to
copy those files to the desired backup destination.
The database must be running in ARCHIVELOG mode for the hot backup option.
If a data loss failure does occur, the lost database files can be restored using the hot
backup and the online and offline redo logs created since the backup was done. The database is restored to
the most consistent state without any loss of committed transactions.
103. What are Armstrong rules? How do we say that they are complete and/or sound
The well-known inference rules for FDs
Reflexive rule :
If Y is subset or equal to X then X Y.
Augmentation rule:
If X Y then XZ YZ.
Transitive rule:
If {X Y, Y Z} then X Z.
Decomposition rule :
If X YZ then X Y.
Union or Additive rule:
If {X Y, X Z} then X YZ.
Pseudo Transitive rule :
If {X Y, WY Z} then WX Z.
Of these the first three are known as Amstrong Rules. They are sound because it is enough if a set of
FDs satisfy these three. They are called complete because using these three rules we can generate the rest all
inference rules.
104. How can you find the minimal key of relational schema?
Ramesh 15 Ramesh
DBMS Questions
Minimal key is one which can identify each tuple of the given relation schema uniquely. For finding
the minimal key it is required to find the closure that is the set of all attributes that are dependent on any
given set of attributes under the given set of functional dependency.
Algo. I Determining X+, closure for X, given set of FDs F
1. Set X+ = X
2. Set Old X+ = X+
3. For each FD Y Z in F and if Y belongs to X+ then add Z to X+
4. Repeat steps 2 and 3 until Old X+ = X+
Ramesh 16 Ramesh
DBMS Questions
SQL
1. Which is the subset of SQL commands used to manipulate Oracle Database structures, including tables?
Data Definition Language (DDL)
5. What is the parameter substitution symbol used with INSERT INTO command?
&
6. Which command displays the SQL command in the SQL buffer, and then executes it?
RUN
9. State true or false. !=, <>, ^= all denote the same operation.
True
10. What are the privileges that can be granted on a table by a user to others?
Insert, update, delete, select, references, index, execute, alter, all
11. What command is used to get back the privileges offered by the GRANT command?
REVOKE
12. Which system tables contain information on privileges granted and privileges obtained?
USER_TAB_PRIVS_MADE, USER_TAB_PRIVS_RECD
13. Which system table contains information on constraints on all the tables created?
Ramesh 17 Ramesh
DBMS Questions
USER_CONSTRAINTS
16. What command is used to create a table by copying the structure of another table?
Answer :
CREATE TABLE .. AS SELECT command
Explanation :
To copy only the structure, the WHERE clause of the SELECT command should contain a FALSE
statement as in the following.
CREATE TABLE NEWTABLE AS SELECT * FROM EXISTINGTABLE WHERE 1=2;
If the WHERE condition is true, then all the rows or rows satisfying the condition will be copied to
the new table.
20. Which date function is used to find the difference between two dates?
MONTHS_BETWEEN
22. What is the advantage of specifying WITH GRANT OPTION in the GRANT command?
Ramesh 18 Ramesh
DBMS Questions
The privilege receiver can further grant the privileges he/she has obtained from the owner to any
other user.
23. What is the use of the DROP option in the ALTER TABLE command?
It is used to drop constraints specified on the table.
24. What is the value of ‘comm’ and ‘sal’ after executing the following query if the initial value of ‘sal’ is
10000?
UPDATE EMP SET SAL = SAL + 1000, COMM = SAL*0.1;
sal = 11000, comm = 1000
27. Which function is used to find the largest integer less than or equal to a specific value?
FLOOR
Ramesh 19 Ramesh
DBMS Questions
SQL – QUERIES
I. SCHEMAS
Table 1 : STUDIES
Table 2 : SOFTWARE
Table 3 : PROGRAMMER
PNAME (VARCHAR), DOB (DATE), DOJ (DATE), SEX (CHAR), PROF1 (VARCHAR), PROF2
(VARCHAR), SAL (NUMBER)
LEGEND :
PNAME – Programmer Name, SPLACE – Study Place, CCOST – Course Cost, DEVIN – Developed in,
SCOST – Software Cost, DCOST – Development Cost, PROF1 – Proficiency 1
QUERIES :
1. Find out the selling cost average for packages developed in Oracle.
2. Display the names, ages and experience of all programmers.
3. Display the names of those who have done the PGDCA course.
4. What is the highest number of copies sold by a package?
5. Display the names and date of birth of all programmers born in April.
6. Display the lowest course fee.
7. How many programmers have done the DCA course.
8. How much revenue has been earned through the sale of packages developed in C.
9. Display the details of software developed by Rakesh.
10. How many programmers studied at Pentafour.
11. Display the details of packages whose sales crossed the 5000 mark.
12. Find out the number of copies which should be sold in order to recover the development cost of each
package.
13. Display the details of packages for which the development cost has been recovered.
14. What is the price of costliest software developed in VB?
15. How many packages were developed in Oracle ?
16. How many programmers studied at PRAGATHI?
17. How many programmers paid 10000 to 15000 for the course?
18. What is the average course fee?
19. Display the details of programmers knowing C.
20. How many programmers know either C or Pascal?
21. How many programmers don’t know C and C++?
22. How old is the oldest male programmer?
Ramesh 20 Ramesh
DBMS Questions
23. What is the average age of female programmers?
24. Calculate the experience in years for each programmer and display along with their names in
descending order.
25. Who are the programmers who celebrate their birthdays during the current month?
26. How many female programmers are there?
27. What are the languages known by the male programmers?
28. What is the average salary?
29. How many people draw 5000 to 7500?
30. Display the details of those who don’t know C, C++ or Pascal.
31. Display the costliest package developed by each programmer.
32. Produce the following output for all the male programmers
Programmer
Mr. Arvind – has 15 years of experience
Ramesh 21 Ramesh
DBMS Questions
KEYS:
Ramesh 22 Ramesh
DBMS Questions
II . SCHEMA :
Table 1 : DEPT
Table 2 : EMP
MGR is the empno of the employee whom the employee reports to. DEPTNO is a foreign key.
QUERIES
1. List all the employees who have at least one person reporting to them.
2. List the employee details if and only if more than 10 employees are present in department no 10.
3. List the name of the employees with their immediate higher authority.
4. List all the employees who do not manage any one.
5. List the employee details whose salary is greater than the lowest salary of an employee belonging to
deptno 20.
6. List the details of the employee earning more than the highest paid manager.
7. List the highest salary paid for each job.
8. Find the most recently hired employee in each department.
9. In which year did most people join the company? Display the year and the number of employees.
10. Which department has the highest annual remuneration bill?
11. Write a query to display a ‘*’ against the row of the most recently hired employee.
12. Write a correlated sub-query to list out the employees who earn more than the average salary of their
department.
13. Find the nth maximum salary.
14. Select the duplicate records (Records, which are inserted, that already exist) in the EMP table.
15. Write a query to list the length of service of the employees (of the form n years and m months).
Ramesh 23 Ramesh
DBMS Questions
KEYS:
Ramesh 24 Ramesh
DBMS Questions
Index Search Add FAQ Ask Question
Ramesh 25 Ramesh
DBMS Questions
PL/SQL and Java appeal to different people in different job roles. The following table briefly describes the difference between
these two language environments:
PL/SQL:
• Data centric and tightly integrated into the database
• Proprietary to Oracle and difficult to port to other database systems
• Data manipulation is slightly faster in PL/SQL than in Java
• Easier to use than Java (depending on your background)
Java:
• Open standard, not proprietary to Oracle
• Incurs some data conversion overhead between the Database and Java type systems
• Java is more difficult to use (depending on your background)
• Back to top of file
How can one search PL/SQL code for a string/ key value?
The following query is handy if you want to know where a certain table, field or expression is referenced in your PL/SQL source
code.
SELECT TYPE, NAME, LINE
FROM USER_SOURCE
WHERE UPPER(TEXT) LIKE '%&KEYWORD%';
• Back to top of file
Ramesh 26 Ramesh
DBMS Questions
WHEN OTHERS THEN
raise_application_error(-20000, SQLERRM);
END;
/
show errors
• Back to top of file
If you forget to set serveroutput on type SET SERVEROUTPUT ON once you remember, and then EXEC NULL;. If you haven't
cleared the DBMS_OUTPUT buffer with the disable or enable procedure, SQL*Plus will display the entire contents of the buffer
when it executes this dummy PL/SQL block.
• Back to top of file
Ramesh 27 Ramesh
DBMS Questions
Can one call DDL statements from PL/SQL?
One can call DDL statements like CREATE, DROP, TRUNCATE, etc. from PL/SQL by using the "EXECUTE IMMEDATE"
statement. Users running Oracle versions below 8i can look at the DBMS_SQL package (see FAQ about Dynamic SQL).
begin
EXECUTE IMMEDIATE 'CREATE TABLE X(A DATE)';
end;
NOTE: The DDL statement in quotes should not be terminated with a semicolon.
• Back to top of file
-- Returning a cursor...
sql_stmt := 'SELECT * FROM emp WHERE empno = :id';
EXECUTE IMMEDIATE sql_stmt INTO emp_rec USING emp_id;
One can also use the older DBMS_SQL package (V2.1 and above) to execute dynamic statements. Look at these examples:
CREATE OR REPLACE PROCEDURE DYNSQL AS
cur integer;
rc integer;
BEGIN
cur := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(cur, 'CREATE TABLE X (Y DATE)', DBMS_SQL.NATIVE);
rc := DBMS_SQL.EXECUTE(cur);
DBMS_SQL.CLOSE_CURSOR(cur);
END;
/
More complex DBMS_SQL example using bind variables:
CREATE OR REPLACE PROCEDURE DEPARTMENTS(NO IN DEPT.DEPTNO%TYPE) AS
v_cursor integer;
v_dname char(20);
v_rows integer;
BEGIN
v_cursor := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(v_cursor, 'select dname from dept where deptno > :x',
DBMS_SQL.V7);
DBMS_SQL.BIND_VARIABLE(v_cursor, ':x', no);
DBMS_SQL.DEFINE_COLUMN_CHAR(v_cursor, 1, v_dname, 20);
v_rows := DBMS_SQL.EXECUTE(v_cursor);
loop
if DBMS_SQL.FETCH_ROWS(v_cursor) = 0 then
exit;
end if;
DBMS_SQL.COLUMN_VALUE_CHAR(v_cursor, 1, v_dname);
DBMS_OUTPUT.PUT_LINE('Deptartment name: '||v_dname);
end loop;
DBMS_SQL.CLOSE_CURSOR(v_cursor);
EXCEPTION
when others then
DBMS_SQL.CLOSE_CURSOR(v_cursor);
raise_application_error(-20000, 'Unknown Exception Raised: '||sqlcode||'
'||sqlerrm);
Ramesh 28 Ramesh
DBMS Questions
END;
/
• Back to top of file
How does one get the value of a sequence into a PL/SQL variable?
As you might know, one cannot use sequences directly from PL/SQL. Oracle (for some silly reason) prohibits this:
i := sq_sequence.NEXTVAL;
However, one can use embedded SQL statements to obtain sequence values:
select sq_sequence.NEXTVAL into :i from dual;
Thanks to Ronald van Woensel
Ramesh 29 Ramesh
DBMS Questions
How does one loop through tables in PL/SQL?
Look at the following nested loop code example.
DECLARE
CURSOR dept_cur IS
SELECT deptno
FROM dept
ORDER BY deptno;
-- Employee cursor all employees for a dept number
CURSOR emp_cur (v_dept_no DEPT.DEPTNO%TYPE) IS
SELECT ename
FROM emp
WHERE deptno = v_dept_no;
BEGIN
FOR dept_rec IN dept_cur LOOP
dbms_output.put_line('Employees in Department
'||TO_CHAR(dept_rec.deptno));
FOR emp_rec in emp_cur(dept_rec.deptno) LOOP
dbms_output.put_line('...Employee is '||emp_rec.ename);
END LOOP;
END LOOP;
END;
/
• Back to top of file
How often should one COMMIT in a PL/SQL loop? / What is the best commit
strategy?
Contrary to popular believe, one should COMMIT less frequently within a PL/SQL loop to prevent ORA-1555 (Snapshot too
old) errors. The higher the frequency of commit, the sooner the extents in the rollback segments will be cleared for new
transactions, causing ORA-1555 errors.
To fix this problem one can easily rewrite code like this:
FOR records IN my_cursor LOOP
...do some stuff...
COMMIT;
END LOOP;
... to ...
FOR records IN my_cursor LOOP
...do some stuff...
i := i+1;
IF mod(i, 10000) THEN -- Commit every 10000 records
COMMIT;
END IF;
END LOOP;
If you still get ORA-1555 errors, contact your DBA to increase the rollback segments.
NOTE: Although fetching across COMMITs work with Oracle, is not supported by the ANSI standard.
• Back to top of file
I can SELECT from SQL*Plus but not from PL/SQL. What is wrong?
PL/SQL respect object privileges given directly to the user, but does not observe privileges given through roles. The consequence
is that a SQL statement can work in SQL*Plus, but will give an error in PL/SQL. Choose one of the following solutions:
• Grant direct access on the tables to your user. Do not use roles!
• GRANT select ON scott.emp TO my_user;
Ramesh 30 Ramesh
DBMS Questions
• Move all the tables to one user/schema.
• Back to top of file
• A row-level trigger cannot query or modify a mutating table. (Of course, NEW and OLD still can be accessed by the
trigger) .
• A statement-level trigger cannot query or modify a mutating table if the trigger is fired as the result of a CASCADE
delete.
• Etc.
• Back to top of file
Ramesh 31 Ramesh
DBMS Questions
• The PL/SQL Cellar - Free Oracle PL/SQL scripts including a bitwise operations package and message digest algorithms
• PLSolutions.com - PL/Solutions provides consulting and training services for the Oracle PL/SQL language and PL/Vision
Ramesh 32 Ramesh
DBMS Questions
How to change UserID and Password in Oracle.
what are differenct types of joins. explain outer join.
How to print output in Oracle.
what is a data control component.
why do we use DBMS ?
what are logical objects in RDBMS (tables & views).
what do you know about IDL?
can we maintain mirror data in different databases.
Data Integrity constraint is
(a)to ensure the presence of primary key
What is indexing in databases?
What is atomicity?
types of DBMS,queries
what is a cursor
types of cursors
normalization
normal forms
what is an os
Types of joins ?
what is a trigger ?
Ramesh 33 Ramesh
DBMS Questions
Ramesh 34 Ramesh
DBMS Questions
for queries that return more than one row, you must declare an
explicit cursor or use
a cursor FOR loop.
Then, you use the FETCH statement to retrieve the first row.
You can execute FETCH repeatedly until all rows have been
retrieved.
DECLARE
CURSOR c1 IS SELECT ename FROM emp;
name1 emp.ename%TYPE;
name2 emp.ename%TYPE;
name3 emp.ename%TYPE;
BEGIN
OPEN c1;
FETCH c1 INTO name1; -- this fetches first row
FETCH c1 INTO name2; -- this fetches second row
FETCH c1 INTO name3; -- this fetches third row
...
CLOSE c1;
END;
what is SGA.
Ramesh 35 Ramesh
DBMS Questions
what are the background processes in oracle.
what are control files.
what are the minimum privilege for the user to connect
database.
what is a role. why do you create it.
Software Engineering
~~~~~~~~~~~~~~~~~~~~
what is waterfall model, prototype model etc.
what is testing. what is unit testing, integration testing
etc.
what are the stages in software project.
(study,analysis,design,development,testing,implementation)
what is done in each stage of the SDLC.
what is the output of analysis stage.
what is er-model.
how do you compare an entity with class or object.
how do you design a project.
Types of Testing ?
what is testing
Ramesh 36 Ramesh
DBMS Questions
Funtional point model
Ramesh 37 Ramesh
DBMS Questions
ORACLE
Doubts :
• WHAT R SYNONYMS AND SEQUENCES IN PL/SQL;
• how can you store a image in the database.
• what do you mean by where current of C1
• LONG RAW data type is used for storing BLOB's (binary large objects).( ie graphics and images)
• what is soundex built in function
• what is to_number, to_char.
Integrity : the quality or state of being complete; unbroken condition; wholeness; entirety .
Consistency : agreement, holding firmly.
Constrain : to force into, or hold in, close bounds
Introduction to Oracle
Oracle is a comprehensive operating environment that packs the power of mainframe relation
database management system into user’s micro computer. It provides a set of functional programs that user
can use as tools to build structures and perform tasks. Because applications are developed on oracle are
completely portable to the other versions of the programmer can create a complex application in a single
user, environment and them move it to a multi user platform.Users do not have to be an expert to appriciate
Oracle but the better user understand the program,the more productively and creatively he can use the tools it
provides
Ramesh 38 Ramesh
DBMS Questions
the part of the application developed,an application developed oracle will be able to keep
pace with growth and change in the world at large.
Oracle Gives You Security and Control
Oracle has several features that ensure the integrity of the data base. If an interruption occurs in
processing, a Rollback can reset the database to a point before the disaster. If a restore is necessary, Oracle
has a Roll forward command for recreating your database to its mast resent save point.
Oracle provides user with several functions for securing data. Grant and Revoke commands limit
access to information down to the row and column levels. Views are valuable feature for limiting access to
the primary tables in the database.
WHY ORACLE ?
Oracle is an open system i.e. the database is accessing by different data access languages
like SQL, Visual Basic, Power Builders,Delphi,VC++,JAVA etc.
Ramesh 39 Ramesh
DBMS Questions
Oracle supports database upto gigabytes in size.
* Oracle supports large number of concurrent users.
* Oracle supports true client/server environment.if enable processing to be spilt between database
server and the client application programs.
* Oracle provides high levelof data security in terms of users, passwords privileges, and permissions.
* Oracle database behaves same on all platform line Windows,Unix,Dos,Mainframes etc.
physical structure:
one or more data files, Two of more log files, One control file.
Logical structure:
Table spaces,
Segments, Extents, Data blocks.
The data files contain all user data in terms of tables, index, and views. The log files contain the
information to open and be recovered, of Undone after a transaction(Rollback).
The control file physical data, media information to open and manage data files .If the control file is
damaged the server will not be able to open are use the database even if the database is undamaged.
What are the Back ground processes in Oracle and what are they. ?
There are basically 9 Processes but in a general system we need to mention the first five background
processes. They do the house keeping activities for the Oracle and are common in any system.
a) Data Base Writer(DBWR) ::
Data Base Writer Writes Modified blocks from Database buffer cache to Data Files.This is required
since the data is not written whenever a transaction is commited.
b)LogWriter(LGWR) ::
LogWriter writes the redo log entries to disk. Redo Log data is generated in redo log buffer of SGA.
As transaction commits and log buffer fills, LGWR writes log entries into a online redo log file.
c) System Monitor(SMON) ::
The System Monitor performs instance recovery at instance startup. This is useful for recovery from
system failure.
d)Process Monitor(PMON) ::
The Process Monitor peforms process recovery when user Process fails. Pmon Clears and Frees
resources that process was using.
e) CheckPoint(CKPT) ::
At Specified times, all modified database buffers in SGA are written to data files by DBWR at
Checkpoints and Updating all data files and control files of database to indicate the
most recent checkpoint.
f)Archieves(ARCH) ::
The Archiver copies online redo log files to archival storal when they are busy.
g) Recoveror(RECO) ::
The Recoveror is used to resolve the distributed transaction in network
h) Dispatcher (Dnnn) ::
The Dispatcher is useful in Multi Threaded Architecture
i) Lckn ::
We can have upto 10 lock processes for inter instance locking in parallel sql.
Ramesh 40 Ramesh
DBMS Questions
NORMALIZATION
Normalization is a process of simplifying the relationship between data elements in a record. Through
Normalization a collection of data in a record structure is replaced by successive record structures that are
simpler and more predictable and therefore more manageable. It is process of reducing redundancy and
eliminating the anomalies. (anamali means inconsistent state.)
There are totally Five Normal Forms(Rules) out of which, any database should necessarily satisfy three of
them, those Three Normal Forms are as follows:
First normal form is achieved when all repeating groups are removed so that a record is of fixed
length. A repeating group, the re-occurrence of a data item within a record, is actually another relation.
Hence, it is removed from the record and treated as an additional record structure, or relation.
Second Normal form should be in first normal form and no partial dependency exists. Means if we
have a composite primary key(combination of 2 or more fields) then all the non keys must depend on the
composite primary key. no attribute should depend upon the part of key.(for example if Rollno and SSno is a
composite key, then no other field in that particular table should be depedent upon either Rollno or ssno
individually)
Third Normal form is achieved when Transitive Dependencies are removed from a record design.
The general case is as follows :
A,B and C are three data items in a record. If C is functionally dependent on B (2nd N.F) and
B is functionally dependent on A Then C is functionally dependent on A Therefore, a Transitive Dependency
exists.
In data management, transitive dependency is a concern because data can inadvertently be lost when
the relationship is hidden. In the general case above, if A is deleted, then B and C are deleted also, whether or
not this is intended. This problem is eliminated by designing the record for third normal form. Conversion to
third normal form removes the transitive dependency by splitting the relation into two separate relations.
BCNF must be 3NF and every determinant is a candidate key. Candidate key is other than primary
key, which uniquely identify each row in the table.
for example ssno is PK then rollno becomes Candidate key.
4NF and 5NF are depends on instance. we can not give a proper def.
bcz it all depends on joins.
“CODD’s 12 RULES" for a fully Relational DBMS
Ramesh 41 Ramesh
DBMS Questions
INTRODUCTION
According to Elmasri and Navathe (1994), Dr. E. F. Codd, the originator of the relational data model,
published a two-part article in ComputerWorld (Codd, 1985) that lists 12 rules for how to determine whether
a DBMS is relational and to what extent it is relational. These rules provide a very useful yardstick for
evaluating a relational system. Codd also mentions that, according to these rules, no fully relational system is
available yet. In particular, rules 6, 9, 10, 11, and 12 are difficult to satisfy.
THE 12 RULES
Ramesh 42 Ramesh
DBMS Questions
On the basis of the above rules, there is no fully relational DBMS available today.
Ramesh 43 Ramesh
DBMS Questions
Ramesh 44 Ramesh
DBMS Questions
Ramesh 45 Ramesh
DBMS Questions
It is a DDL statement It is a DML statement
It is a one way trip,cannot One can Rollback
ROLLBACK
Doesn't have selective features (where clause) Has
Doesn't fire database triggers Does
It requires disabling of referential Does not require
constraints.
What is a view ?
A view is stored procedure based on one or more tables, it’s a virtual table.
What are various privileges that a user can grant to another user ?
SELECT, CONNECT, RESOURCES
Ramesh 46 Ramesh
DBMS Questions
There is a string '120000 12 0 .125' ,how you will find the position of the decimal place ?
INSTR('120000 12 0 .125',1,'.')
output 13
There is a '%' sign in one field of a column. What will be the query to find it ?
'\' Should be used before '%'.
When you use WHERE clause and when you use HAVING clause ?
HAVING clause is used when you want to specify a condition for a group function and it is written
after GROUP BY clause
The WHERE clause is used when you want to specify a condition for columns, single row functions
except group functions and it is written before GROUP BY clause if it is used.
Ramesh 47 Ramesh
DBMS Questions
Suppose customer table is there having different columns like customer no, payments.What will be the
query to select top three max payments ?
SELECT customer_no, payments from customer C1 WHERE 3<=(SELECT COUNT(*) from customer C2
WHERE C1.payment <= C2.payment)
What is a cursor ?
Oracle uses work area to execute SQL statements and store processing information PL/SQL construct called
a cursor lets you name a work area and access its stored information A cursor is a mechanism used to fetch
more than one row in a PL/SQL block.
Difference between an implicit & an explicit cursor ?
PL/SQL declares a cursor implicitly for all SQL data manipulation statements, including quries that
return only one row. However,queries that return more than one row you must declare an explicit cursor or
use a cursor FOR loop.
Explicit cursor is a cursor in which the cursor name is explicitly assigned to a SELECT statement via
the CURSOR...IS statement. An implicit cursor is used for all SQL statements Declare, Open, Fetch, Close.
An explicit cursors are used to process multirow SELECT statements An implicit cursor is used to process
INSERT, UPDATE, DELETE and single row SELECT. .INTO statements.
Ramesh 48 Ramesh
DBMS Questions
END;
What should be the return type for a cursor variable. Can we use a scalar data type as return type ?
The return type for a cursor must be a record type.It can be declared explicitly as a user-defined or
%ROWTYPE can be used. eg TYPE t_studentsref IS REF
CURSOR RETURN students%ROWTYPE
Can cursor variables be stored in PL/SQL tables.If yes how.If not why?
No, a cursor variable points a row which cannot be stored in a two-dimensional PL/SQL table.
Ramesh 49 Ramesh
DBMS Questions
No. A function has to return a value, an OUT parameter cannot return a value.
The prcompiler translates the embedded SQL and pl/sql ststements into calls to the precompiler runtime
library.The output must be compiled and linked with this library to creater an executable.
What is maximum buffer size that can be specified using the DBMS_OUTPUT.ENABLE function?
Ramesh 50 Ramesh
DBMS Questions
1,000,000
What is index ?
INDEX is a general term for an ORACLE / SQL feature used primarily to speed execution an impose
UNIQUENESS upon certain data. INDEX provides a faster access method to one table’s data than doing a
full table scan.
There are several types of Indexes :
UNIQUE INDEX, COMPRESSED INDEX, CONCATENATED INDEX. An Index has an entry for each
value found in the table’s Indexed field(s) ( except those with a NULL value ) and pointer(s) to the rows
having that value.
What is a package ?
A PACKAGE is a PL/SQL object that groups PL/SQL types, variables, SQL cursors,
exceptions,procedures, and functions.Each package has a specification and a body. The specification shows
the object you can access when you use the package. The body fully defines all the objects and can contain
additional objects used only for the internal workings. You can change the body (for example, by adding
procedures to the packages) without invalidating any object that uses the package.
What is Schema ?
A SCHEMA is a collection of objects.
SCHEMA objects are logical structures that directly refer to the database’s data.
SCHEMA objects include structures such as tables, views, synonyms, sequences, indexes, clusters, stored
procedures and data links.
Ramesh 51 Ramesh
DBMS Questions
4. What is SNAPSHOT ? What is a SNAPSHOT LOG ?
A SNAPSHOT is a means of creating a local copy of remote data. A snapshot can be used to
replicate all or part of a single table, or to replicate the result of a query against multiple tables. The refreshes
of the replicated data can be done automatically by the database ( at time intervals you specify ) or
manually.Snapshot Log is the table associated with the Master Table of the Snap shot.
Ramesh 52 Ramesh
DBMS Questions
It is a directive to the COMPILER, rather than a piece of executable code. Eventhough it appears in
the program, it is not executable. It gives instructions to the compiler.
DBMS_OUTPUT package allows you to use 3 debugging functions within your package. You must set
‘SERVER OUTPUT ON’ before executing the procedure object you will be debugging.
PUT - Puts multiple o/p’s on same line.
PUT_LINE - Puts each o/p on a separate line.
NEW_LINE - Used with PUT; Signals the END of current o/p line.
Ramesh 53 Ramesh
DBMS Questions
PRE-QUERY fires ONLY ONCE during EXECUTE-QUERY or COUNT-QUERY processing, just
before Oracle Forms constructs and issues the SELECT statement to identify rows that match the query
criteria.
POST-QUERY fires each time for records placed on the blocks list of records.
41. What is the DIFFERENCE between EXPLICIT CURSOR & IMPLICIT CURSOR ?
IMPLICIT CURSORS are automatically opened by issuing a SELECT statement. But the EXPLICIT
cursors are to be opened using OPEN, fetching is done using FETCH and closing using CLOSE.
Ramesh 54 Ramesh
DBMS Questions
c] Assignment statements such as X := Y +
3. It provides commands for avariety of Z
tasks including :
a] Querying data 2. PL/SQL allows you to logically group a
b] Creating,Updating and Replacing set of statements and send them to the
objects and Inserting, Updating RDBMS as a single block.
and Deleting rows.
4] All RDBMS supports SQL 3. Procedural capabilities.
Thus one can transfer the skills gained 4. Improved performance.
with SQL from one 5. Enhanced productivity
RDBMS to another. 6. Portability
Programs written in SQL are portable,
they can often be moved from one database 7. Integration with the RDBMS.
to another with little modification.
77. What is the purpose of OUTER JOIN ?
An OUTER JOIN returns all the rows returned by simple join as well as those rows from one table
that do not match any row from the other table. The symbol (+) represents the outer join.
Ramesh 55 Ramesh
DBMS Questions
MULTIPLE CHOICE QUESTIONS
11. The purpose of defining an index is
(A) Enhance Sorting Performance (B) Enhance Searching Performance
(C) Achieve Normalization (D) All of the above
13. To group users based on common access permission one should use
(A) User Groups (B) Roles (C) Grants (D) None of the above
15. Which of the constraint can be defined at the table level as well as at the column level
(A) Unique (B) Not Null (C) Check (D) All the above
16. To change the default date format in a SQLPLUS Session you have to
(A) Set the new format in the DATE_FORMAT key in the windows Registry.
(B) Alter session to set NLS_DATE-FORMAT.
(C) Change the Config.ora File for the date base.
(D) Change the User Profile USER-DATE-FORMAT.
17. Which of the following is not necessarily an advantages of using a package rather than independent
stored procedure in data base.
(A) Better performance. (B) Optimized memory usage.
(C) Simplified Security implementation. (D) Encapsulation.
Ramesh 56 Ramesh
DBMS Questions
QUERIES
Where do we use distinct keyword ?
Distinct is used to avoid duplicating records…………………
DELETE
FROM table_name A
WHERE rowid>(SELECT min(rowid) from table_name B where
B.table_no=A.table_no);
DROP old_table
RENAME new_table TO old_table
DELETE FROM table_name A
WHERE rowid NOT IN (SELECT MAX(ROWID) FROM table_name
GROUP BY column_name)
Ramesh 57 Ramesh
DBMS Questions
Guidelines for developers working with Databases
• Should follow the Hungarian Style in naming the Database name (SQL server), Schema
name(Oracle), field/column name in the respective databases.
Example:
EmployeeName ------ Correct
EmpName, empname, emp_name ------ Incorrect
• If the Column/Table name exceeds more than 30 characters the developer can go for abbreviated
names, but it should be completely relevant to the work what the table is doing.
For Example: The ProjectSpecificPreferencesDetails Table can be named ProjSpecPrefDetails, which is
meaningful and also satisfies the field/column’s length.
• Should use the concepts of Stored Procedures (SQL Server), Procedures (Oracle),
Functions, Triggers where ever necessary in the database design Try to avoid unnecessary
connections in the database server in a loop. Using Procedures,
Functions and Triggers solves this problem. Another alternative is to get the whole data into the client
and try to solve the problem in the client level only, instead of interacting with the server for several
times in a loop.
• Should follow the Normalization concepts properly. Try to achieve the Third Normal Form for the
data base which is designed, it is considered to be more efficient.(Normal Forms are discussed below)
• No table in the database should be independent. Every table should be related with one or the other
table.
• Should follow the concept of index in the database. Multiple indexing is advisable if there is an
assumption of storing huge data. Retrieval of data will be faster if indexes are used.
Redundant data wastes disk space and creates maintenance problems. If data that exists in more than one
place must be changed, the data must be changed in exactly the same way in all locations. A customer
address change is much easier to implement if that data is stored only in the Customers table and
nowhere else in the database
First Normal Form
• Eliminate repeating groups in individual tables.
• Create a separate table for each set of related data.
Ramesh 58 Ramesh
DBMS Questions
• Identify each set of related data with a primary key.
Do not use multiple fields in a single table to store similar data. For example, to track an inventory item that
may come from two possible sources, an inventory record may contain fields for Vendor Code 1 and Vendor
Code 2.
But what happens when you add a third vendor? Adding a field is not the answer; it requires program and
table modifications and does not smoothly accommodate a dynamic number of vendors. Instead, place all
vendor information in a separate table called Vendors, then link inventory to vendors with an item number
key, or vendors to inventory with a vendor code key.
Second Normal Form
• Create separate tables for sets of values that apply to multiple records.
• Relate these tables with a foreign key.
Records should not depend on anything other than a table's primary key (a compound key, if necessary). For
example, consider a customer's address in an accounting system. The address is needed by the Customers
table, but also by the Orders, Shipping, Invoices, Accounts Receivable, and Collections tables. Instead of
storing the customer's address as a separate entry in each of these tables, store it in one place, either in the
Customers table or in a separate Addresses table.
Third Normal Form
• Eliminate fields that do not depend on the key.
Values in a record that are not part of that record's key do not belong in the table. In general, any time the
contents of a group of fields may apply to more than a single record in the table, consider placing those
fields in a separate table.
For example, in an Employee Recruitment table, a candidate's university name and address may be
included. But you need a complete list of universities for group mailings. If university information is
stored in the Candidates table, there is no way to list universities with no current candidates. Create a
separate Universities table and link it to the Candidates table with a university code key.
**********************************
Examples of Normalized Tables
**********************************
Normalization Examples:
Unnormalized table:
Tables should have only two dimensions. Since one student has several classes, these classes should
be listed in a separate table. Fields Class1, Class2, & Class3 in the above record are indications of
design trouble.
Ramesh 59 Ramesh
DBMS Questions
Spreadsheets often use the third dimension, but tables should not. Another way to look at this
problem: with a one-to-many relationship, do not put the one side and the many side in the same
table. Instead, create another table in first normal form by eliminating the repeating group (Class#), as
shown below:
Student# Advisor Adv-Room Class#
---------------------------------------
1022 Jones 412 101-07
1022 Jones 412 143-01
1022 Jones 412 159-02
4123 Smith 216 201-01
4123 Smith 216 211-02
4123 Smith 216 214-01
Note the multiple Class# values for each Student# value in the above table. Class# is not functionally
dependent on Student# (primary key), so this relationship is not in second normal form.
In the last example, Adv-Room (the advisor's office number) is functionally dependent on the Advisor
attribute. The solution is to move that attribute from the Students table to the Faculty table, as shown
below:
Students: Student# Advisor
-------------------
1022 Jones
4123 Smith
Jones 412 42
Smith 216 42
Ramesh 60 Ramesh
DBMS Questions
o As the name indicates, denormalization is the reverse process of normalization. It's the
controlled introduction of redundancy in to the database design. It helps improve the query
performance as the number of joins could be reduced.
• How do you implement one-to-one, one-to-many and many-to-many relationships while
designing tables?
o One-to-One relationship can be implemented as a single table and rarely as two tables with
primary and foreign key relationships. One-to-Many relationships are implemented by
splitting the data into two tables with primary key and foreign key relationships. Many-to-
Many relationships are implemented using a junction table with the keys from both the tables
forming the composite primary key of the junction table. It will be a good idea to read up a
database designing fundamentals text book.
• What is bit datatype and what's the information that can be stored inside a bit column?
o Bit datatype is used to store boolean information like 1 or 0 (true or false). Untill SQL Server
6.5 bit datatype could hold either a 1 or 0 and there was no support for NULL. But from SQL
Server 7.0 onwards, bit datatype can represent a third state, which is NULL.
Ramesh 61 Ramesh
DBMS Questions
transaction. For more information and explanation of these properties, see SQL Server books
online or any RDBMS fundamentals text book. Explain different isolation levels An isolation
level determines the degree of isolation of data between concurrent transactions. The default
SQL Server isolation level is Read Committed. Here are the other isolation levels (in the
ascending order of isolation): Read Uncommitted, Read Committed, Repeatable Read,
Serializable. See SQL Server books online for an explanation of the isolation levels. Be sure
to read about SET TRANSACTION ISOLATION LEVEL, which lets you customize the
isolation level at the connection level. Read Committed - A transaction operating at the Read
Committed level cannot see changes made by other transactions until those transactions are
committed. At this level of isolation, dirty reads are not possible but nonrepeatable reads and
phantoms are possible. Read Uncommitted - A transaction operating at the Read
Uncommitted level can see uncommitted changes made by other transactions. At this level of
isolation, dirty reads, nonrepeatable reads, and phantoms are all possible. Repeatable Read - A
transaction operating at the Repeatable Read level is guaranteed not to see any changes made
by other transactions in values it has already read. At this level of isolation, dirty reads and
nonrepeatable reads are not possible but phantoms are possible. Serializable - A transaction
operating at the Serializable level guarantees that all concurrent transactions interact only in
ways that produce the same effect as if each transaction were entirely executed one after the
other. At this isolation level, dirty reads, nonrepeatable reads, and phantoms are not possible.
• CREATE INDEX myIndex ON myTable(myColumn)What type of Index will get created after
executing the above statement?
o Non-clustered index. Important thing to note: By default a clustered index gets created on the
primary key, unless specified otherwise.
• What's the difference between DELETE TABLE and TRUNCATE TABLE commands?
Ramesh 62 Ramesh
DBMS Questions
o DELETE TABLE is a logged operation, so the deletion of each row gets logged in the
transaction log, which makes it slow. TRUNCATE TABLE also deletes all the rows in a
table, but it won't log the deletion of each row, instead it logs the deallocation of the data
pages of the table, which makes it faster. Of course, TRUNCATE TABLE can be rolled back.
TRUNCATE TABLE is functionally identical to DELETE statement with no WHERE clause:
both remove all rows in the table. But TRUNCATE TABLE is faster and uses fewer system
and transaction log resources than DELETE. The DELETE statement removes rows one at a
time and records an entry in the transaction log for each deleted row. TRUNCATE TABLE
removes the data by deallocating the data pages used to store the table's data, and only the
page deallocations are recorded in the transaction log. TRUNCATE TABLE removes all rows
from a table, but the table structure and its columns, constraints, indexes and so on remain.
The counter used by an identity for new rows is reset to the seed for the column. If you want
to retain the identity counter, use DELETE instead. If you want to remove table definition and
its data, use the DROP TABLE statement. You cannot use TRUNCATE TABLE on a table
referenced by a FOREIGN KEY constraint; instead, use DELETE statement without a
WHERE clause. Because TRUNCATE TABLE is not logged, it cannot activate a trigger.
TRUNCATE TABLE may not be used on tables participating in an indexed view
• What are the new features introduced in SQL Server 2000 (or the latest release of SQL Server
at the time of your interview)? What changed between the previous version of SQL Server and
the current version?
o This question is generally asked to see how current is your knowledge. Generally there is a
section in the beginning of the books online titled "What's New", which has all such
information. Of course, reading just that is not enough, you should have tried those things to
better answer the questions. Also check out the section titled "Backward Compatibility" in
books online which talks about the changes that have taken place in the new version.
• What is an index? What are the types of indexes? How many clustered indexes can be created
on a table? I create a separate index on each column of a table. What are the advantages and
disadvantages of this approach?
o Indexes in SQL Server are similar to the indexes in books. They help SQL Server retrieve the
data quicker. Indexes are of two types. Clustered indexes and non-clustered indexes. When
you create a clustered index on a table, all the rows in the table are stored in the order of the
clustered index key. So, there can be only one clustered index per table. Non-clustered
indexes have their own storage separate from the table data storage. Non-clustered indexes are
stored as B-tree structures (so do clustered indexes), with the leaf level nodes having the index
key and it's row locater. The row located could be the RID or the Clustered index key,
Ramesh 63 Ramesh
DBMS Questions
depending up on the absence or presence of clustered index on the table. If you create an
index on each column of a table, it improves the query performance, as the query optimizer
can choose from all the existing indexes to come up with an efficient execution plan. At the
same time, data modification operations (such as INSERT, UPDATE, DELETE) will become
slow, as every time data changes in the table, all the indexes need to be updated. Another
disadvantage is that, indexes need disk space, the more indexes you have, more disk space is
used.
• What are the steps you will take to improve performance of a poor performing query?
o This is a very open ended question and there could be a lot of reasons behind the poor
performance of a query. But some general issues that you could talk about would be: No
indexes, table scans, missing or out of date statistics, blocking, excess recompilations of
stored procedures, procedures and triggers without SET NOCOUNT ON, poorly written query
with unnecessarily complicated joins, too much normalization, excess usage of cursors and
temporary tables. Some of the tools/ways that help you troubleshooting performance problems
are: SET SHOWPLAN_ALL ON, SET SHOWPLAN_TEXT ON, SET STATISTICS IO ON,
SQL Server Profiler, Windows NT /2000 Performance monitor, Graphical execution plan in
Query Analyzer. Download the white paper on performance tuning SQL Server from
Microsoft web site. Don't forget to check out sql-server-performance.com
• What are the steps you will take, if you are tasked with securing an SQL Server?
o Again this is another open ended question. Here are some things you could talk about:
Preferring NT authentication, using server, database and application roles to control access to
the data, securing the physical database files using NTFS permissions, using an unguessable
SA password, restricting physical access to the SQL Server, renaming the Administrator
account on the SQL Server computer, disabling the Guest account, enabling auditing, using
multiprotocol encryption, setting up SSL, setting up firewalls, isolating SQL Server from the
web server etc. Read the white paper on SQL Server security from Microsoft website. Also
check out My SQL Server security best practices
• What is a deadlock and what is a live lock? How will you go about resolving deadlocks?
o Deadlock is a situation when two processes, each having a lock on one piece of data, attempt
to acquire a lock on the other's piece. Each process would wait indefinitely for the other to
release the lock, unless one of the user processes is terminated. SQL Server detects deadlocks
and terminates one user's process. A livelock is one, where a request for an exclusive lock is
repeatedly denied because a series of overlapping shared locks keeps interfering. SQL Server
detects the situation after four denials and refuses further shared locks. A livelock also occurs
when read transactions monopolize a table or page, forcing a write transaction to wait
indefinitely. Check out SET DEADLOCK_PRIORITY and "Minimizing Deadlocks" in SQL
Server books online. Also check out the article Q169960 from Microsoft knowledge base.
Ramesh 64 Ramesh
DBMS Questions
• What is blocking and how would you troubleshoot it?
o Blocking happens when one connection from an application holds a lock and a second
connection requires a conflicting lock type. This forces the second connection to wait, blocked
on the first. Read up the following topics in SQL Server books online: Understanding and
avoiding blocking, Coding efficient transactions. Explain CREATE DATABASE syntax
Many of us are used to creating databases from the Enterprise Manager or by just issuing the
command: CREATE DATABAE MyDB.
• But what if you have to create a database with two filegroups, one on drive C and the other on
drive D with log on drive E with an initial size of 600 MB and with a growth factor of 15%?
o That's why being a DBA you should be familiar with the CREATE DATABASE syntax.
Check out SQL Server books online for more information.
• How to restart SQL Server in single user mode? How to start SQL Server in minimal
configuration mode?
o SQL Server can be started from command line, using the SQLSERVR.EXE. This EXE has
some very important parameters with which a DBA should be familiar with. –m is used for
starting SQL Server in single user mode and -f is used to start the SQL Server in minimal
configuration mode. Check out SQL Server books online for more parameters and their
explanations.
• As a part of your job, what are the DBCC commands that you commonly use for database
maintenance?
o DBCC CHECKDB, DBCC CHECKTABLE, DBCC CHECKCATALOG, DBCC
CHECKALLOC, DBCC SHOWCONTIG, DBCC SHRINKDATABASE, DBCC
SHRINKFILE etc. But there are a whole load of DBCC commands which are very useful for
DBAs. Check out SQL Server books online for more information.
• What are statistics, under what circumstances they go out of date, how do you update them?
o Statistics determine the selectivity of the indexes. If an indexed column has unique values
then the selectivity of that index is more, as opposed to an index with non-unique values.
Query optimizer uses these indexes in determining whether to choose an index or not while
executing a query. Some situations under which you should update statistics: 1) If there is
significant change in the key values in the index 2) If a large amount of data in an indexed
column has been added, changed, or removed (that is, if the distribution of key values has
changed), or the table has been truncated using the TRUNCATE TABLE statement and then
repopulated 3) Database is upgraded from a previous version. Look up SQL Server books
online for the following commands: UPDATE STATISTICS, STATS_DATE, DBCC
SHOW_STATISTICS, CREATE STATISTICS, DROP STATISTICS, sp_autostats,
sp_createstats, sp_updatestats
• What are the different ways of moving data/databases between servers and databases in SQL
Server?
o There are lots of options available, you have to choose your option depending upon your
requirements. Some of the options you have are: BACKUP/RESTORE, dettaching and
Ramesh 65 Ramesh
DBMS Questions
attaching databases, replication, DTS, BCP, logshipping, INSERT...SELECT,
SELECT...INTO, creating INSERT scripts to generate data.
• Explain different types of BACKUPs avaialabe in SQL Server? Given a particular scenario,
how would you go about choosing a backup plan?
o Types of backups you can create in SQL Sever 7.0+ are Full database backup, differential
database backup, transaction log backup, filegroup backup. Check out the BACKUP and
RESTORE commands in SQL Server books online. Be prepared to write the commands in
your interview. Books online also has information on detailed backup/restore architecture and
when one should go for a particular kind of backup.
• What is database replication? What are the different types of replication you can set up in SQL
Server?
o Replication is the process of copying/moving data between databases on the same or different
servers. SQL Server supports the following types of replication scenarios: · Snapshot
replication · Transactional replication (with immediate updating subscribers, with queued
updating subscribers) · Merge replication See SQL Server books online for indepth coverage
on replication. Be prepared to explain how different replication agents function, what are the
main system tables used in replication etc.
• How to determine the service pack currently installed on SQL Server?
o The global variable @@Version stores the build number of the sqlservr.exe, which is used to
determine the service pack installed. To know more about this process visit SQL Server
service packs and versions.
• What are cursors? Explain different types of cursors. What are the disadvantages of cursors?
How can you avoid cursors?
o Cursors allow row-by-row processing of the resultsets. Types of cursors: Static, Dynamic,
Forward-only, Keyset-driven. See books online for more information. Disadvantages of
cursors: Each time you fetch a row from the cursor, it results in a network roundtrip, where as
a normal SELECT query makes only one roundtrip, however large the resultset is. Cursors are
also costly because they require more resources and temporary storage (results in more IO
operations). Further, there are restrictions on the SELECT statements that can be used with
some types of cursors. Most of the times, set based operations can be used instead of cursors.
Here is an example: If you have to give a flat hike to your employees using the following
criteria: Salary between 30000 and 40000 -- 5000 hike Salary between 40000 and 55000 --
7000 hike Salary between 55000 and 65000 -- 9000 hike. In this situation many developers
tend to use a cursor, determine each employee's salary and update his salary according to the
above formula. But the same can be achieved by multiple update statements or can be
combined in a single UPDATE statement as shown below:
o UPDATE tbl_emp SET salary = CASE WHEN salary BETWEEN 30000 AND 40000 THEN
salary + 5000 WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000 WHEN
salary BETWEEN 55000 AND 65000 THEN salary + 10000 END
o Another situation in which developers tend to use cursors: You need to call a stored procedure
when a column in a particular row meets certain condition. You don't have to use cursors for
Ramesh 66 Ramesh
DBMS Questions
this. This can be achieved using WHILE loop, as long as there is a unique key to identify each
row. For examples of using WHILE loop for row by row processing, check out the 'My code
library' section of my site or search for WHILE. Write down the general syntax for a SELECT
statements covering all the options. Here's the basic syntax: (Also checkout SELECT in books
online for advanced syntax).
o SELECT select_list [INTO new_table_] FROM table_source [WHERE search_condition]
[GROUP BY group_by_expression] [HAVING search_condition] [ORDER BY
order_expression [ASC | DESC] ]
• What is a join and explain different types of joins.
o Joins are used in queries to explain how different tables are related. Joins also let you select
data from a table depending upon data from another table. Types of joins: INNER JOINs,
OUTER JOINs, CROSS JOINs. OUTER JOINs are further classified as LEFT OUTER
JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS. For more information see pages
from books online titled: "Join Fundamentals" and "Using Joins".
• What is an extended stored procedure? Can you instantiate a COM object by using T-SQL?
o An extended stored procedure is a function within a DLL (written in a programming language
like C, C++ using Open Data Services (ODS) API) that can be called from T-SQL, just the
way we call normal stored procedures using the EXEC statement. See books online to learn
how to create extended stored procedures and how to add them to SQL Server. Yes, you can
instantiate a COM (written in languages like VB, VC++) object from T-SQL by using
sp_OACreate stored procedure. Also see books online for sp_OAMethod, sp_OAGetProperty,
sp_OASetProperty, sp_OADestroy. For an example of creating a COM object in VB and
calling it from T-SQL, see 'My code library' section of this site.
• What is the system function to get the current user's user id?
o USER_ID(). Also check out other system functions like USER_NAME(), SYSTEM_USER,
SESSION_USER, CURRENT_USER, USER, SUSER_SID(), HOST_NAME().
• What are triggers? How many triggers you can have on a table? How to invoke a trigger on
demand?
o Triggers are special kind of stored procedures that get executed automatically when an
INSERT, UPDATE or DELETE operation takes place on a table. In SQL Server 6.5 you
could define only 3 triggers per table, one for INSERT, one for UPDATE and one for
DELETE. From SQL Server 7.0 onwards, this restriction is gone, and you could create
multiple triggers per each action. But in 7.0 there's no way to control the order in which the
triggers fire. In SQL Server 2000 you could specify which trigger fires first or fires last using
sp_settriggerorder. Triggers can't be invoked on demand. They get triggered only when an
associated action (INSERT, UPDATE, DELETE) happens on the table on which they are
defined. Triggers are generally used to implement business rules, auditing. Triggers can also
Ramesh 67 Ramesh
DBMS Questions
be used to extend the referential integrity checks, but wherever possible, use constraints for
this purpose, instead of triggers, as constraints are much faster. Till SQL Server 7.0, triggers
fire only after the data modification operation happens. So in a way, they are called post
triggers. But in SQL Server 2000 you could create pre triggers also. Search SQL Server 2000
books online for INSTEAD OF triggers. Also check out books online for 'inserted table',
'deleted table' and COLUMNS_UPDATED()
• There is a trigger defined for INSERT operations on a table, in an OLTP system. The trigger is
written to instantiate a COM object and pass the newly insterted rows to it for some custom
processing. What do you think of this implementation? Can this be implemented better?
o Instantiating COM objects is a time consuming process and since you are doing it from within
a trigger, it slows down the data insertion process. Same is the case with sending emails from
triggers. This scenario can be better implemented by logging all the necessary data into a
separate table, and have a job which periodically checks this table and does the needful.
Ramesh 68 Ramesh
DBMS Questions
Ramesh 69 Ramesh
DBMS Questions
• How might you quantitatively measure an improvement made to a query?
• Why might the optimiser use a table scan when an index is available?
• How can you force the optimiser to use a particular index?
Ramesh 70 Ramesh
DBMS Questions
DBMS-1 Questions
1)____________is statement that is executed automatically by the system
as a side effect of a modification of a database.
A) Assertion
B) Trigger
C)cursor
D) None
Ans: B
A) Data model
B) ER model
D) None
Ans: A
A) Database design
B) Instance
C) Schema
D) None
Ans: C
A) 2NF
B) BCNF
C) 3NF
D) 1NF
Ans: B
Ramesh 71 Ramesh
DBMS Questions
A) Super key
B) Candidate key
C) Primary key
D) None
Ans: A
A) Shared
B) Exclusive
C) Both
D) None
Ans: C
A) Physical level
B) Logical level
C) View level
D) None
Ans: C
A) Candidate key
B) Primary key
C) Alternate key
D) None
Ans: C
A) RAID level 0
B) RAID level 1
C) RAID level 2
Ramesh 72 Ramesh
DBMS Questions
D) RAID level 3
Ans: B
A) Repetition of information
C) Only A
D) Both
Ans: D
A) 1
B) 2
C) 3
D) None
Ans: A
A) Candidate key
B) Composite key
C) Alternate key
D) None
Ans: B
A) Procedural
B) Non procedural
C) Structured
D) None
Ans: B
A) Cardinality ratio
B) Mapping cardinalities
Ramesh 73 Ramesh
DBMS Questions
C) Both
D) None
Ans: C
Attribute
Entity
C) Object
D) None
Ans: A
A) 3
B) 2
C) 1
D) None
Ans: B
17)__________ is the time from when a read or write request is issued to when
data transfer begins.
B) Access time
C) Latency time
D) None
Ans: B
18) The property ‘Either all operations of the transaction are reflected
properly in the database’ refers to
A) Durability
B) Atomicity
Ramesh 74 Ramesh
DBMS Questions
C) Isolation
D) None
Ans: B
A) Aborted
B) Committed
C) Partially commited
D) Failed
Ans: B
A) Growing
B) Shrinking
C) Both
D) None
Ans: C
21.Given two union compatible relations R1(A,B) and R2(C,D)
what is the result of the operation R1 A=C AB=D R2 ?
a.R1 U R2 b. R1 ^ R2 c.R1 - R2 d.R1 * R2
Ans:B
Ramesh 75 Ramesh
DBMS Questions
Ans:C
32.SQL is relationally?
a. complete language b.incomplete language
c.Cant handle certain relations d.Sound language
Ans:A
34.In SQL relations can contain null values, and comparisons with null values
are treated as unknown suppose all comparisons with a null value are
treated as false. Which of the following pairs is not equivalent?
a.x=5 not (not(x=5)) b.x=5 x>4 and x<6, where x is an integer
c.x!=5 and not(x=5) d. none
Ans:C
Ramesh 76 Ramesh
DBMS Questions
35.Relation R is decomposed using a set of functional dependencies F,
and relation S is decomposed using another set of functional
dependencies, G.One decomposition is definitely BCNF, the other is
definitely 3NF, but it is not know which is which. To make
guaranteed identification, which one of the following tests
should be used on the decompositions?
(Assume the closure of F and G are available)
a.Dependency-preservation b.Lossless-Join
c.BCNF definition d.3NF definition
Ans:B
37.The level of abstraction describes only part of the entries database is called
a.Physical level b.Conceptual level c.View level d.Procedural level
Ans:C
Ramesh 77 Ramesh
DBMS Questions
a.Physical level b.Logical level c.View level d.None
Ans:A
51.Extend DML
a.Data Multiple Language b.Data Manipulation Language
c.Data Multiplex Language d.Data Model Language
Ans:B
Ramesh 78 Ramesh
DBMS Questions
54.The domain of attribute must include only atomic
(simple, indivisible) values in
a.1 NF b.2 NF c.3 NF d.4NF
Ans:A
56.Advantages of DBMS?
a.Redundancy is controlled b.Enforcing integrity constraints.
c.Data isolation. d.Both Redundancy is controlled & Enforces integrity constraints
Ans:D
DBMS-2 Questions
1) What is a query?
Exp: A query with respect to DBMS relates to user commands that are used
to interact with a data base. The query language can be classified into data
definition language and data manipulation language..
Ramesh 79 Ramesh
DBMS Questions
Exp: :Subqueries, or nested queries, are used to bring back a set of rows to
be used by the parent query. Depending on how the subquery is written, it can be
executed once for the parent query or it can be executed once for each row returned
by the parent query. If the subquery is executed for each row of the parent, this
is called a correlated subquery.A correlated subquery can be easily identified if
it contains any references to the parent subquery columns in its WHERE clause.
Columns from the subquery cannot be referenced anywhere else in the parent query.
The following example demonstrates a non-correlated subquery.
Ans :
1. Analysis phase
2. Redo Phase
3. Undo phase
4)What are the primitive operations common to all record management systems?
5)Name the buffer in which all the commands that are typed in are stored.?
7)Are the resulting relations of PRODUCT and JOIN operation the same?
Ans :No.
Exp:PRODUCT: Concatenation of every row in one relation with every row in another.
JOIN: Concatenation of rows from one relation and related rows from another..
Ramesh 80 Ramesh
DBMS Questions
Lock Management.
Ans :Two important pieces of RDBMS architecture are the kernel, which is the s
oftware, 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.
Ans :Data dictionary is a set of tables and database objects that is stored in a
special area of the database and maintained exclusively by the kernel..
Ans :The information in the data dictionary validates the existence of the objects,
provides access to them, and maps the actual physical storage location
Ans :You communicate with an RDBMS using Structured Query Language (SQL).
13)Define SQL and state the differences between SQL and other conventional programming
Languages ?
Ans :SQL is a nonprocedural language that is designed specifically for data access
operations on normalized relational database structures. The primary difference between
SQL and other conventional programming languages is that SQL statements specify what
data operations should be performed rather than how to perform them. .
14)Name the three major set of files on disk that compose a database in Oracle?
Ans:There are three major sets of files on disk that compose a database. All the
files are binary.
1. Database files
2. Control files
3. Redo logs
Exp:The most important of these are the database files where the actual data resides.
The control files and the redo logs support the functioning of the architecture
itself. All three sets of files must be present, open, and available to Oracle for
any data on the database to be useable. Without these files, you cannot access the
database, and the database administrator might have to recover some or all of the
database using a backup, if there is one..
Ramesh 81 Ramesh
DBMS Questions
15)What are the four Oracle system processes that must always be up and running
for the database to be useable ?
Ans :The four Oracle system processes that must always be up and running for the
database to be useable include
1. DBWR (Database Writer)
2. LGWR (Log Writer)
3. SMON (System Monitor)
4. PMON (Process Monitor).
Ans :A database trigger is a PL/SQL block that can defined to automatically execute
for insert, update, and delete statements against a table. The trigger can e defined
to execute once for the entire statement or once for every row that is inserted,
updated, or deleted. For any one table, there are twelve events for which you can
define database triggers. A database trigger can call database procedures that
are also written in PL/SQL. .
17)Name two utilities that Oracle provides, which are use for backup and recovery.
Ans :1. The Export utility dumps the definitions and data for the specified part
of the database to an operating system binary file.
2. The Import utility reads the file produced by an export, recreates the
definitions of objects, and inserts the data.
Exp::Stored procedures are database objects that perform a user defined operation.
A stored procedure can have a set of compound SQL statements. A stored procedure
executes the SQL commands and returns the result to the client. Stored procedures
are used to reduce network traffic..
Ans :Bad normalization & Updating tables from join because theta joins are joins
made on keys that are not primary keys..
Ans :It is a program module that provides the interface between the low-level
data stored in database, application programs and queries submitted to the system.
Ans :It is a program module, which is responsible for fetching data from disk
storage into main memory and deciding what data to be cache in memory. .
Ramesh 82 Ramesh
DBMS Questions
22) What is Transaction Manager?
Ans :It is a program module, which ensures that database, remains in a consistent
state despite system failures and concurrent transaction execution proceeds
without conflicting
Ans :It is a program module, which manages the allocation of space on disk
storage and data structure used to represent information stored on a disk.
Ans :It is the program module, which tests for the satisfaction of integrity
constraint and checks the authority of user to access data..
Exp::Procedures that are not part of a package are known as stand-alone because
they independently defined. A good example of a stand-alone procedure is one
written in a SQL*Forms application. These types of procedures are not available
for reference from other Oracle tools. Another limitation of stand-alone procedures
is that they are compiled at run time, which slows execution..
Ans :PL/SQL uses cursors for all database information accesses statements.
The language supports the use two types of cursors
1. Implicit
2. Explicit.
Ans :Given a relation R and a set of FDs F, dependency preservation states that
the closure of the union of the projection of F on each decomposed relation Ri is
equal to the closure of F. i.e., ((?R1(F)) U … U (?Rn(F)))+ = F+ if decomposition
is not dependency preserving, then some dependency is lost in the decomposition..
Exp:Proactive Update: The updates that are applied to database before it becomes
effective in real world .
Retroactive Update: The updates that are applied to database after it becomes
effective in real world .
Simulatneous Update: The updates that are applied to database at the same time
when it becomes effective in real world ..
Ramesh 83 Ramesh
DBMS Questions
Ans :LIKE operator.
Ans :START or @.
32)What is the parameter substitution symbol used with INSERT INTO command?
Ans :&.
33)Which command displays the SQL command in the SQL buffer, and then executes it?
Ans :RUN.
Ans :True.
36)State true or false. !=, <>, ^= all denote the same operation.?
Ans :True.
37)What are the privileges that can be granted on a table by a user to others?
Ans :Insert, update, delete, select, references, index, execute, alter, all.
38)What command is used to get back the privileges offered by the GRANT command?
Ans :REVOKE.
Ramesh 84 Ramesh
DBMS Questions
Ans :TRUNCATE is a DDL command whereas DELETE is a DML command. Hence DELETE
operation can be rolled back, but TRUNCATE operation cannot be rolled back.
WHERE clause can be used with DELETE and not with TRUNCATE
41) What command is used to create a table by copying the structure of another table?
Ans :TROUBLETHETROUBLE
Ans :NO
Explanation : The query checks whether a given string is a numerical digit..
44) What does the following query do? SELECT SAL + NVL(COMM,0) FROM EMP;?
Ans :This displays the total salary of all employees. The null values in the
commission column will be replaced by 0 and added to salary..
45) Which date function is used to find the difference between two dates?
Ans :MONTHS_BETWEEN.
46) Why does the following command give a compilation error? DROP TABLE &TABLE_NAME
Ans :Variable names should start with an alphabet. Here the table name starts
with an '&' symbol
47) What is the advantage of specifying WITH GRANT OPTION in the GRANT command?
Ans :The privilege receiver can further grant the privileges he/she has obtained
from the owner to any other user
48) What is the use of the DROP option in the ALTER TABLE command?
Ramesh 85 Ramesh
DBMS Questions
Ans :DESC has two purposes. It is used to describe a schema as well as to retrieve
rows from table in descending order.
Explanation : The query SELECT * FROM EMP ORDER BY ENAME DESC will
display the output sorted on ENAME in descending order..
Ans :When this clause is used with the DROP command, a parent table can be
dropped even when a child table exists..
51) Which function is used to find the largest integer less than or equal to
a specific value?
Ans :FLOOR.
52) What is the output of the following query? SELECT TRUNC(1234.5678,-2) FROM DUAL;
Ans :1200.
Ramesh 86 Ramesh