SQL Lab Manual For Practicals
SQL Lab Manual For Practicals
EXP I. INTRODUCTION
Oracle has many tools such as SQL * PLUS, Oracle Forms, Oracle Report Writer, Oracle Graphics etc.
SQL * PLUS: The SQL * PLUS tool is made up of two distinct parts. These
are
Interactive SQL: Interactive SQL is designed for create, access
and manipulate data structures like tables and indexes.
PL/SQL: PL/SQL can be used to developed programs for different
applications.
Oracle Forms: This tool allows you to create a data entry screen along
with the suitable menu objects. Thus it is the oracle forms tool that
handles data gathering and data validation in a commercial application.
Report Writer: Report writer allows programmers to prepare innovative
reports using data from the oracle structures like tables, views etc. It is
the report writer tool that handles the reporting section of commercial
application.
Oracle Graphics: Some of the data can be better represented in the
form of pictures. The oracle graphics tool allows programmers to prepare
graphs using data from oracle structures like tables, views etc.
SQL (Structured Query Language):
Structured Query Language is a database computer language designed for
managing data in relational database management systems(RDBMS), and
originally based upon Relational Algebra. Its scope includes data query and
update, schema creation and modification, and data access control. SQL was
one of the first languages for Edgar F. Codd's relational model in his influential
1970 paper, "A Relational Model of Data for Large Shared Data Banks"[3] and
became the most widely used language for relational databases.
IBM developed SQL in mid of 1970’s.
Oracle incorporated in the year 1979.
SQL used by IBM/DB2 and DS Database Systems.
SQL adopted as standard language for RDBS by ASNI in 1989.
DATA TYPES:
CHAR (Size): This data type is used to store character strings values of fixed
length. The size in brackets determines the number of characters the cell can
hold. The maximum number of character is 255 characters.
1. VARCHAR (Size) / VERCHAR2 (Size): This data type is used to store
variable length alphanumeric data. The maximum character can hold is
2000 character.
2. NUMBER (P, S): The NUMBER data type is used to store number (fixed or
floating point). Number of virtually any magnitude may be stored up to 38
Predicates which specify conditions that can be evaluated to SQL three-valued logic (3VL) Boolean
truth values and which are used to limit the effects of statements and queries, or to change program
flow.
Queries which retrieve data based on specific criteria.
Statements which may have a persistent effect on schemas and data, or which may control
transactions, program flow, connections, sessions, or diagnostics.
SQL statements also include the semicolon (";") statement terminator. Though not required on every
platform, it is defined as a standard part of the SQL grammar.
Insignificant white space is generally ignored in SQL statements and queries, making it easier to
format SQL code for readability.
There are five types of SQL statements. They are:
1. DATA DEFINITION LANGUAGE (DDL)
2. DATA MANIPULATION LANGUAGE (DML)
3. DATA RETRIEVAL LANGUAGE (DRL)
4. TRANSATIONAL CONTROL LANGUAGE (TCL)
5. DATA CONTROL LANGUAGE (DCL)
1. DATA DEFINITION LANGUAGE (DDL): The Data Definition Language (DDL) is used to
create and destroy databases and database objects. These commands will primarily be used by database
administrators during the setup and removal phases of a database project. Let's take a look at the structure
and usage of four basic DDL commands:
1. CREATE 2. ALTER 3. DROP 4. RENAME
1. CREATE:
(a)CREATE TABLE: This is used to create a new relation and the
corresponding
Syntax: CREATE TABLE relation_name
(field_1 data_type(Size),field_2 data_type(Size), .. . );
Example:
SQL>CREATE TABLE Student (sno NUMBER(3),sname CHAR(10),class
CHAR(5));
(b)CREATE TABLE..AS SELECT....: This is used to create the structure of a
new relation from the structure of an existing relation.
Syntax: CREATE TABLE (relation_name_1, field_1,field_2,.....field_n) AS
SELECT field_1,field_2,...........field_n FROM relation_name_2;
WHERE field_name=data;
Example: SQL>UPDATE student SET sname = ‘kumar’ WHERE sno=1;
3. DELETE-FROM: This is used to delete all the records of a relation but it will
retain the structure of that relation.
a) DELETE-FROM: This is used to delete all the records of relation.
Syntax: SQL>DELETE FROM relation_name;
Example: SQL>DELETE FROM std;
b) DELETE -FROM-WHERE: This is used to delete a selected record from a
relation.
Syntax: SQL>DELETE FROM relation_name WHERE condition;
Example: SQL>DELETE FROM student WHERE sno = 2;
3. DRL(DATA RETRIEVAL LANGUAGE): Retrieves data from one or more tables.
1. SELECT FROM: To display all fields for all records.
Syntax : SELECT * FROM relation_name;
Example : SQL> select * from dept;
DEPTNO DNAME LOC
-------- ----------- ----------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
2. SELECT FROM: To display a set of fields for all records of relation.
Syntax: SELECT a set of fields FROM relation_name;
Example: SQL> select deptno, dname from dept;
DEPTNO DNAME
------- ----------
10 ACCOUNTING
20 RESEARCH
30 SALES
3. SELECT - FROM -WHERE: This query is used to display a selected set of
fields for a selected set of records of a relation.
Syntax: SELECT a set of fields FROM relation_name WHERE condition;
Example: SQL> select * FROM dept WHERE deptno<=20;
2 ravi
3 ramu
1. COMMIT: This command is used to end a transaction only with the help of
the commit command transaction changes can be made permanent to the
database.
Syntax: SQL>COMMIT;
Example: SQL>COMMIT;
2. SAVE POINT: Save points are like marks to divide a very lengthy
transaction to smaller once. They are used to identify a point in a transaction to
which we can latter role back. Thus, save point is used in conjunction with role
back.
Example:
SQL>CREATE TABLE Student (sno NUMBER(3) PRIMARY KEY ,sname
CHAR(10),class CHAR(5));
2. ALTER:
(a)ALTER TABLE ...ADD...: This is used to add some extra fields into existing
relation.
3. CHECK: Specifies a condition that each row in the table must satisfy. To
satisfy the constraint, each row in the table must make the condition either
TRUE or unknown (due to a null).
Syntax:
CREATE TABLE Table_Name(column_name data_type(size) CHECK(logical
expression), ….);
Example: CREATE TABLE student (sno NUMBER (3), name CHAR(10),class
CHAR(5),CHECK(class IN(‘CSE’,’CAD’,’VLSI’));
4. PRIMARY KEY: A field which is used to identify a record uniquely. A column
or combination of columns can be created as primary key, which can be used
as a reference from other tables. A table contains primary key is known as
Master Table.
It must uniquely identify each record in a table.
It must contain unique values.
It cannot be a null field.
It cannot be multi port field.
It should contain a minimum no. of fields necessary to be called unique.
Syntax:
CREATE TABLE Table_Name(column_name data_type(size) PRIMARY KEY,
….);
Example:
CREATE TABLE faculty (fcode NUMBER(3) PRIMARY KEY, fname
CHAR(10));
5. FOREIGN KEY: It is a table level constraint. We cannot add this at column
level. To reference any primary key column from other table this constraint can
be used. The table in which the foreign key is defined is called a detail table.
The table that defines the primary key and is referenced by the foreign key is
called the master table.
Syntax: CREATE TABLE Table_Name(column_name data_type(size)
FOREIGN KEY(column_name) REFERENCES table_name);
Example:
CREATE TABLE subject (scode NUMBER (3) PRIMARY KEY,
subname CHAR(10),fcode NUMBER(3),
3. AVG: AVG followed by a column name returns the average value of that
column values.
Syntax: AVG (n1,n2..)
Example: Select AVG(10, 15, 30) FROM DUAL;
4. MAX: MAX followed by a column name returns the maximum value of that
column.
Syntax: MAX (Column name)
Example: SELECT MAX (Sal) FROM emp;
SQL> select deptno,max(sal) from emp group by deptno;
DEPTNO MAX(SAL)
------ --------
10 5000
20 3000
30 2850
SQL> select deptno,max(sal) from emp group by deptno having
max(sal)<3000;
DEPTNO MAX(SAL)
----- --------
30 2850
5. MIN: MIN followed by column name returns the minimum value of that
column.
Syntax: MIN (Column name)
Example: SELECT MIN (Sal) FROM emp;
SQL>select deptno,min(sal) from emp group by deptno having min(sal)>1000;
DEPTNO MIN(SAL)
----- --------
10 1300
VIEW: In SQL, a view is a virtual table based on the result-set of an SQL
statement.
A view contains rows and columns, just like a real table. The fields in a
view are fields from one or more real tables in the database.
You can add SQL functions, WHERE, and JOIN statements to a view and
present the data as if the data were coming from one single table.
1. Conversion functions:
To_char: TO_CHAR (number) converts n to a value of VARCHAR2 data type,
using the optional number format fmt. The value n can be of
type NUMBER, BINARY_FLOAT, or BINARY_DOUBLE.
SQL>select to_char(65,'RN')from dual;
LXV
To_number : TO_NUMBER converts expr to a value of NUMBER data type.
SQL> Select to_number('1234.64') from Dual;
1234.64
To_date: TO_DATE converts char of CHAR, VARCHAR2, NCHAR,
or NVARCHAR2 data type to a value of DATE data type.
SQL>SELECT TO_DATE('January 15, 1989, 11:00 A.M.')FROM DUAL;
TO_DATE('
---------
15-JAN-89
2. String functions:
Concat: CONCAT returns char1 concatenated with char2.
Both char1 and char2 can be any of the datatypes
SQL>SELECT CONCAT(‘ORACLE’,’CORPORATION’)FROM DUAL;
ORACLECORPORATION
Lpad: LPAD returns expr1, left-padded to length n characters with the
sequence of characters in expr2.
SQL>SELECT LPAD(‘ORACLE’,15,’*’)FROM DUAL;
*********ORACLE
Rpad: RPAD returns expr1, right-padded to length n characters with expr2,
replicated as many times as necessary.
SQL>SELECT RPAD (‘ORACLE’,15,’*’)FROM DUAL;
ORACLE*********
Ltrim: Returns a character expression after removing leading blanks.
SQL>SELECT LTRIM(‘SSMITHSS’,’S’)FROM DUAL;
MITHSS
Rtrim: Returns a character string after truncating all trailing blanks
SQL>SELECT RTRIM(‘SSMITHSS’,’S’)FROM DUAL;
SSMITH
Lower: Returns a character expression after converting uppercase character data to lowercase.
SQL>SELECT LOWER(‘DBMS’)FROM DUAL;
dbms
Upper: Returns a character expression with lowercase character data converted to uppercase
SQL>SELECT UPPER(‘dbms’)FROM DUAL;
DBMS
Length: Returns the number of characters, rather than the number of bytes, of the given string
expression, excluding trailing blanks.
SQL>SELECT LENGTH(‘DATABASE’)FROM DUAL;
8
Substr: Returns part of a character, binary, text, or image expression.
SQL>SELECT SUBSTR(‘ABCDEFGHIJ’3,4)FROM DUAL;
CDEF
Instr: The INSTR functions search string for substring. The function returns an
integer indicating the position of the character in string that is the first
character of this occurrence.
SQL>SELECT INSTR('CORPORATE FLOOR','OR',3,2)FROM DUAL;
14
3. Date functions:
Sysdate:
SQL>SELECT SYSDATE FROM DUAL;
29-DEC-08
next_day:
SQL>SELECT NEXT_DAY(SYSDATE,’WED’)FROM DUAL;
05-JAN-09
add_months:
SQL>SELECT ADD_MONTHS(SYSDATE,2)FROM DUAL;
28-FEB-09
last_day:
SQL>SELECT LAST_DAY(SYSDATE)FROM DUAL;
31-DEC-08
months_between:
SQL>SELECT MONTHS_BETWEEN(SYSDATE,HIREDATE)FROM EMP;
4
Least:
SQL>SELECT LEAST('10-JAN-07','12-OCT-07')FROM DUAL;
10-JAN-07
Greatest:
SQL>SELECT GREATEST('10-JAN-07','12-OCT-07')FROM DUAL;
10-JAN-07
Trunc:
SQL>SELECT TRUNC(SYSDATE,'DAY')FROM DUAL;
28-DEC-08
Round:
SQL>SELECT ROUND(SYSDATE,'DAY')FROM DUAL;
28-DEC-08
to_char:
SQL> select to_char(sysdate,
"dd\mm\yy") from dual;
24-mar-05.
to_date:
SQL> select to_date(sysdate, "dd\mm\yy") from dual;
24-mar-o5.
1) Create table EMPLOYEE with the following attributes and then insert the
following data in to EMPLOYEE table.
2. Create table DEPARTMENT with the following attributes and then insert the
following data into DEPARTMENT table.
3. Create table DEPT_LOCATIONS with the following attributes and insert the
following data into DEPT_LOCATIONS table.
DNUMBER DLOCATION
---------------------------------------------
1 Houston
4 Stafford
5 Bellaire
5 Sugarland
5 Houston
Ans: Create table dept_locations( dnumber number(7),dlocation
varchar2(15));
4.Create table PROJECT with the following attributes and insert the following
data into PROJECT table.
5.Create table DEPENDENT with the following attributes and insert the
following data into DEPENDENT table.
6. Create table WORKS_ON with the following attributes and then insert the
following data into WORKS_ON table.
(Or)
Alter Table Employee add Primary key (ssn);
c) Simple queries:
SQL> select empno, ename,job from emp where job =’CLERK’ and
deptno=30;
SQL>Select ename,sal from emp where sal between 2000 and 3000;
SQL>select ename,round(months_between(sysdate,hiredate)/12)exp
from emp where round (months_between(sysdate,hiredate)/12)>24;
26.List employee names and their joining date in the folloeing formats
D.SMITH 17/12/80
29. List employee names with length of the names sorted on length.
32.List employee names and the string with out first character and
last character in their name.
37.List employee names and dept names with which they are
associated.
1)Between,And:
2)Like:
2. Write a query to retrieve all employees who were born during the 1950s
.SQL> select * from employee where bdate like '%5_';
4) NOT:
SQL> /
FNAME SALARY
--------------- ----------
Ramesh 38000
James 55000
Jennifer 43000
John 30000
Joyce 25000
Franklin 40000
Ahmad 25000
7 rows selected.
John 30000
Joyce 25000
Ramesh 38000
5 rows selected.
F) Renaming attributes:
1) Rename Employee table to Employees?
A) Rename Employee to Employees;
G) Delete command:
Delete from employees where ssn=123456789;
3. To delete a column
Alter table dept drop column dspl;
Table altered
Table deleted.
J) SQL FUNCTIONS:
These functions are used to manipulating data items and returning the results.
1. Group functions or Aggregate functions.
2. Single Row or scalar function.
Group functions or Aggregate functions:
These functions operated a set of values or rows
i. Sum()
ii. Avg()
iii. Min()
iv. Max()
v. Count()
Sum():used to find out the sum of the salary of employees.
Ex:List the sum of the salary of employees
Select sum(sal) from emp;
Avg():it find out the average salaries of employees.
Ex:List the average salary of the employees
Select avg(sal) from emp;
Min():used to find out the minimum salary of an employee in the given table.
Ex:list out the minimum salary of an employee in the emp table.
Select min(sal) from emp;
Max():used to find out the maximum salary of an employee in the given table.
Ex:list out the maxiimum salary of an employee in the emp table.
Select max(sal) from emp;
Count():used to list out the number of values in a particular table.
Ex:
1.List the numbers of jobs.
select count (job) from emp;
2.List the numbers of people and average salary in deptno 30.
select count(*),avg(sal) from emp where deptno=30;
In these function we are using date functions also there are listed below:
Select months_between(’26-jun-06’,’25-may-06’) from dual;
MONTHS_BETWEEN('26-JUN-09','25-MAY-09')
1.03225806
Select add_months('26-jun-06',5') from dual;
ADD_MONTH
26-NOV-06
Select next_day('26-jun-09','monday') from dual;
NEXT_DAY(
29-JUN-09
Select last_day('26-jun-09') from dual;
LAST_DAY(
30-JUN-09
1. Write a query to retrieve name and address of all employees who work
for the ‘Research’ department.
FNAME ADDRESS
--------------- ------------------------------
John 731 fondren, Houston, TX
Joyce 6531 Rice, Houston, TX
Ramesh 975, Fire Oak, Humble, TX
Franklin 638 Voss, Houston, TX
2. Write a query to retrieve employee’s first and last name and first and last
name of his or her immediate supervisor.
8 rows selected.
NOTE: + is specified in above using ‘outer join’ to an attribute in join
condition where we don’t have null value.
Ex: ssn don’t have null value but superssn has. So, I gave (+) to ssn.
3. Write a query to retrieve list of employees and the projects they are
working on, ordered by department and with in each department, ordered
alphabetically by last name, first name.
SQL>select e.ssn,e.fname,e.lname,w.pno,e.dno from employee e,works_on w
where e.ssn=w.essn order by dno,fname,lname;
SSN FNAME LNAME PNO DNO
--------- --------------- --------------- --------- ---------
888665555 James Borg 20 1
987987987 Ahmad Jabbar 10 4
987987987 Ahmad Jabbar 30 4
999887777 Alicia Zelaya 30 4
999887777 Alicia Zelaya 10 4
987654321 Jennifer Wallace 30 4
987654321 Jennifer Wallace 20 4
333445555 Franklin Wong 2 5
333445555 Franklin Wong 3 5
333445555 Franklin Wong 10 5
333445555 Franklin Wong 20 5
123456789 John Smith 1 5
123456789 John Smith 2 5
453453453 Joyce English 1 5
16 rows selected.
4. For every project located in ‘Stafford’, list the project number, the
controlling department number and the department manager’s last name, birth
date.
SQL>select p.pnumber,p.dnum,e.lname,e.bdate from employee e,department
d,project p where p.plocation='Stafford' and p.dnum=d.dnumber and
d.mgrssn=e.ssn
30 4 Wallace 20-JUN-41
5. Find the sum of the salaries of all employees, the maximum salary, the
minimum salary and the average salary.
SQL> select sum(salary),max(salary),min(salary),avg(salary) from employee
6. Find the sum of the salaries of all employees, the maximum salary, the
minimum salary and the average salary of all employees of the ‘Research’
department.
SQL>select sum(salary),max(salary),min(salary),avg(salary) from employee
e,department d where d.dname='Research' and d.dnumber=e.dno
COUNT(*)
---------
4
8. For each department, retrieve the department number, the number of
employees in the department and their average salary.
1 1 55000
4 3 31000
5 4 33250 count(*) also works
9. For each project, retrieve the project number, Project name and the
number of employees who work on that project.
SQL>select pno,pname,count(pno) "Employees working" from project
p,works_on w where p.pnumber=w.pno group by pno,pname
PNO PNAME Employees working
--------- --------------- -----------------
1 ProductX 2
2 ProductY 3
3 ProductZ 2
10 Computerization 3
20 Reorganization 3
30 Newbenefits 3
6 rows selected.
10. For each project on which more than two employees work, retrieve the
project number, project name and the number of employees who work on the
project.
SQL>select pno,pname,count(pno) from project p,works_on w where
p.pnumber=w.pno group by pno,pname having count(pno)>2
1. Write a nested query to retrieve the name of each employee who has a
dependent with the same first name and same sex as the employee.
A. SQL>select fname from employee e1 where ssn in ( select ssn from
dependant d
where e1.fname=d.dependent_name and e1.sex=d.sex and
e1.ssn=d.essn)
output:
no rows selected
2. [Using exists]
A . SQL>select fname from employee e1 where exists ( select ssn from
dependant d
where e1.fname=d.dependent_name and e1.sex=d.sex and
e1.ssn=d.essn)
OUTPUT:
No rows selected
3. Write a query to show resulting salaries if every employee working on
‘ProductX’ project is given a 10 percent raise.
A . SQL> select ssn,salary+.1*salary "10 % raise of salary" from employee
where ssn in ( select essn
from works_on w
where pno in (select pnumber
from project
where pname='ProductX'));
OUTPUT:
SSN 10 % raise of salary
--------- --------------------
123456789 33000
453453453 27500
4. For each department that has more than two employees, retrieve the
department number and the number of its employees who are making
more than or equal to $30,000.
6. Write a nested query to list the names of managers who have at least
one dependent.
A . SQL> select fname from employee,department where mgrssn=ssn
and exists( select * from dependant where mgrssn=essn)
OUTPUT:
FNAME
---------------
Franklin
Jennifer
7. Write a nested query to retrieve the names of all employees who have
two or more dependents.
A: SQL>
select fname from employee where ssn in( select essn from dependant
where essn=ssn group by(essn) having count(*)>2)
OUTPUT:
FNAME
---------------
John
Franklin
8. Write a nested query to retrieve the SSNs of all employees who work on
project number 1, 2 or 3.
A: SQL>
select ssn from employee where ssn in( select distinct essn from works_on
where pno in(1,2,3))
OUTPUT:
SSN
---------
123456789
333445555
453453453
666884444
NOTE: ‘distinct’ may or mayn’t be present
9. Write a nested query to retrieve the names of all employees whose salary
is greater than the salary of all the employees in department 5.
A: SQL> select fname from employee where salary > all (select salary
from employee
where dno=5)
OUTPUT:
FNAME
---------------
Jennifer
James
Note: while doing nested queries consider the output as inner and apply
conditions one by one with each condition satisfying in one condition.
OUTPUT:
PNUMBER
----------
1
2
3
OUTPUT:
SSN
---------
123456789
453453453
3. Write a query to retrieve the names of employee who worked on all the
projects controlled by department 5.
SQL>
4. Without using a nested query, retrieve the names of employees who
have no dependents.
SQL> select fname from employee e where e.ssn in ((select ssn from
employee) MINUS (select distinct essn from dependant))
OUTPUT:
FNAME
---------------
Joyce
Ramesh
James
Ahmad
Alicia
SNO SNAME
---- ------
1 kumar
2 ravi
3 ramu
5 lalitha
9 devi
SNO SNAME
---- ------
1 kumar
2 ravi
3 ramu
5 lalitha
9 devi
SNO SNAME
---- -------
1 Kumar
SNO SNAME
---- -------
2 RAVI
3 RAMU
DATA DEFINITION LANGUAGE (DDL): The Data Definition Language (DDL) is used to create
and destroy databases and database objects. These commands will primarily be used by database
administrators during the setup and removal phases of a database project. Let's take a look at the structure
and usage of four basic DDL commands:
1. CREATE 2. ALTER 3. DROP 4. RENAME
1. CREATE:
(a)CREATE TABLE: This is used to create a new relation and the
corresponding
Syntax: CREATE TABLE relation_name
(field_1 data_type(Size),field_2 data_type(Size), .. . );
Example:
SQL>CREATE TABLE Student (sno NUMBER(3),sname CHAR(10),class
CHAR(5));
2. ALTER:
(a)ALTER TABLE ...ADD...: This is used to add some extra fields into existing
relation.
Syntax: ALTER TABLE relation_name ADD(new field_1 data_type(size), new
field_2 data_type(size),..);
Example : SQL>ALTER TABLE std ADD(Address CHAR(10));
(B) By using delete command data will be removed based on the condition
where as by using truncate command there is no condition.
(C) Truncate is a DDL command & delete is a DML command.
1. COMMIT: This command is used to end a transaction only with the help of
the commit command transaction changes can be made permanent to the
database.
Syntax: SQL>COMMIT;
Example: SQL>COMMIT;
2. SAVE POINT: Save points are like marks to divide a very lengthy
transaction to smaller once. They are used to identify a point in a transaction to
which we can latter role back. Thus, save point is used in conjunction with role
back.
3. ROLE BACK: A role back command is used to undo the current transactions.
We can role back the entire transaction so that all changes made by SQL
statements are undo (or) role back a transaction to a save point so that the
SQL statements after the save point are role back.
2. REVOKE: To with draw the privileges that has been GRANTED to a uses, we
use the REVOKE command
View created.
SQL> SELECT * FROM EMPLOYEE;
EMPNO ENAME JOB
---- ------ -------
7369 SMITH CLERK
7876 ADAMS CLERK
7900 JAMES CLERK
7934 MILLER CLERK
2.Example:
CREATE VIEW [Current Product List] AS
SELECT ProductID,ProductName
FROM Products
WHERE Discontinued=No
DROP VIEW: This query is used to delete a view , which has been already
created.
Syntax: DROP VIEW View_name;
Example : SQL> DROP VIEW EMPLOYEE;
View dropped
PL/SQL stands for Procedural Language extension of SQL. PL/SQL is a combination of SQL
along with the procedural features of programming languages. It was developed by Oracle Corporation in the
early 90’s to enhance the capabilities of SQL.
Oracle uses a PL/SQL engine to processes the PL/SQL statements. A PL/SQL code can be stored in
the client system (client-side) or in the database (server-side).
Advantages of PL/SQL:
Block Structures: PL SQL consists of blocks of code, which can be nested within each other. Each
block forms a unit of a task or a logical module. PL/SQL Blocks can be stored in the database and
reused.
Procedural Language Capability: PL SQL consists of procedural language constructs such as
conditional statements (if else statements) and loops like (FOR loops).
Better Performance: PL SQL engine processes multiple SQL statements simultaneously as a single
block, thereby reducing network traffic.
Error Handling: PL/SQL handles errors or exceptions effectively during the execution of a PL/SQL
program. Once an exception is caught, specific actions can be taken depending upon the type of the
exception or it can be displayed to the user with a message.
Syntax of PL/SQL program:
Declare
Variable declaration;
Begin
Executable statements;
end;
Conditional Statements in PL/SQL
As the name implies, PL/SQL supports programming language features like conditional statements,
iterative statements.
The programming constructs are similar to how you use in programming languages like Java and C+
+. In this section I will provide you syntax of how to use conditional statements in PL/SQL programming.
IF THEN ELSE STATEMENT:
1) IF condition THEN
Statement 1;
ELSE
Statement 2;
END IF;
2) IF condition 1 THEN
Statement 1;
Statement 2;
ELSIF condtion2 THEN
Statement 3;
ELSE
Statement 4;
END IF
Loops in PL/SQL
There are three types of loops in PL/SQL:
1. Simple Loop
2. While Loop
3. For Loop
1. Simple Loop: A Simple Loop is used when a set of statements is to be executed at least once before the
loop terminates. An EXIT condition must be specified in the loop, otherwise the loop will get into an infinite
number of iterations. When the EXIT condition is satisfied the process exits from the loop.
Syntax: LOOP
Statements;
EXIT;
{or EXIT WHEN condition ;}
END LOOP;
2. While Loop: A WHILE LOOP is used when a set of statements has to be executed as long as a condition is
true. The condition is evaluated at the beginning of each iteration. The iteration continues until the
condition becomes false.
Syntax: WHILE <condition>
LOOP statements;
END LOOP;
3. FOR Loop: A FOR LOOP is used to execute a set of statements for a predetermined number of times.
Iteration occurs between the start and end integer values given. The counter is always incremented by 1.
The loop exits when the counter reaches the value of the end integer.
Syntax:
FOR counter IN val1..val2
LOOP statements;
END LOOP;
BEGIN
FOR I IN 1..100 LOOP
IF MOD(I,2)=0 THEN
DBMS_OUTPUT.PUT_LINE(I);
END IF;
END LOOP;
END;
/
Output:
END IF;
END IF;
END;
/
Output:
BEGIN
T:=&T;
FOR I IN 1..3 LOOP
DBMS_OUTPUT.PUT_LINE(T||'X'||I||'='||I*T);
END LOOP;
END;
/
Output:
IF PR=1 THEN
DBMS_OUTPUT.PUT_LINE('THE GIVEN NUMBER IS PRIME'||N);
ELSE
DBMS_OUTPUT.PUT_LINE('THE GIVEN NO IS NOT PRIME'||N);
END IF;
END;
/
Output:
7) Write PL/SQL code to accept the text and reverse the text and
test whether the given character is Palandrome or not.
DECLARE
G VARCHAR2(20);
R VARCHAR2(20);
BEGIN
G:='&G';
DBMS_OUTPUT.PUT_LINE('THE GIVEN TEXT :'||G);
A NUMBER;
REV NUMBER;
D NUMBER;
BEGIN
A:=&A;
REV:=0;
WHILE A>0
LOOP
D:=MOD(A,10);
REV:=(REV * 10) + D;
A:=TRUNC(A/10);
END LOOP;
DBMS_OUTPUT.PUT_LINE('NO IS'||REV);
END;
/
Output:
DECLARE
A NUMBER;
B NUMBER;
C NUMBER;
N NUMBER;
I NUMBER;
BEGIN
N:=&N;
A:=0;
B:=1;
DBMS_OUTPUT.PUT_LINE(A);
DBMS_OUTPUT.PUT_LINE(B);
FOR I IN 1..N-2
LOOP
C:=A+B;
DBMS_OUTPUT.PUT_LINE(C);
A:=B;
B:=C;
C:=A+B;
END LOOP;
END;
/
Output:
IF B=I THEN
DBMS_OUTPUT.PUT_LINE(I||'IS ARMSTRONG NUMBER');
END IF;
END LOOP;
END;
/
Output:
DBMS_OUTPUT.PUT_LINE('');
END LOOP;
END;
/
Output:
12) Write PL/SQL code to print the numbers in this form 00000
123
45
246
8 10
DECLARE
I NUMBER;
J NUMBER;
K NUMBER;
BEGIN
FOR I IN 0..5 LOOP
1
DECLARE
I NUMBER;
J NUMBER;
K NUMBER;
M NUMBER;
N NUMBER;
BEGIN
N:=&N;
FOR I IN 1..N LOOP
FOR J IN 1..N-I LOOP
DBMS_OUTPUT.PUT('~');
END LOOP;
FOR K IN 1..I LOOP
DBMS_OUTPUT.PUT(K);
END LOOP;
FOR K IN REVERSE 1..I-1 LOOP
DBMS_OUTPUT.PUT(K);
END LOOP;
DBMS_OUTPUT.PUT_LINE('');
END LOOP;
FOR I IN REVERSE 1..N-1 LOOP
FOR J IN 1..N-I LOOP
DBMS_OUTPUT.PUT('~');
END LOOP;
FOR K IN 1..I LOOP
DBMS_OUTPUT.PUT(K);
END LOOP;
FOR K IN REVERSE 1..I-1 LOOP
DBMS_OUTPUT.PUT(K);
END LOOP;
DBMS_OUTPUT.PUT_LINE('');
END LOOP;
END;
/
Output:
/
Output:
DECLARE
VAR_ROWS NUMBER(5);
BEGIN
UPDATE EMP SET SAL=SAL+100;
IF SQL%NOTFOUND THEN
DBMS_OUTPUT.PUT_LINE('NONE OF THE SALARIES WERE UPDATED');
ELSE IF SQL%FOUND THEN
VAR_ROWS:=SQL%ROWCOUNT;
DBMS_OUTPUT.PUT_LINE('SALARIES FOR'||VAR_ROWS||'EMPLOYEES ARE
UPDATED');
END IF ;
END IF;
END;
/
Output:
FOR DEPT IN D
LOOP
DBMS_OUTPUT.PUT_LINE('DEPARTMENT NUMBER'|| DEPT.DEPTNO);
DBMS_OUTPUT.PUT_LINE('...........');
FOR EMP IN E(DEPT.DEPTNO)
LOOP
DBMS_OUTPUT.PUT_LINE('MR'||' '||EMP.ENAME||' '|| 'IS WORKING
IN DEPARTMENT '||DEPT.DNAME||' '|| 'AT'||' '||DEPT.LOC||' AS ' ||
EMP.JOB);
END LOOP;
END LOOP;
END;
/
Output:
B) DECLARE
CURSOR C_EMPLOYEE IS
SELECT EMPNO,ENAME,JOB,SAL,DEPTNO FROM EMP WHERE
EMPNO=7839;
V_EMPLOYEEDATA C_EMPLOYEE%ROWTYPE;
BEGIN
OPEN C_EMPLOYEE;
FETCH C_EMPLOYEE INTO V_EMPLOYEEDATA;
WHILE C_EMPLOYEE%FOUND LOOP
DBMS_OUTPUT.PUT_LINE(V_EMPLOYEEDATA.ENAME||'
'||V_EMPLOYEEDATA.EMPNO||'
'||V_EMPLOYEEDATA.SAL);
FETCH C_EMPLOYEE INTO V_EMPLOYEEDATA;
END LOOP;
CLOSE C_EMPLOYEE;
COMMIT;
END;
/
Output:
DECLARE
cursor c(jb varchar2) is select ename from emp where job=jb;
em emp.job%type;
BEGIN
open c('MANAGER');
dbms_output.put_line(' EMPLOYEES WORKING AS MANAGERS
ARE:');
loop
fetch c into em;
exit when c%notfound;
dbms_output.put_line(em);
end loop;
close c;
open c('ANALYST');
dbms_output.put_line(' EMPLOYEES WORKING AS ANALYST ARE:');
loop
fetch c into em;
exit when c%notfound;
dbms_output.put_line(em);
end loop;
close c;
END;
/
Output:
/
Output:
b) DECLARE
X NUMBER(4):=&X;
Y NUMBER;
BEGIN
FACT(X,Y);
PROCEDURE DEFINITION:
CREATE or REPLACE PROCEDURE isprimepro(num in number,chec out number)
IS
temp NUMBER;
BEGIN
temp:=num;
FOR itr IN 2..(num-1)
LOOP
IF(mod(num,itr)=0) THEN
chec:=1;
END IF;
END LOOP;
END;
/
PL/SQL BLOCK TO CALL THE PROCEDURE:
DECLARE
chec NUMBER;
given_number NUMBER;
BEGIN
given_number:=&given_number;
isprimepro(given_number,chec);
IF chec=1 THEN
dbms_output.put_line('number is not prime');
ELSE
dbms_output.put_line('number is prime');
END IF;
END;
/
Output:
end if;
dbms_output.put_line(a||' '||c||' '||b||' ='||d);
exception
when ex then
dbms_output.put_line('not a valid operator');
when zero_divide then
dbms_output.put_line('denominatar should not be zero');
when others then
dbms_output.put_line('sql error');
end;
/
Output:
Functions:
FUNCTION DEFINITION :
CREATE or REPLACE FUNCTION isprime(num in number) RETURN
number IS
temp NUMBER;
BEGIN
temp:=num;
FOR itr IN 2..(num-1)
LOOP
IF (mod(temp,itr)=0) THEN
return 1;
END IF;
END LOOP;
return 0;
END;
/
PL/SQL BLOCK TO CALL THE FUNCTION:
DECLARE
given_number NUMBER;
prime_check NUMBER;
BEGIN
given_number:=&given_number;
prime_check:=isprime(given_number);
IF prime_check=0 THEN
dbms_output.put_line('NUMBER IS PRIME');
ELSE
dbms_output.put_line('NUMBER IS NOT PRIME');
END IF;
END;
/
Output:
end;
/
(b) set serveroutput on;
Declare
n number(2):=&n;
r number(4);
Begin
r:=FunFact(n);
dbms_output.put_line('factorial of'||n||'is:'||r);
end;
/
Output:
IF M IS NULL THEN
RAISE MYERROR;
END IF;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('ERROR OF DATA');
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('ERROR OF TOO MANY ROWS');
WHEN MYERROR THEN
DBMS_OUTPUT.PUT_LINE('ERROR FOUND NULL');
END;
/
Output:
(ii) Triggers
1) Write pl/sql code for before insert Trigger program
Steps for doing Trigger Program
a. First create a table called Person(Don’t insert any values into created
table)
b.Write code for Trigger and run the trigger program
c.Insert values into the created table after sucessfully completion of trigger
program and see the trigger output.
(a) CREATE TABLE PERSON1(ID INTEGER,NAME VARCHAR2(30),DOB
DATE,PRIMARY
KEY(ID));
(b) CREATE OR REPLACE TRIGGER PERSON_INSERT_BEFORE
BEFORE INSERT ON PERSON1 FOR EACH ROW
BEGIN
DBMS_OUTPUT.PUT_LINE('BEFORE INSERT OF'||:NEW.NAME);
END;
/
(c) INSERT INTO PERSON1 VALUES(1,’JOHN DOE’,SYSDATE);
Output:
DECLARE
CURSOR C IS SELECT * FROM ANI;
BEGIN
FOR I IN C
LOOP
IF I.EMPNO=:NEW.EMPNO THEN
RAISE_APPLICATION_ERROR(-2009,'EMPNO ALREADY EXISTS');
END IF;
END LOOP;
END;
/
Output:
8. Write pl/sql code using Trigger to salary with more than old
salary.
CREATE OR REPLACE TRIGGER SALUPDATE9
BEFORE UPDATE ON C FOR EACH ROW
BEGIN
IF :NEW.SAL<:OLD.SAL THEN
Output:
1. What is RDBMS?
Ans. Relational Data Base Management system is system software that stores and
Ans. An integrity constraint is a rule that restricts the values for one or more columns in a
table.
Unique Key.
1.It doesn’t allow DUPLICATE value but you can insert any no. of
NULL values
Ans.
2. Allocating system storage and planning future storage requirements for the
database system
4. Creating primary objects (tables, views, indexes) once application developers have
designed an application
application developers
5. What is SGA?
Ans.System Global Area or Shared Global Area is a group of shared memory structures
that contain data and control information for one instance. If multiple users are
concurrently connected to the same instance, the data in the instance's SGA is
6. What is instance?
Ans.The combination of the SGA and the Oracle processes (Background Process) is
Ans.The database buffer cache is a portion of the SGA that holds copies of the data blocks
read from data files. It will maintain two list Least-Recently-Used list (LRU) and
Ans.The redo log buffer is a circular buffer in the SGA that holds information about
Ans.The shared pool is an area in the SGA that contains three major areas: library cache,
LOG_BUFFERS
Ans.A private SQL area is a memory area that contains data such as bind information and
runtime buffers. A private SQL area has a persistent area and a runtime area.
Ans.The data dictionary is a collection of database tables and views containing reference
information about the database, its structures, and its users. It will maintain the
following information
14. What are DBWR, LGWR, PMON, SMON, RECO, CKPT, Dnnn and ARCH?
buffers to datafiles
LGWR - Log Writer process (LGWR) writes the redo log buffer to a redo log file
on disk
PMON – Process Monitor (PMON) performs process recovery when a user process
fails. PMON is responsible for cleaning up the cache and freeing resources (Lock)
start up. SMON is also responsible for cleaning up temporary segments; it also
RECO - Recoverer process (RECO) is a process used with the distributed option that
transactions also.
CKPT - When a checkpoint occurs, Oracle must update the header of all data files to
Dnnn - Dispatcher processes allow user processes to share a limited number of server
processes.
ARCH - Archiver process (ARCH) copies online redo log files to a designated storage
device once they become full. ARCH is present only when the redo log is used in
Ans.When a checkpoint occurs, Oracle must update the headers of all datafiles to indicate
the checkpoint. If you are not enabled CKPT using CHECKPOINT_PROCESS, this
16. Is checkpoint optional? Then which one will take care of ckpt is not present?
17. Which background process you can have more than in an instance?
Ans.Dnnn. You can create multiple dispatcher processes for a single database instance.
18. When the data buffer will be flushed into respective files?
Ans.The parameter file is a text file that contains a list of parameters and a value for each
parameter. This file will read in the NOMOUNT stage. The default parameter file
20. Which parameter can’t be changed after the init file has been set?
Ans.DB_BLOCK_SIZE. If you want change the block size you have to recreate the
database.
Ans.a) Create the parameter file say INITTEST.ORA made the needful changes
f) After created the database, run two scripts CATALOG.SQL and CATPROC.sql to
Ans.One or More Data files, Two or more Log files and one or more Control files.
Segments.)
Checkpoint information
v$archive)
Ans.Program Global Area (PGA) is a memory buffer that contains data and control
information for a server process. A PGA is created by Oracle when a server process is
started.
Ans. A database is divided into one or more logical storage units called tablespaces.
A database administrator can create new tablespaces, add and remove datafiles from
tablespaces, set and alter default segment storage settings for segments created in a
NAME WITH PATH’ SIZE 100M;(size can be in terms of kb,mb,gb and etc).
b) Index segments(Index)
c) Rollback segments
d) Temporary segments
e) Bootstrap segments.
NAME> STORAGE
(INITIAL 2
MINEXTENTS 121
MAXEXTENTS 10240
NEXT 10240
PCT_INCREASE 0);
Ans.Shrink:
Using this parameter, you can manually decrease the size of a rollback
Eg.
Optimal:
Using this parameter, you can decrease the size of a rollback segment
Automatically. This parameter you can specify either Create or Alter statement for
rollback segments.
Eg.
3. Instance recovery
Ans.When processing queries with ORDER BY, DISTINCT, GROUP BY, UNION, and
INTERSECT clause and creating index, oracle requires temporary workspace for
Ans.i) When you want to take a tablespace offline and the tablespace contains
segments from being used, you can take them offline before taking the tablespace
offline.
ii). You want to drop a rollback segment, but cannot because transactions are
currently using it. To prevent the rollback segment from being used, you can take it
Syntax.
Ans.Deferred rollback segments are rollback segments that were created to hold
rollback entries for tablespaces taken offline until the tablespaces are brought back
online.
Ans.If you try to take a rollback segment offline that contains rollback data for active
A Public rollback segments form a pool of rollback segments that any instance
Ans.Rollback :
Rolling forward:
While performing Instance recovery rolling forward will take place for
37. When system tablespace and system rollback segment will be made offline?
Ans.System tablespace and system rollback segments can’t make offline. Because system
transactions and data dictionary views will take place in the system rollback segments
Ans.The extents will grow based on the storage parameters like next and pctincrease i.e.
Next (next*(pctincrease/100)).
Ans.Row migration is, If a row in a data block is updated, so that the overall row length
increases and the block's free space has been completely filled, the data for the entire
row is migrated to a new data block, assuming the entire row can fit in a new block.
Row chaining is Oracle stores the data for the row in a chain of data blocks (one or
more) reserved for that segment. Row chaining most often occurs with large rows.
does not consider the block for the insertion of new rows until the percentage of the
free) for possible updates to rows that already are contained in that block.
Ans.Specifies the number of free lists for each of the free list groups for the table,
cluster, or index. The default and minimum value for this parameter is 1, meaning that
Ans.Maxdatafiles - Specifies the maximum number of data files that can ever be created
Maxlogfiles - Specifies the maximum number of redo log file groups that can ever
Maxloghistory - Specifies the maximum number of archived redo log files for
Ans.Oracle assigns new log sequence number every time that a log switch occurs and
from the redo log buffer of the SGA to an online redo log file, and a system change
number (SCN) is assigned to identify the redo entries for each committed transaction.
Ans.The point at which Oracle ends writing to one online redo log file and begins writing
A log switch always occurs when the current online redoes log file is completely
filled and writing must continue to the next online redo log file.
Ans.Oracle provides the capability to mirroring an instance's online redo log files to
safeguard against damage to its online redo log files. With mirroring online redo log
files, LGWR concurrently writes the same redo log information to multiple identical
Ans.A snapshot is a table that contains the results of a query of one or more tables or
views, often located on a remote database. Simply you can say Image of table.
Ans.Because a snapshot's master tables can be modified, the data in a snapshot must
occasionally be updated to ensure that the snapshot accurately reflects the data
currently in its master tables. The process of updating a snapshot for this purpose
You can use the FAST or COMPLETE options of the REFRESH clause to specify the
refresh mode.
Ans.This can happen when the database has many transactions that are changing data, then
committing or rolling back. The rollback data can be overwritten if the rollback
segments are too small for the number and size of the changes being made.
Ans.General types are exclusive locks and share locks. But further classifications are
Ans.A deadlock is a situation that can occur in multi-user systems that prevents some
transactions from continuing work. A deadlock can occur when two or more users are
distributed transaction either all commit or all roll back the transaction, thus
Ans.Striping" is the practice of dividing a large table's data into small portions and
storing these portions in separate datafiles on separate disks. This permits multiple
contention.
IDENTIFIED BY <p.word>
Ans.Connect, resource and dba are default roles which are created by oracle automatically.
CREATE CLUSTER
CREATE SEQUENCE
CREATE SESSION
CREATE SYNONYM
CREATE VIEW
CREATE PROCEDURE
CREATE SEQUENCE
Ans.A role is a set of privileges that can be granted to users or to other roles.
Syntax.
Ans.Object privileges. Because with admin option only for system privileges.
Ans.If you revoke an object privilege from a user who has granted the privilege to
other users or roles, Oracle7 also revokes the privilege from the grantees.
containing this information like user performing the operation, type of operation,
65. What is object audit, how to enable it and where will you see the result?
Ans.To audit all successful and unsuccessful DELETE statements on the EMP table,
66. What is statement audit, how to enable it and where will you see the result?
from the database BY SESSION (the default and only value for this option), enter the
following statement:
67. What is privilege audit, how to enable it and where will you see the result?
Ans.To audit all unsuccessful SELECT, INSERT, and DELETE statements on all
tables and unsuccessful uses of the EXECUTE ANY PROCEDURE system privilege,
Ans.Audit_trail=true
Ans.AUD$ table
Ans.When you run a database in ARCHIVELOG mode, the archiving of the online
redo log is enabled. Information in a database control file indicates that a group of
filled online redo log files cannot be used by LGWR until the group is archived.
71. How to change from noarchivelog to archivelog? Explain all the steps.
Steps:
b. Start up a new instance and mount but do not open the database.
72. How to change from archivelog to noarchivelog? Explain all the steps.
Steps:
f. Start up a new instance and mount but do not open the database.
Ans.To enable automatic archiving of filled groups each time an instance is started,
parameter file:
LOG_ARCHIVE_START=TRUE
STARTUP MOUNT - You might want to start an instance and mount a database,
but not open the database because you want to perform renaming datafiles, Adding
, dropping, or renaming redo log files, enabling and disabling redo log archiving
Ans.You might want to start an instance, and mount and open a database in restricted
mode so that the database is available only to administrative personnel who are
Ans.You can usually solve the problem by starting a new instance (and optionally
mounting and opening the database) using startup force. A database instance should
not be forced to start unless you are faced instance startup problem.
Ans.SVRMGR>SHUTDOWN;
b). Before the database is shut down, Oracle7 waits for all currently connected
c). The next startup of the database will not require any instance recovery
Procedures.
Ans.SVRMGR>SHUTDOWN IMMEDIATE;
a). Current client SQL statements being processed by Oracle7 are terminated
Immediately.
c). Oracle7 does not wait for users currently connected to the database to
Ans.Aborting an instance shuts down a database and yields the following results:
a). Current client SQL statements being processed by Oracle7 are immediately
Terminated.
c). Oracle7 does not wait for users currently connected to the database to
Ans.The pathname for a directory where the server will write debugging user trace
Ans.Dedicated server - The separate server process created on behalf of each user is a
MTS - The multi-threaded server configuration eliminates the need for a dedicated
server process for each connection. A single server process may provide service to
Ans.SQL*Net is Oracle Corporation's latest remote data access software. It enables both
databases and their applications can reside on different computers and communicate
as peer applications.
different tables that are stored together in the same cluster can have the same
ROWID.
Ans.Backups of the database's datafiles and control files are absolutely necessary as
part of the strategy to safeguard data against potential media failures that can damage
these files.
Logical backup - Complete, cumulative and incremental backup using export utility.
90. How do you take the backup of control file. Why do you have to take that?
Because a control file keeps track of the associated database's physical file
Ans.If you use Export to backup, all data must be exported in a logically consistent
way so that the backup reflects a single point in time. No one should make changes to
the database while the Export takes place. Ideally, you should run the database in
restricted mode while you export the data, so no regular users can access the data.
Ans.Online Backup:
Online backups are taken while the database is Open. Before you make an
online backup, you must do begin and end backup of tablespace. Online backups
Offline Backup:
Offline backups are taken while the database is shut down. Before you make
93. What is hot backup, when do you take it and how do you take it? Explain the steps.
Ans.Online or HOT backups allow you to back up all or part of the database while it is
running.
Syntax
94. What is cold backup, when do you take it and how do you take it? Explain the steps.
Ans.Offline or COLD backups are taken while the database is shut down. Before you
Steps.
SVRMGR> Shutdown
SVRMGR>startup
Ans.Using EXP tool extract the object definitions and table data from an Oracle
database and store them in an Oracle-binary format export file that is located typically
on tape or on disk. Export files can be used to transfer data between databases that are
Ans.Import extracts the objects from an Export file and puts them into a Database.
Destroy: Specifies whether the existing data files making up the database should be
reused. That is, the DESTROY option specifies that IMPORT should include the
99. What happens when you issue begin backup and end backup?
Ans.When you say begin backup, checkpoint will take place to update the highest
SCN in the respective Tablespace’s datafile header after that datafile header will be
frozen.
When you say end backup, datafile header frozen will be released.
100.What is recovery?
operation of a database system, you must usually recover the databases and return to
Recovery.
Ans.Recovering the database to the particular point in time using this syntax.
Statement to begin time-based recovery. The time is always specified using the
before disk failure, and includes the committed data in memory that was lost due to
failure
Ans.Complete: Complete media recovery recovers all lost changes; no work is lost.
Complete media recovery is possible only if all necessary redo logs (online and archived)
are available.
Different types of complete media recovery are available, depending on the files
that are damaged and the availability of the database that is required during recovery
operations.
damaged database to a transaction consistent state before the media failure or user error.
There are different types of incomplete media recovery that might be used,
i. cancel-based
j. time-based
tablespaces listed. To translate the tablespace names into datafile names, the database
must be mounted and open. The tablespaces must be offline to perform the recovery.
Ans.DATABASE recovery performs media recovery on all online datafiles that require
redo to be applied. If all instances were cleanly shutdown, and no backups were restored,
b) Application level
c) Memory Level
d) I/O level
e) Contention level
Ans.As a general guideline, you should create indexes on tables that are often queried
for less than 2% or 4% of the table's rows. This value may be higher in situations where
all data can be retrieved from an index, or where the indexed columns can be used for
tables that share the same data blocks because they share common columns and are often
used together.
Syntax.
table is similar in
112.What is Normalization?
of breaking down all items to their lowest level, making sure that each piece of data can
113.What is De-normalization?
Ans.In the real world, a world in which performance may be more important than
abstract perfection, you may find that you need to compromise your commitment to
normalize and be flexible about dealing with real data, for that you may need to embrace
114.When do de-normalize?
denormalizing your data. If you find that your application is performing repetitive SQL
table joins and sort/merges on large tables, you may be able to avoid reducing the need
Ans.A database trigger is a stored PL/SQL block that is associated with a table. Oracle
automatically executes a trigger when a specified SQL statement is issued against the
table.
Ans.In oracle 7.x only 12 types of triggers, but in oracle 8.x 14 types of triggers i.e. 12
117.In one table how many database triggers can be invoked in V7.x and V8.x?
Ans.In oracle 7.x a table can have 12 triggers maximum, but in oracle 8.x any number of
Ans.A database can be access through more than one instance. Parallel processing
divides a large task into many smaller tasks, and executes the smaller tasks concurrently
their failure resilience features. They also permit striping to be quite easily achieved, but
Ans.With the parallel query feature, multiple processes can work together
simultaneously to process a single SQL statement. This capability is called parallel query
processing. By dividing the work necessary to process a statement among multiple server
processes, the Oracle Server can process the statement more quickly than if only a single
121.What is Sql*loader?
Ans.SQL*Loader moves data from external files into tables in an Oracle database.
SQL*Loader loads data in a variety of formats, performs filtering and loads multiple
tables simultaneously.
SQL*Loader can:
. Manipulate data fields with SQL functions before inserting the data into
database columns
. Load multiple tables during the same run, loading selected rows into each table
. Provide thorough error reporting capabilities, so you can easily adjust and load
all records
Ans.A remote transaction is a transaction that contains one or more remote statements,
123.What is DDBMS?
A distributed database system appears to a user as a single server but is, in fact, a
set of two or more servers. The data on each server can be simultaneously accessed and
modified via a network. Each server in the distributed system is controlled by its local
database administrator (DBA), and each server cooperates to maintain the consistency of
124.What is SQL?
that all programs and users must use to access data within the Oracle database.
Ans.
126.What is Savepoint?
Ans.To identify a point in a transaction to which you can later roll back.
Ans.To remove all rows from a table or cluster and reset the STORAGE parameters to
128.What is PL/sql?
the power of traditional SQL. PL/sql statements can be combined with traditional SQL in
Block Structure:
Declare
<Local declaration>
Begin
<Statements>
Exception
<Error handler>
End;
129.What is ODBC?
as a foreign key and establishes a relationship between that foreign key and a specified
primary or unique key, called the referenced key. In this relationship, the table containing
the foreign key is called the child table and the table containing the referenced key is
database and provides continued primary database availability in the event of a disaster
take the standby database out of recovery mode and activate it for online use. Once you
activate your standby database, you cannot return it to standby recovery mode unless you