Anda di halaman 1dari 35

what is oracle

Mostly people think when you say i am oracle programmer, oracle DBA, Oracle BI Consultant.
They ask what is Oracle?
here is the answer
1. Oracle comes from the Latin word, oraculum or divine announcement.
2. In ancient Greece, it means somebody the tell the revelation.
3. In recent times, Oracle refers to the megalith company that supplies relational database
products to around 150 countries worldwide.
4. It is the worlds leading supplier of information management software with an annual
income of around $9.7 billion in recent years.
5. The product is used by some of the biggest web sites in cyberspace like the Fortune 1000
corporations.
6. Oracle is known for its sophisticated database system which makes it the highest ranking
performer in network computers.
what is Oracle database?
The Oracle database application makes use of microcomputers and high-end workstations as its
computer platform. It runs a set of processes on how to store and access data in the operating
system. It is a program that runs in the background but helps in the maintenance of stored data. It
also directs where these data shall be stored in the hard drive.

What is the first system of SQL?


The Oracle database operating systems were among the first to use the Structured Query
Language (SQL), now an industry standard. SQL allows for the selection, insertion, update, and
deletion of records from the database. It is the procedural language in Oracle application that
includes: SQL Plus, Oracle Developer, HTML Dv, and Oracle Enterprise Manager. These various
oracle tools helps in accessing and creating programs for database management.

What are Oracle Program Developers and Programmers?


Programmers and Developers have diverse work functions. A Programmer is a coder; while a
Developer, not only encodes but gathers relevant materials for implementation as well.

Developers needed for front-end programming, should be well versed in coding using tools,
reports, forms,and HTML among others. Back-end developers does not normally have the
detailed knowledge of forms as compared to their front-end counterparts.
Among the qualifications and requirements for the job would include the following:
1. Basic knowledge of SQL knowledge in nested subquery, aggregate functions, intervals, dual
tables, format mask, string conversion and so on.
2. Basic P/L and SQL -includes knowledge of block structures anonymous and unnamed; P/L
SQL collections, tablse, and arrays; explicit cursors; use of packages and straight procedures ;
maintenance and functionality among others.The above qualifications are needed for Junior
Developers that would still need further training. A Senior Developer however, would need to
have a good grasp of advanced PL/SQL topics.
For the Senior Developer level, the applicant should be well versed in the following areas:
1. Knowledge in aggregate and analytical programming
2. Knowledge in the creation of hierarchy query; generation of SML from a query; how to tune a
query
3. Implementing and creation of a member functions
4. Updates when SQL is not found
5. Knowldge of Select function with No Data Found exception
6. Knowledge in Native Dynamic SQL and autonomous transactions, among others

What is the educational requirement for Junior/Senior Oracle Developer?


First, is he should pursue a certificate course in Oracle technology, either through the Oracle
University or in any technical college that offers the same course. A certication for Database
Administrator/Developer at the Oracle-certified master level would enable the applicant for any
entry level position. Further training and certification for Advance Oracle Applications in the
next two (2) to three (3) years, will elevate the applicants position to senior level status.

What is the Employment Prospects for Junior/Senior Oracle Developers?


Oracle jobs are seen to grow above labor industry standards in the next few years. Since Oracle
is the worlds leader in database management, its market growth is on the uptrend, with Senior

Oracle Developers being in great demand. Salaries of Oracle Developers on job posting in the
United States are 37% higher than all other job postings. The salary range is from $95,000 to
$107,000 per annum depending on qualifications and experience.

oracle pl/sql interview questions and answers


Oracle PL/SQL Interview Questions and Answers
Q1. What is PL/SQL?
Answer : PL/SQL is a procedural language that has both interactive SQL and procedural
programming language constructs such as iteration, conditional branching.
Q2. What is the basic structure of PL/SQL?
Answer : PL/SQL uses block structure as its basic structure. Anonymous blocks or nested blocks
can be used in PL/SQL.
Q3. What are the components of a PL/SQL block?
Answer : A set of related declarations and procedural statements is called block.
Q4. What are the components of a PL/SQL Block?
Answer : Declarative part, Executable part and Execption part.Q5. What are the datatypes a
available in PL/SQL?
Answer : Some scalar data types such as
NUMBER, VARCHAR2, DATE, CHAR, LONG, BOOLEAN.
Some composite data types such as RECORD & TABLE.Q6. What are % TYPE and %
ROWTYPE? What are the advantages of using these over datatypes?
Answer : % TYPE provides the data type of a variable or a database column to that variable.
% ROWTYPE provides the record type that represents a entire row of a table or view or columns
selected in the cursor.The advantages are: I. need not know about variables data type
ii. If the database definition of a column in a table changes, the data type of a variable changes
accordingly.
Q7. What is difference between % ROWTYPE and TYPE RECORD ?
Answer : % ROWTYPE is to be used whenever query returns a entire row of a table or view.
TYPE rec RECORD is to be used whenever query returns columns of different table or views
and variables.
E.g. TYPE r_emp is RECORD (eno emp.empno% type,ename emp ename %type );
e_rec emp% ROWTYPE
Cursor c1 is select empno,deptno from emp;
e_rec c1 %ROWTYPE.
Q8. What is PL/SQL table?
Answer : Objects of type TABLE are called PL/SQL tables, which are modelled as (but not the
same as) database tables, PL/SQL tables use a primary PL/SQL tables can have one column and
a primary key.

Q9. What is a cursor? Why Cursor is required?


Answer : Cursor is a named private SQL area from where information can be accessed.
Cursors are required to process rows individually for queries returning multiple rows.
Q10. Explain the two types of Cursors?
Answer : There are two types of cursors, Implict Cursor and Explicit Cursor.
PL/SQL uses Implict Cursors for queries.
User defined cursors are called Explicit Cursors. They can be declared and used.
Q11. What are the PL/SQL Statements used in cursor processing?
Answer : DECLARE CURSOR cursor name, OPEN cursor name, FETCH cursor name INTO
<variable list> or Record types, CLOSE cursor name.
Q12. What are the cursor attributes used in PL/SQL?
Answer : %ISOPEN to check whether cursor is open or not
% ROWCOUNT number of rows featched/updated/deleted.
% FOUND to check whether cursor has fetched any row. True if rows are featched.
% NOT FOUND to check whether cursor has featched any row. True if no rows are featched.
These attributes are proceded with SQL for Implict Cursors and with Cursor name for Explict
Cursors.
Q13. What is a cursor for loop?
Answer : Cursor for loop implicitly declares %ROWTYPE as loop index,opens a cursor, fetches
rows of values from active set into fields in the record and closes when all the records have been
processed.
eg. FOR emp_rec IN C1 LOOP
salary_total := salary_total +emp_rec sal;
END LOOP;
Q14. What will happen after commit statement ?
Answer : Cursor C1 is
Select empno,
ename from emp;
Begin
open C1; loop
Fetch C1 into
eno.ename;
Exit When
C1 %notfound;
commit;
end loop;
end;
The cursor having query as SELECT . FOR UPDATE gets closed after
COMMIT/ROLLBACK.

The cursor having query as SELECT. does not get closed even after COMMIT/ROLLBACK.
Q 15. Explain the usage of WHERE CURRENT OF clause in cursors ?
Answer : WHERE CURRENT OF clause in an UPDATE,DELETE statement refers to the latest
row fetched from a cursor.
Q 16. What is a database trigger ? Name some usages of database trigger ?
Answer : Database trigger is stored PL/SQL program unit associated with a specific database
table. Usages are Audit data modificateions, Log events transparently, Enforce complex business
rules Derive column values automatically, Implement complex security authorizations. Maintain
replicate tables.
Q 17. How many types of database triggers can be specified on a table? What are they?
Answer :
Insert

Update

Delete

Before Row

o.k.

o.k.

o.k.

After Row

o.k.

o.k.

o.k.

Before Statement

o.k.

o.k.

o.k.

After Statement

o.k.

o.k.

o.k.

If FOR EACH ROW clause is specified, then the trigger for each Row affected by the statement.
If WHEN clause is specified, the trigger fires according to the retruned boolean value.
Q 18. Is it possible to use Transaction control Statements such a ROLLBACK or COMMIT in
Database Trigger? Why?
Answer : It is not possible. As triggers are defined for each table, if you use COMMIT of
ROLLBACK in a trigger, it affects logical transaction processing.
Q 19. What are two virtual tables available during database trigger execution?
Answer : The table columns are referred as OLD.column_name and NEW.column_name.
For triggers related to INSERT only NEW.column_name values only available.
For triggers related to UPDATE only OLD.column_name NEW.column_name values only
available.
For triggers related to DELETE only OLD.column_name values only available.
Q 20. What happens if a procedure that updates a column of table X is called in a database
trigger of the same table?
Answer : Mutation of table occurs.

Q 21. Write the order of precedence for validation of a column in a table ?


Answer :
I. done using Database triggers.
ii. done using Integarity Constraints.
Q 22. What is an Exception? What are types of Exception?
Answer : Exception is the error handling part of PL/SQL block. The types are Predefined and
user_defined. Some of Predefined execptions are.
CURSOR_ALREADY_OPEN
DUP_VAL_ON_INDEX
NO_DATA_FOUND
TOO_MANY_ROWS
INVALID_CURSOR
INVALID_NUMBER
LOGON_DENIED
NOT_LOGGED_ON
PROGRAM-ERROR
STORAGE_ERROR
TIMEOUT_ON_RESOURCE
VALUE_ERROR
ZERO_DIVIDE
OTHERS.
Q 23. What is Pragma EXECPTION_INIT? Explain the usage?
Answer : The PRAGMA EXECPTION_INIT tells the complier to associate an exception with an
oracle error. To get an error message of a specific oracle error.
e.g. PRAGMA EXCEPTION_INIT (exception name, oracle error number)
Q 24. What is Raise_application_error?
Answer : Raise_application_error is a procedure of package DBMS_STANDARD which allows
to issue an user_defined error messages from stored sub-program or database trigger.
Q 25. What are the return values of functions SQLCODE and SQLERRM?
Answer : SQLCODE returns the latest code of the error that has occured.
SQLERRM returns the relevant error message of the SQLCODE.
Q 26. Where the Pre_defined_exceptions are stored?
Answer : In the standard package.
Procedures, Functions & Packages;
Q 27. What is a stored procedure?
Answer : A stored procedure is a sequence of statements that perform specific function.

Q28. What is difference between a PROCEDURE & FUNCTION?


Answer : A FUNCTION is alway returns a value using the return statement.
A PROCEDURE may return one or more values through parameters or may not return at all.
Q29. What are advantages of Stored Procedures?
Answer : Extensibility,Modularity, Reusability, Maintainability and one time compilation.
A 30. What are the modes of parameters that can be passed to a procedure?
Answer : IN,OUT,IN-OUT parameters.
Q 31. What are the two parts of a procedure?
Answer : Procedure Specification and Procedure Body.
Q 32. Give the structure of the procedure?
Answer : PROCEDURE name (parameter list..)
is
local variable declarations
BEGIN
Executable statements.
Exception.
exception handlers
end;
Q 33. Give the structure of the function?
Answer : FUNCTION name (argument list ..) Return datatype is
local variable declarations
Begin
executable statements
Exception
execution handlers
End;
Q 34. Explain how procedures and functions are called in a PL/SQL block ?
Answer : Function is called as part of an expression.
sal := calculate_sal (a822);
procedure is called as a PL/SQL statement
calculate_bonus (A822);
Q 35. What is Overloading of procedures?
Answer : The Same procedure name is repeated with parameters of different datatypes and
parameters in different positions, varying number of parameters is called overloading of
procedures.
e.g. DBMS_OUTPUT put_line

Q 36. What is a package? What are the advantages of packages?


Answer : Package is a database object that groups logically related procedures.
The advantages of packages are Modularity, Easier Applicaton Design, and Information.
Hiding,. Reusability and Better Performance.
Q 37. What are two parts of package?
Answer : The two parts of package are PACKAGE SPECIFICATION & PACKAGE BODY.
Package Specification contains declarations that are global to the packages and local to the
schema.
Package Body contains actual procedures and local declaration of the procedures and cursor
declarations.
Q 38. What is difference between a Cursor declared in a procedure and Cursor declared in a
package specification?
Answer : A cursor declared in a package specification is global and can be accessed by other
procedures or procedures in a package.
A cursor declared in a procedure is local to the procedure that can not be accessed by other
procedures.
Q 39. How packaged procedures and functions are called from the following ?
Answer : a. Stored procedure or anonymous block
b. an application program such a PRC *C, PRO* COBOL
c. SQL *PLUS
a. PACKAGE NAME.PROCEDURE NAME (parameters);
variable := PACKAGE NAME.FUNCTION NAME (arguments);
EXEC SQL EXECUTE
b.
BEGIN
PACKAGE NAME.PROCEDURE NAME (parameters)
variable := PACKAGE NAME.FUNCTION NAME (arguments);
END;
END EXEC;
c. EXECUTE PACKAGE NAME.PROCEDURE if the procedures does not have any out/in-out
parameters. A function can not be called.
Q 40. Name the tables where characteristics of Package, procedure and functions are stored?
Answer : User_objects, User_Source and User_error.
PL/SQL Advanced Interview Questions
1. Which of the following statements is true about implicit cursors?
1. Implicit cursors are used for SQL statements that are not named.
2. Developers should use implicit cursors with great care.

3. Implicit cursors are used in cursor for loops to handle data processing.
4. Implicit cursors are no longer a feature in Oracle.

2. Which of the following is not a feature of a cursor FOR loop?


1. Record type declaration.
2. Opening and parsing of SQL statements.
3. Fetches records from cursor.
4. Requires exit condition to be defined.
3. A developer would like to use referential datatype declaration on a variable. The
variable name is EMPLOYEE_LASTNAME, and the corresponding table and
column is EMPLOYEE, and LNAME, respectively. How would the developer define
this variable using referential datatypes?
1. Use employee.lname%type.
2. Use employee.lname%rowtype.
3. Look up datatype for EMPLOYEE column on LASTNAME table and use that.
4. Declare it to be type LONG.
4. Which three of the following are implicit cursor attributes?
1. %found
2. %too_many_rows
3. %notfound
4. %rowcount
5. %rowtype
5. If left out, which of the following would cause an infinite loop to occur in a simple
loop?
1. LOOP

2. END LOOP
3. IF-THEN
4. EXIT
6. Which line in the following statement will produce an error?
1. cursor action_cursor is
2. select name, rate, action
3. into action_record
4. from action_table;
5. There are no errors in this statement.
7. The command used to open a CURSOR FOR loop is
1. open
2. fetch
3. parse
4. None, cursor for loops handle cursor opening implicitly.
8. What happens when rows are found using a FETCH statement
1. It causes the cursor to close
2. It causes the cursor to open
3. It loads the current row values into variables
4. It creates the variables to hold the current row values
9. Read the following code:
10.
11.

CREATE OR REPLACE PROCEDURE find_cpt


(v_movie_id {Argument Mode} NUMBER, v_cost_per_ticket
{argument mode} NUMBER)
12.
IS
13.
BEGIN
14.
IF v_cost_per_ticket > 8.5 THEN
15.
SELECT cost_per_ticket
16.
INTO
v_cost_per_ticket

17.
18.
19.
20.

FROM
gross_receipt
WHERE
movie_id = v_movie_id;
END IF;
END;

Which mode should be used for V_COST_PER_TICKET?


1. IN
2. OUT
3. RETURN
4. IN OUT
21. Read the following code:
22.
23.
24.
25.
26.

CREATE OR REPLACE TRIGGER update_show_gross


{trigger information}
BEGIN
{additional code}
END;

The trigger code should only execute when the column, COST_PER_TICKET, is greater
than $3. Which trigger information will you add?
1. WHEN (new.cost_per_ticket > 3.75)
2. WHEN (:new.cost_per_ticket > 3.75
3. WHERE (new.cost_per_ticket > 3.75)
4. WHERE (:new.cost_per_ticket > 3.75)
27. What is the maximum number of handlers processed before the PL/SQL block is
exited when an exception occurs?
1. Only one
2. All that apply
3. All referenced
4. None
28. For which trigger timing can you reference the NEW and OLD qualifiers?
1. Statement and Row

2. Statement only
3. Row only
4. Oracle Forms trigger
29. Read the following code:
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.

CREATE OR REPLACE FUNCTION get_budget(v_studio_id IN NUMBER)


RETURN number IS
v_yearly_budget NUMBER;
BEGIN
SELECT
INTO
FROM
WHERE

yearly_budget
v_yearly_budget
studio
id = v_studio_id;

RETURN v_yearly_budget;
END;

Which set of statements will successfully invoke this function within SQL*Plus?
1. VARIABLE g_yearly_budget NUMBER
EXECUTE g_yearly_budget := GET_BUDGET(11);
2. VARIABLE g_yearly_budget NUMBER
EXECUTE :g_yearly_budget := GET_BUDGET(11);
3. VARIABLE :g_yearly_budget NUMBER
EXECUTE :g_yearly_budget := GET_BUDGET(11);
4. VARIABLE g_yearly_budget NUMBER
:g_yearly_budget := GET_BUDGET(11);
43.
44.
45.
46.
47.
48.
49.

CREATE OR REPLACE PROCEDURE update_theater


(v_name IN VARCHAR v_theater_id IN NUMBER) IS
BEGIN
UPDATE theater
SET
name = v_name
WHERE
id = v_theater_id;
END update_theater;

50. When invoking this procedure, you encounter the error:


ORA-000: Unique constraint(SCOTT.THEATER_NAME_UK) violated.

How should you modify the function to handle this error?

1. An user defined exception must be declared and associated with the error code
and handled in the EXCEPTION section.
2. Handle the error in EXCEPTION section by referencing the error code directly.
3. Handle the error in the EXCEPTION section by referencing the
UNIQUE_ERROR predefined exception.
4. Check for success by checking the value of SQL%FOUND immediately after the
UPDATE statement.
51. Read the following code:
52.
53.
54.
55.
56.
57.
58.
59.
60.

CREATE OR REPLACE PROCEDURE calculate_budget IS


v_budget
studio.yearly_budget%TYPE;
BEGIN
v_budget := get_budget(11);
IF v_budget < 30000
THEN
set_budget(11,30000000);
END IF;
END;

You are about to add an argument to CALCULATE_BUDGET. What effect will this
have?
1. The GET_BUDGET function will be marked invalid and must be recompiled
before the next execution.
2. The SET_BUDGET function will be marked invalid and must be recompiled
before the next execution.
3. Only the CALCULATE_BUDGET procedure needs to be recompiled.
4. All three procedures are marked invalid and must be recompiled.
61. Which procedure can be used to create a customized error message?
1. RAISE_ERROR
2. SQLERRM
3. RAISE_APPLICATION_ERROR
4. RAISE_SERVER_ERROR
62. The CHECK_THEATER trigger of the THEATER table has been disabled. Which
command can you issue to enable this trigger?

1. ALTER TRIGGER check_theater ENABLE;


2. ENABLE TRIGGER check_theater;
3. ALTER TABLE check_theater ENABLE check_theater;
4. ENABLE check_theater;
63. Examine this database trigger
64.
65.
66.
67.
68.
69.

CREATE OR REPLACE TRIGGER prevent_gross_modification


{additional trigger information}
BEGIN
IF TO_CHAR(sysdate, DY) = MON
THEN
RAISE_APPLICATION_ERROR(-20000,Gross receipts cannot be
deleted on Monday);
70.
END IF;
71.
END;

This trigger must fire before each DELETE of the GROSS_RECEIPT table. It
should fire only once for the entire DELETE statement. What additional
information must you add?
1. BEFORE DELETE ON gross_receipt
2. AFTER DELETE ON gross_receipt
3. BEFORE (gross_receipt DELETE)
4. FOR EACH ROW DELETED FROM gross_receipt
72. Examine this function:
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.

CREATE OR REPLACE FUNCTION set_budget


(v_studio_id IN NUMBER, v_new_budget IN NUMBER) IS
BEGIN
UPDATE studio
SET
yearly_budget = v_new_budget
WHERE
id = v_studio_id;
IF SQL%FOUND THEN
RETURN TRUEl;
ELSE
RETURN FALSE;
END IF;
END;

COMMIT;

Which code must be added to successfully compile this function?

1. Add RETURN right before the IS keyword.


2. Add RETURN number right before the IS keyword.
3. Add RETURN boolean right after the IS keyword.
4. Add RETURN boolean right before the IS keyword.
88. Under which circumstance must you recompile the package body after recompiling
the package specification?
1. Altering the argument list of one of the package constructs
2. Any change made to one of the package constructs
3. Any SQL statement change made to one of the package constructs
4. Removing a local variable from the DECLARE section of one of the package
constructs
89. Procedure and Functions are explicitly executed. This is different from a database
trigger. When is a database trigger executed?
1. When the transaction is committed
2. During the data manipulation statement
3. When an Oracle supplied package references the trigger
4. During a data manipulation statement and when the transaction is committed
90. Which Oracle supplied package can you use to output values and messages from
database triggers, stored procedures and functions within SQL*Plus?
1. DBMS_DISPLAY
2. DBMS_OUTPUT
3. DBMS_LIST
4. DBMS_DESCRIBE
91. What occurs if a procedure or function terminates with failure without being
handled?

1. Any DML statements issued by the construct are still pending and can be
committed or rolled back.
2. Any DML statements issued by the construct are committed
3. Unless a GOTO statement is used to continue processing within the BEGIN
section, the construct terminates.
4. The construct rolls back any DML statements issued and returns the unhandled
exception to the calling environment.
92. Examine this code
93.
94.

BEGIN

theater_pck.v_total_seats_sold_overall :=
theater_pck.get_total_for_year;
95.
END;

For this code to be successful, what must be true?


1
1. Both the V_TOTAL_SEATS_SOLD_OVERALL variable and the
GET_TOTAL_FOR_YEAR function must exist only in the body of the
THEATER_PCK package.
2. Only the GET_TOTAL_FOR_YEAR variable must exist in the specification of
the THEATER_PCK package.
3. Only the V_TOTAL_SEATS_SOLD_OVERALL variable must exist in the
specification of the THEATER_PCK package.
4. Both the V_TOTAL_SEATS_SOLD_OVERALL variable and the
GET_TOTAL_FOR_YEAR function must exist in the specification of the
THEATER_PCK package.
2

A stored function must return a value based on conditions that are determined at
runtime. Therefore, the SELECT statement cannot be hard-coded and must be
created dynamically when the function is executed. Which Oracle supplied package
will enable this feature?
1. DBMS_DDL
2. DBMS_DML
3. DBMS_SYN

4. DBMS_SQL
What are joins and Types of join?
Ans. We need retrive data from two or more tables to make our result complete. We need to
perform a join.
INNER JOIN
This join returns rows when there is at least one match in both the tables.
OUTER JOIN
There are three different Outer Join methods.
LEFT OUTER JOIN
This join returns all the rows from the left table with the matching rows from the right table. If
there are no field matching in the right table then it returns NULL values
RIGHT OUTER JOIN
Right outer join returns all the rows from the right table with the matching rows from the left
table. If there are no field matching in the left table then it returns NULL values
FULL OUTER JOIN
Full outer join merge left outer join and right outer join. this returns row from either table when
the conditions are met and returns null value when there is no match
CROSS JOIN
Corss join is does not necessary any condition to join. The output result contains records that are
multiplication of record from both the tables.
What is DIFFERENCE BETWEEN LEFT, RIGHT OUTER JOIN?
Ans:If there r any values in one table that do not have corresponding values in the other,in an
equi join that row will not be selected.Such rows can be forcefully selected by using outer join
symbol(+) on either of the sides(left or right) based on the requirement.
WHAT ARE SET OPERATORS?
Ans: UNION, INTERSECT or MINUS is called SET OPERATORS.
What are different datatypes supported by sql in oracle?
Ans: Char (size), Nchar (size), Varchar2 (size), Nvarchar2 (size) data types for character values,
Number (precision, scale), Number, Number (n), Float, Float (binary precision) data types for
numerical values, Date data type for date values, Long, Raw (size), Long Raw, Clob, Blob,
Nclob, Bfile for large objects.
What is difference between long and lob datatypes?
Ans:LOB
1) The maximum size is 4GB. 2) LOBs (except NCLOB) can be attributes of an object type. 3)
LOBs support random access to data. 4) Multiple LOB columns per table or LOB attributes in an
object type.
LONG
1) The maximum size is 2GB. 2) LONGs cannot. 3) LONGs support only sequential access. 4)
Only one LONG column was allowed in a table

How much memory is allocated for date datatype? What is default date format in oracle?
Ans: For Date data type oracle allocates 7 bytes Memory. Default Date Format is: DD-MONYY.
What is range for each datatype of sql?
Ans: Datatype Range Char Varchar2 Number Float LONG, RAW, LONGRAW Large
Objects (LOBs) 2000 bytes 4000 bytes Precision
1 to 38 Scale -84 to 127 Precision 38 decimals Or 122 binary precision 2 GB 4GB
What is a constraint? What are its various levels?
Ans: Constraint: Constraints are representators of the column to enforce data entity and
consistency.There r two levels
1)Column-level constraints 2)Table-level constraints.
List out all the constraints supported by oracle
Primary Key , Foreign Key or Referential Integrity, Not Null, Unique, Check.
Select 3 product which having highest sale price
SELECT * FROM ( SELECT * FROM product ORDER BY sales_price DESC) WHERE rownum
<= 3
Delete the records from product which having null description
delete from product where product_name is null
Display detail of product which having maximum sale
SELECT * FROM
( SELECT product_id, count(product_id)as cnt FROM sales group by product_id order by cnt
desc) WHERE rownum = 1
Select customer details and produtct details of cutomer imran
Select p.product_name, c.cutomer_name, p.sale_price from product p, cutomer c, sale s
where p.product_id=s.product_id and c.cutomer_id=s.ccustomer_id and
customer_name=imran
Difference between DELETE & TRUNCATE statement
Ans. Delete is a DML command. Truncate is a DDL command.
In Delete statement we can use where clause But we cant use where clause in truncate
statement.
Delete activates trigger. Truncate does not activate trigger.
We can rollback delete command. We can not rollback truncate command. Delete does not reset
identity of table. Truncate resets identity of table.
Difference between Primary key and Unique Key

Ans. Primary key and Unique key enforce uniqueness of the column on which they are defined.
But by default, the primary key creates a clustered index on the column, where as unique key
creates a non-clustered index by default. Another major difference is that primary key does not
allow NULL value, but unique key allows one NULL value only.
What are oracle number, character, date, conversion, other
functions.
Ans.
Oracle Number Functions
Round (m, [n]),
Trunc (m, [n]),
Power (m, n),
Sqrt,
Abs (m),
Ceil (m),
Floor (m),
Mod (m, n)Oracle Character FunctionsChr (x)
Concert (string1, string2)
Lower (string)
Upper (string)
Substr (string, from_str, to_str)
ASCII (string)
Length (string)
Initcap (string).Oracle Date Functionssysdate
Months between (d1, d2)
To_char (d, format)
Last day (d)
Next_day (d, day).
Oracle Conversion FunctionsTo_char
To_date
To_number
What is syntax of PL/SQL BLOCK
Ans. DECLARE
BEGIN
EXCEPTION
END;
What are different types of oracle PL/SQL BLOCKS?

Ans:
Oracle PL/SQL DECLARE BLOCK In DECLARE BLOCK all the declarations of the
variable used in the program is made. If no variables are used this block will become optional.
Oracle PL/SQL BEGIN BLOCK In BEGIN BLOCK all the executable statements are placed.
This block is Mandatory.
Oracle EXCEPTION BLOCK In EXCEPTION BLOCK all the exceptions are handled. this
block is optional.
what is a Oracle PL/SQL cursor? and how to create cursor syntax?
Ans: Cursor is Private SQL area in PL/SQL.
Declare the Cursor,
Open the Cursor,
Fetch values from SQL into the local Variables,
Close the Cursor.
Type of cursors are supported by oracle pl/sql?
Ans. There are two types of cursors namely Implicit Cursor, Explicit Cursor.
What is a cursor for loop?
Ans: Cursor For Loop is shortcut process for Explicit Cursors because the Cursor is Open, Rows
are fetched once for each iteration and the cursor is closed automatically when all the rows have
been processed.
What are cursor attributes?
Ans: %Found, %NotFound, %IsOpen, %RowCount are the cursor attributes.
Use of cursor with for update of clause?
Ans: This Clause stop accessing of other users on the particular columns used by the cursor until
the COMMIT is issued.
How Exception is different from error?
Ans: Whenever an error occurs Exception raises. Error is a bug whereas the Exception is a
warning or error condition.
Whats a PL/SQL table? Its purpose and Advantages?

A PL/SQL table is one dimensional, indexed, unbounded sparsed collection of


homogeneous
Data.
PLSQL tables are used to move data into and out of the database and between client side
applications and stored sub-programs. They have attributes such as exits, prior, first, last,
delete ,next . These attributes make PLSQL tables easier to use and applications easier to
maintain.
Advantages:
1 PL\SQL tables give you the ability to hold multiple values in a structure in memory so
that a PL\SQL block does not have to go to the database every time it needs to retrieve

one of these values it can retrieve it directly from the PL\SQL table in memory.
2 Global temporary tables act as performance enhancers when compared to standard
tables as they greatly reduce the disk IO.
3 They also offer the ease-of-use of standard tables, since standard SQL can be used with
them; no special array-processing syntax is required.

What is a Cursor? How many types of Cursor are there?


A) Cursor is an identifier/name to a work area that we can interact with to access its
information. A cursor points to the current row in the result set fetched. There are three
types of cursors. They are
1 Implicit cursors created automatically by PL/SQL for all SQL Dml statements such as
Insert Update, delete and Select
2 Explicit cursors Created explicitly. They create a storage area where the set of rows
Returned by a query are placed.
3 Dynamic Cursors Ref Cursors( used for the runtime modification of the select
querry).
Declaring the cursor, Opening the cursor, Fetching data , Closing the cursor(Releasing the
work area) are the steps involved when using explicit cursors.

What is the difference between Function and Procedure?


1..Procedure is a sub program written to perform a set of actions and returns multiple
valuesUsing out parameters or return no value at all.
2..Function is a subprogram written to perform certain computations and return a single
value.

What are the modes for passing parameters to Oracle?


There are three modes for passing parameters to subprograms
1.IN An In-parameter lets you pass values to the subprogram being called. In the
subprogram it acts like a constant and cannot be assigned a value.
2. OUT An out-parameter lets you return values to the caller of the subprogram. It acts
like an initialized variable its value cannot be assigned to another variable or to itself.
3.INOUT An in-out parameter lets you pass initial values to the subprogram being
called and returns updated values to the caller.

What is the difference between Truncate and Delete Statement?


1.Truncate Data truncated by using truncate statement is lost permanently and cannot
be retrieved even by rollback. Truncate command does not use rollback segment during
its execution, hence it is fast.
2. Delete Data deleted by using the delete statement can be retrieved back by Rollback.
Delete statement does not free up the table object allocated space.

What are Exceptions? How many types of Exceptions are there?


Exceptions are conditions that cause the termination of a block. There are two types of
exceptions
1.Pre-Defined Predefined by PL/SQL and are associated with specific error codes.
2.User-Defined Declared by the users and are rose on deliberate request. (Breaking a

condition etc.)
Exception handlers are used to handle the exceptions that are raised. They prevent
exceptions from propagating out of the block and define actions to be performed when
exception is raised.

What is a Pragma Exception_Init? Explain its usage?


Pragma Exception_Init is used to handle undefined exceptions. It issues a directive to the
compiler asking it to associate an exception to the oracle error. There by displaying a
specific error message pertaining to the error occurred. Pragma Exception_Init
(exception_name, oracle_error_name).

What is a Raise and Raise Application Error?


1.Raise statement is used to raise a user defined exception.
2. A raise application error is a procedure belonging to dbms_standard package. It allows
to display a user defined error message from a stored subprogram.

What is the difference between Package, Procedure and Functions?


1.A package is a database objects that logically groups related PL/SQL types, objects, and
Subprograms.
2.Procedure is a sub program written to perform a set of actions and can return multiple
values.
3.Function is a subprogram written to perform certain computations and return a single
value. Unlike subprograms packages cannot be called, passed parameters or nested.

How do you make a Function and Procedure as a Private?


Functions and Procedures can be made private to a package by not mentioning their
declaration in the package specification and by just mentioning them in the package body.

How do you kick a Concurrent program from PL/SQL?


Using FND_REQUEST.SUBMIT_REQUEST.

What is an Anonymous block?


Anonymous Block is a block of instructions in PL/SQL and SQL which is not saved
under a name as an object in database schema It is also not compiled and saved in server
storage, so it needs to be parsed and executed each time it is run. However, this simple
form of program can use variables, can have flow of control logic, can return query
results into variables and can prompt the user for input using the SQL*Plus & feature as
any stored procedure.

What are the two basic parameters that we have to pass while registering PL/SQL
procedure?
Error code and Error Buffer.

How to display messages in Log file and Output file?


Using FND_FILE.PUT_LINE

What is a Trigger ? How many types of Triggers are there?


Trigger is a procedure that gets implicitly executed when an insert/update/delete
statement is issued against an associated table. Triggers can only be defined on tables not
on views, how ever triggers on the base table of a view are fired if an insert/update/delete
statement is issued against a view.
There are two types of triggers, Statement level trigger and Row level trigger.
Insert
After / For each row
Trigger is fired / Update /
Before / For Each statement
Delete

Can we use Commit in a Database Trigger, if No then why?


No. Committing in a trigger will violate the integrity of the transaction.

What is Commit, Rollback and Save point?


Commit Makes changes to the current transaction permanent. It Erases the savepoints
and releases the transaction locks.
Savepoint Savepoints allow to arbitrarily hold work at any point of time with option of
later committing. They are used to divide transactions into smaller portions.
Rollback This statement is used to undo work.

What is the difference between DDL, DML and DCL structures?


DDL statements are used for defining data. Ex: Create, Alter, Drop,Truncate,Rename.
DML statements are used for manipulating data. Ex: Insert, update, truncate.
DCL statements are used for to control the access of data. Ex; Grant, Revoke.
TCL statements are used for data saving.Ex; Commit,Rollback,Savepoint.

How can u create a table in PL/SQL procedure?


By using execute immediate statement we can create a table in PLSQL.
Begin
Execute immediate create table amit as select * from emp;
End;
All DDL,DML,DCL commands can be performed by using this command.

How do we Tune the Queries?


Queries can be tuned by Checking the logic (table joins), by creating Indexes on objects
in the where clause, by avoiding full table scans. Finally use the trace utility to generate
the trace file, use the TK-Prof utility to generate a statistical analysis about the query
using which appropriate actions can be taken.

What is Explain Plan? How do u use Explain Plan in TOAD?


It is a utility provided by toad that gives the statistics about the performance of the query.
It gives information such as number of full table scans occurred, cost, and usage of
indexes

What is a TK-PROF and its usage?


Tk-Prof is a utility that reads the trace files and generates more readable data that gives
the statistics about the performance of the query on a line to line basis.

What is Optimization? How many types of Optimization are there?


Rule based Optimization and Cost Based Optimization.

What is the default optimization chosen by Oracle?


Cost based Optimization.

What is the difference between the snapshot and synonym?


7 A snapshot refers to read-only copies of a master table or tables located on a remote
node. A snapshot can be queried, but not updated; only the master table can be updated. A
snapshot is periodically refreshed to reflect changes made to the master table. In this
sense, a snapshot is really a view with periodicity.
8 A synonym is an alias for table, view, sequence or program unit. They are of two types
private and public.

What is the difference between data types char and varchar?


Char reserves the number of memory locations mentioned in the variable declarations,
even though not used (it can store a maximum of 255 bytes). Where as Varchar does not
reserve any memory locations when the variable is declared, it stores the values only after
they are assigned (it can store a maximum of 32767 bytes).

Items are imported from the legacy system using the item import interface using the
SRS. How are items imported using the UNIX /PLSQL commands with out using
SRS?
1.From the operating system, use CONCSUB to submit a concurrent program. Its an
easiest way to test a concurrent program.
Normally, CONCSUB submits a concurrent request and returns control to the OS
prompt/shell script without waiting for the request to complete. The CONCSUB WAIT
parameter can be used to make CONCSUB wait until the request has completed before
returning control to the OS prompt/shell script
By using the WAIT token, the utility checks the request status every 60 seconds and
returns to the operating system prompt upon completion of the request. concurrent
manager does not abort, shut down, or start up until the concurrent request completes. If
your concurrent program is compatible with itself, we can check it for data integrity and
deadlocks by submitting it many times so that it runs concurrently with itself.
Syntax: CONCSUB [WAIT= [START=] [REPEAT_DAYS=] [REPEAT_END=]
To pass null parameters to CONCSUB, use without spaces for each null parameter.
In words: single quote double quote double quote single quote
Following is an example of CONCSUB syntax with null parameters:
CONCSUB oe/oe OE Order Entry Super User JWALSH CONCURRENT XOE
XOEPACK 4 3 3
2. To Invoke a Concurrent Program using PL/SQL:
i) Just insert a row in FND_CONCURRENT_REQUESTS with the apropriate parameters

and commit.
ii) Invoke the SUBMIT_REQUEST procedure in FND_REQUEST package.
FND_REQUEST.SUBMIT_REQUEST( AR, RAXMTR, , , FALSE, Autoinvoice
Master Program, sc_time, FALSE, 1, 1020, VRP, 01-JAN-00, chr(0)

How can the duplicate records be deleted from the table?


delete from t1 a where rowid not in (select max(rowid) from t1 b where a.no=b.no)

What is the significance of _all tables?


All tables are multi-org tables which are associated with the company as a whole.
Multiple Organizations is enabled in Oracle
Applications by partitioning some database tables by the Operating Unit. Other tables are
shared across Operating Units (and therefore across set of books). Examples of
Applications with partitioned tables are Oracle Payables, Oracle Purchasing, Oracle
Receivables, Oracle Projects, Oracle Sales & Marketing etc. The name of each
corresponding partitioned table is the view name appended by _ALL

What are mutating tables? And what is mutating error?


A mutating table is a table that is currently being modified by an UPDATE, DELETE, or
INSERT statement, or it is a table that might need to be updated by the effects of a
declarative DELETE CASCADE referential integrity constraint.
A mutating error occurs when a trigger which fires when updation/deletion/insertion is
done on a table A performs insertion/updation/deletion on the same table A. This error
results in an infinite loop which is termed as a mutating error.

What is difference between oracle 7 andoracle 8i?


A) Oracle 7 is a simple RDBMS, where as Oracle 8i is ORDBMS i.e., RDBMS with
Object Support.
The main add-ons in version 8 are
Abstract Data types
Varrays
PL/SQL Tables
Nested Tables
Partitioned Tables

What is Data cleaning and testing.


Data Cleaning: Transformation of data in its current state to a pre-defined, standardized
format using packaged software or program modules.
Data Testing: The agreed upon conversion deliverables should be approved by the client
representatives who are responsible for the success of the conversion. In addition, three
levels of conversion testing have been identified and described in the prepare conversion
test plans deliverables.
Eg: for Summary Balances in GL we set Test Criteria as Record Counts, Hash Totals,
Balances, Journal Debit and Credit.

While registering a report and a pl/sql block we pass some parameters, for any
pl/sql block we pass 2 additional parameters. Can u list them?
It requires two IN parameters for a PL/SQL procedure thats registered as a concurrent
program in Apps. They are
1. Errcode IN VARCHAR2
2. Errbuff IN VARCHAR2

what is a trace file?


when ever an internal error is detected by a process in oracle it dumps the information
about the error into a trace file.
Alter session set sql_trace=TRUE

When do you use Ref Cursors?


We base a query on a ref cursor when you want to:
1.More easily administer SQL
2. Avoid the use of lexical parameters in your reports
3. Share data sources with other applications, such as Form Builder
4. Increase control and securityv) Encapsulate logic within a subprogram

Oracle Database 12c New Features


The following are some of the interesting new features of Oracle Database 12c.

Invisible Column
Oracle 12c allows a column to be invisible. Invisible columns are considered only
when they are explicitly referred; otherwise they are ignored for queries and DML
operations.
You can make a column visible or invisible whenever you want using ALTER TABLE
command.
CREATE TABLE T2 ( C1

NUMBER(5),

C2 NUMBER(5) INVISIBLE)

INSERT INTO T2 (C1,C2) VALUES (10, 20);


INSERT INTO T2 VALUES(30);
SELECT * FROM T2;
SQL> select * from t2;
C1
---------10
30
SELECT C1,C2 FROM T2;
SQL> select c1,c2 from t2;

C1
C2
---------- ---------10
20
30
ALTER TABLE T2 MODIFY (C2
SELECT

VISIBLE)

* FROM T2

SQL> select c1,c2 from t2;


C1
C2
---------- ---------10
20
30

Default Value from CURRVAL AND NEXTVAL


In Oracle 12c, it is now possible to specify the CURRVAL and NEXTVAL sequence
pseudocolumns as the default values for a column. In previous versions, it was
either done explicitly in INSERT command or a trigger was used to do it
automatically during insertion.
CREATE SEQUENCE t1_seq;
CREATE TABLE t1 (
id
NUMBER DEFAULT t1_seq.NEXTVAL,
description VARCHAR2(30)
);
INSERT INTO t1 (description) VALUES ('DESCRIPTION');
INSERT INTO t1 (id, description) VALUES (999, 'DESCRIPTION');
select * from

t1

SQL> select * from t1;


ID
---------1
999

DESCRIPTION
-----------------------------DESCRIPTION
DESCRIPTION

The following example shows how to use NEXTVAL for master table and CURRVAL
for details or child table.
CREATE SEQUENCE order_master_seq;
CREATE SEQUENCE order_details_seq;
CREATE TABLE order_master (
Order_id
NUMBER DEFAULT order_master_seq.NEXTVAL,
Description VARCHAR2(20)
);
CREATE TABLE order_details (
id
NUMBER DEFAULT order_details_seq.NEXTVAL,

order_id
description

NUMBER DEFAULT order_master_seq.CURRVAL,


VARCHAR2(50)

);
insert into order_master (description) values ('First Order');
insert into order_details (description) values ('First Item');
insert into order_details (description) values ('Second Item');
select * from order_master;
SQL> select * from order_master;
ORDER_ID DESCRIPTION
---------- -------------------1 First Order
select * from order_details;
SQL> select * from order_details;
ID
ORDER_ID DESCRIPTION
---------- ---------- -------------------------------------------------1
1 First Item
2
1 Second Item

DEFAULT ON NULL
If the column is referenced in INSERT, even when supplying the value NULL, the
default value is not used. Oracle 12c allows you to modify this behaviour using the
ON NULL clause in the default definition. When ON NULL is used, default value is
applied when NULL value is provided explicitly.
create sequence t1_seq;
CREATE TABLE t1 (
id
NUMBER DEFAULT ON NULL t1_seq.NEXTVAL,
description VARCHAR2(30)
);
insert into t1(description) values('First Item');
as value for ID is missing
insert into t1 values(null,'Second Item');
even when NULL is explicitly provided
insert into t1 values(333,'Third Item');
SQL> select * from t1;
ID
---------1
2
333

DESCRIPTION
-----------------------------First Item
Second Item
Third Item

// default value is used


// default value is used

Identity Columns
The 12c database introduces the ability to define an identity clause for a table
column defined using a numeric type.
GENERATED
[ALWAYS | BY DEFAULT [ ON NULL ] ]
AS IDENTITY [ (identity_options ) ]

Using ALWAYS forces the use of the identity. If an insert statement references the
identity column, even to specify a NULL value, an error is produced.
CREATE TABLE order_master (
Id NUMBER GENERATED ALWAYS AS IDENTITY,
Description Varchar2(20)
);
Insert into order_master (description) values('First Order');
Insert into order_master (description) values('Second Order');
SQL> select * from order_master;
ID
---------1
2

DESCRIPTION
-------------------First Order
Second Order

SQL> Insert into order_master (id,description) values(100,'Third Order');


Insert into order_master (id,description) values(100,'Third Order')
*
ERROR at line 1:
ORA-32795: cannot insert into a generated always identity column

Using BY DEFAULT allows you to use the identity if the column isn't referenced in the
insert statement, but if the column is referenced, the specified value will be used in
place of the identity.
Attempting to specify the value NULL in this case results in an error, since identity
columns are always NOT NULL.
CREATE TABLE order_master(
Id NUMBER GENERATED BY DEFAULT AS IDENTITY,
Description Varchar2(20)
);
Insert into order_master (description) values('First Order');
Insert into order_master (id,description) values(20,'Second Order');
select * from order_master;
SQL> select * from order_master;

ID
---------1
20

DESCRIPTION
-------------------First Order
Second Order

Using BY DEFAULT ON NULL allows the identity to be used even when the identity
column is referenced and NULL value is specified.
CREATE TABLE order_master(
Id NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY ,
Description Varchar2(20)
);
Insert into order_master (id,description) values(null,'First Order');
Insert into order_master (id,description) values(20,'Second Order');
Insert into order_master (description) values('Third Order');
SQL> select * from order_master;
ID
---------1
20
2

DESCRIPTION
-------------------First Order
Second Order
Third Order

Note: Oracle uses a sequence internally to generate value to populate the identity
column.

Using RETURN_RESULT
Oracle 12c allows a procedure to return a list of rows by using RETURN_RESULT
procedure of DBMS_SQL package.
Rather than defining explicit ref cursor out parameters, the RETURN_RESULT
procedure in the DBMS_SQL package allows you to pass them out implicitly.
The following procedure returns list of rows from JOBS table as return value from a
procedure.
CREATE OR REPLACE PROCEDURE get_jobs
AS
job_cursor SYS_REFCURSOR;
BEGIN
OPEN job_cursor FOR
SELECT * from jobs;
DBMS_SQL.RETURN_RESULT(job_cursor);
END;

You can call the procedure and get the list of rows from the procedure as follows:
EXECUTE get_jobs

Functions in the WITH Clause


The declaration section of the WITH clause can be used to define PL/SQL functions,
as shown below.
WITH
FUNCTION Experience(hd date) RETURN NUMBER IS
BEGIN
RETURN floor ((sysdate - hd) / 365);
END;
SELECT First_name, Experience(hire_date)
FROM
Employees
/

From a name resolution perspective, functions defined in the PL/SQL declaration


section of the WITH clause take precedence over objects with the same name
defined at the schema level.

OFFSET and FETCH clauses


Oracle 12c provides enhanced support for top-n analysis.

OFFSET provides a way to skip the N first rows in a result set before starting
to return any rows

The FETCH clause limits the number of rows returned in the result set

For the result offset clause, the value of the integer literal must be equal to 0
(default if the clause is not given), or positive. If it is larger than the number
of rows in the underlying result set, no rows are returned.

For the fetch first clause, the value of the literal must be 1 or higher. The
literal can be omitted, in which case it defaults to 1. If the clause is omitted
entirely, all rows (or those rows remaining if a result offset clause is also
given) will be returned.

OFFSET { integer-literal | ? } {ROW | ROWS}


FETCH { FIRST | NEXT } [integer-literal | ? ] {ROW | ROWS} ONLY

ROW is synonymous with ROWS and FIRST is synonymous with NEXT.


The following examples show how to use these clauses.
Select * from employees fetch first row only;
retrieves only first row

//

select * from employees fetch next 5 rows only;


retrieves first 5 rows from the beginning

//

select * from employees offset 5 rows fetch next 5 rows only;


retrieves 5 rows from 5th row

//

select * from employees order by salary desc fetch next 5 rows only;
retrieves first 5 highest salaried employees

//

Other Miscellaneous Features

The maximum size of VARCHAR2, NVARCHAR2, and RAW data types has been
increased from 4,000 to 32,767 bytes. Increasing the allotted size for these
data types allows users to store more information in character data types
before switching to large objects (LOBs). This is especially useful for brief
textual data types and the capabilities to build indexes on these types of
columns.

Through Oracle Database 11g Release 2 (11.2), only definer's rights PL/SQL
functions could be result cached. Now, invoker's rights PL/SQL functions can
also be result cached.

Prior to Oracle 12c R1, undo records generated by the temporary tables used
to be stored in undo tablespace. However, with the temporary undo feature in
12c, the temporary undo records can now be stored in a temporary table
instead of undo tablespace.

Complex Queries in SQL ( Oracle )


These questions are the most frequently asked in interviews.
1. To fetch ALTERNATE records from a table. (EVEN NUMBERED)
select * from emp where rowid in (select decode(mod(rownum,2),0,rowid, null) from
emp);
2. To select ALTERNATE records from a table. (ODD NUMBERED)
select * from emp where rowid in (select decode(mod(rownum,2),0,null ,rowid) from
emp);
3. Find
the
3rd
MAX
salary
in
the
emp
table.
select distinct sal from emp e1 where 3 = (select count(distinct sal) from emp e2 where
e1.sal <= e2.sal);
4. Find
the
3rd
MIN
salary
in
the
emp
table.
select distinct sal from emp e1 where 3 = (select count(distinct sal) from emp e2where
e1.sal >= e2.sal);
5. Select
FIRST
n
records
select * from emp where rownum <= &n;

from

table.

6. Select
LAST
n
records
from
a
table
select * from emp minus select * from emp where rownum <= (select count(*) - &n from
emp);
7. List dept no., Dept name for all the departments in which there are no employees in
the
department.
select * from dept where deptno not in (select deptno from emp);
alternate solution: select * from dept a where not exists (select * from emp b where
a.deptno
=
b.deptno);
altertnate solution: select empno,ename,b.deptno,dname from emp a, dept b where
a.deptno(+) = b.deptno and empno is null;
8. How
to
get
3
Max
salaries
?
select distinct sal from emp a where 3 >= (select count(distinct sal) from emp b where
a.sal <= b.sal) order by a.sal desc;
9. How
to
get
3
Min
salaries
?
select distinct sal from emp a where 3 >= (select count(distinct sal) from emp b where
a.sal >= b.sal);
10. How
to
get
nth
max
salaries
?
select distinct hiredate from emp a where &n = (select count(distinct sal) from emp b
where a.sal >= b.sal);
11. Select
DISTINCT
RECORDS
from
emp
table.
select * from emp a where rowid = (select max(rowid) from emp b where
a.empno=b.empno);
12. How
to
delete
duplicate
rows
in
a
table?
delete from emp a where rowid != (select max(rowid) from emp b where
a.empno=b.empno);
13. Count
of
number
of
employees
in
select count(EMPNO), b.deptno, dname from emp
a.deptno(+)=b.deptno group by b.deptno,dname;

department
a, dept b

wise.
where

14. Suppose there is annual salary information provided by emp table. How to fetch
monthly salary of each and every employee?
select ename,sal/12 as monthlysal from emp;
15. Select all record from emp table where deptno =10 or 40.
select * from emp where deptno=30 or deptno=10;
16. Select all record from emp table where deptno=30 and sal>1500.

select * from emp where deptno=30 and sal>1500;


17. Select all record from emp where job not in SALESMAN or CLERK.
select * from emp where job not in ('SALESMAN','CLERK');
18. Select all record from emp where ename in 'BLAKE','SCOTT','KING'and'FORD'.
select * from emp where ename in('JONES','BLAKE','SCOTT','KING','FORD');
19. Select all records where ename starts with S and its lenth is 6 char.
select * from emp where ename like'S____';
20. Select all records where ename may be any no of character but it should end with
R.
select * from emp where ename like'%R';
21. Count MGR and their salary in emp table.
select count(MGR),count(sal) from emp;
22. In emp table add comm+sal as total sal .
select ename,(sal+nvl(comm,0)) as totalsal from emp;
23. Select any salary <3000 from emp table.
select * from emp where sal> any(select sal from emp where sal<3000);
24. Select all salary <3000 from emp table.
select * from emp where sal> all(select sal from emp where sal<3000);
25. Select all the employee group by deptno and sal in descending order.
select ename,deptno,sal from emp order by deptno,sal desc;
26. How can I create an empty table emp1 with same structure as emp?
Create table emp1 as select * from emp where 1=2;
27. How
to
retrive
record
where
sal
Select * from emp where sal>=1000 And sal<2000

between

1000

to

2000?

28. Select all records where dept no of both emp and dept table matches.
select * from emp where exists(select * from dept where emp.deptno=dept.deptno)
29. If there are two tables emp1 and emp2, and both have common record. How can I
fetch
all
the
recods
but
common
records
only
once?
(Select * from emp) Union (Select * from emp1)
30. How to fetch only common records from two tables emp and emp1?
(Select * from emp) Intersect (Select * from emp1)
31. How can I retrive all records of emp1 those should not present in emp2?
(Select * from emp) Minus (Select * from emp1)
32. Count the totalsa deptno
SELECT
deptno,
FROM
GROUP
HAVING COUNT(empno) > 2

wise

where more
sum(sal)
BY

than

2 employees exist.
As
totalsal
emp
deptno

Anda mungkin juga menyukai