Академический Документы
Профессиональный Документы
Культура Документы
1.
select comm,empno ,
2.
NVL(comm,o)
Comm is null return o.
3.
NVL2(comm,'dsp','psd') ,
Comm is null return PSD not null DSP.
4.
NULLIF('a','b')
a <>b then return a if equal then return null.
5.
from emp
Sal in character format.
SELECT SAL, (TO_CHAR(TO_DATE(SAL,'j'), 'jsp')) FROM EMP;
Dens and desn_rank function.
RANK: When multiple rows share the same rank the next rank in the sequence is no
t consecutive.
The DENSE_RANK function acts like the RANK function except that it assigns conse
cutive ranks:
SELECT EMPNO,
DEPTNO,
SAL,
RANK() OVER (PARTITION BY DEPTNO ORDER BY SAL) "RANK",
DENSE_RANK() OVER (PARTITION BY DEPTNO ORDER BY SAL) "DENSRANK"
FROM EMP;
EMPNO
9999
7369
7876
7788
7902
7566
7900
7521
7654
7844
7499
7698
DEPTNO
10
20
20
20
20
20
30
30
30
30
30
30
SAL
2230
1900
4200
6100
6100
6101
3950
4250
4250
4500
4600
5850
RANK
1
1
2
3
3
5
1
2
2
4
5
6
DENSE_RANK
1
1
2
3
3
4
1
2
2
3
4
5
The FIRST and LAST functions can be used to return the first or last value from
an ordered sequence. Say we want to display the salary of each employee, along w
ith the lowest and highest within their department we may use something like:
SELECT EMPNO,
DEPTNO,
SAL,
MIN(SAL) KEEP (DENSE_RANK FIRST ORDER BY SAL) OVER (PARTITION BY DEPTNO)
"Lowest",
MAX(SAL) KEEP (DENSE_RANK LAST ORDER BY SAL) OVER (PARTITION BY DEPTNO) "
Highest"
FROM EMP
ORDER BY DEPTNO, SAL;
Both LAG and LEAD functions have the same usage, as shown below.
LAG (value_expression [,offset] [,default]) OVER ([query_partition_clause] orde
r_by_clause)
LEAD (value_expression [,offset] [,default]) OVER ([query_partition_clause] orde
r_by_clause)
offset - The number of rows preceeding/following the current row, from which the
data is to be retrieved. The default value is 1.
default - The value returned if the offset is outside the scope of the window. T
SELECT EMPNO,
ENAME,
JOB,
SAL,
FROM EMP;
Diff between ROLLUP and CUBE.
SELECT DEPTNO,JOB,COUNT(*) CNT
FROM TEST_EMP
GROUP BY CUBE(DEPTNO,JOB)
SELECT DEPTNO,JOB,COUNT(*) CNT
FROM TEST_EMP
GROUP BY ROLLUP(DEPTNO,JOB)
Roll Up(N+1)
Cube(N*N)
DEPTNO JOB
CNT
DEPTNO
10
Designer
1
10
Manager 1
10
10
2
10
20
Designer
1
20
Helper 2
20
20
3
20
30
Designer
1
30
Tester 4
30
30
5
30
10
JOB
CNT
10
Designer
Manager 1
2
20
Designer
Helper 2
3
30
Designer
Tester 4
5
Designer
3
Helper 2
Manager 1
Tester 4
10
1
1
1
JOB
ANALYST
CLERK
MANAGER
COUNT(*)
1
3000
2
1900
2
5425
5
10325
CLERK 1
1300
MANAGER 1
2975
SUM(SAL)
0
0
0
0
0
0
0
1
0
0
0
0
FLAG1
0
0
0
1
0
0
FLAG2
GROUPING_ID
20
20
20
30
30
30
30
40
40
40
PRESIDENT
rrrr
1
4
CLERK 1
MANAGER 1
SALESMAN
6
CLERK 1
MANAGER 1
2
17
1
3000
12275
950
2850
4
9400
1100
5000
6100
38100
5000
0
0
0
0
5600
0
0
0
0
1
0
0
1
0
0
0
1
0
0
1
1
0
0
1
0
0
0
1
0
0
1
3
1
Scott
2
Millor
3
Jiyo
4
Smith
6.
Display the records between two range
select rownum, empno, ename from emp where rowid in
(select rowid from emp where rownum <=&upto
minus
select rowid from emp where rownum<&Start);
Enter value for upto: 10
Enter value for Start: 7
ROWNUM
EMPNO ENAME
--------- --------- ---------1
7782 CLARK
2
7788 SCOTT
3
7839 KING
4
7844 TURNER
7.
I know the nvl function only allows the same data type(ie. number or cha
r or date Nvl(comm, 0)), if commission is null then the text Not Applicable want
to display, instead of blank space. How do I write the query?
SQL> select nvl(to_char(comm.),'NA') from emp;
Output :
NVL(TO_CHAR(COMM),'NA')
----------------------NA
300
500
NA
1400
NA
NA
8.
Oracle cursor : Implicit & Explicit cursors
Oracle uses work areas called private SQL areas to create SQL statements.
PL/SQL construct to identify each and every work are used, is called as Cursor.
For SQL queries returning a single row, PL/SQL declares all implicit cursors.
For queries that returning more than one row, the cursor needs to be explicitly
declared.
9.
Explicit Cursor attributes
There are four cursor attributes used in Oracle
cursor_name%Found,
cursor_name%NOTFOUND,
cursor_name%ROWCOUNT,
cursor_name%ISOPEN
10. Implicit Cursor attributes
Same as explicit cursor but prefixed by the word SQL
SQL%Found,
SQL%NOTFOUND,
SQL%ROWCOUNT,
SQL%ISOPEN
Tips : 1. Here SQL%ISOPEN is false, because oracle automatically closed the impl
icit cursor after executing SQL statements.
: 2. All are Boolean attributes.
11. Find out nth highest salary from emp table
SELECT DISTINCT (a.sal) FROM EMP A WHERE &N = (SELECT COUNT (DISTINCT (b.sal))
FROM EMP B WHERE a.sal<=b.sal);
Enter value for n: 2
SAL
--------3700
select *
from (select
from emp
order by sal
)
where rownum
minus
select *
from (select
from emp
order by sal
where rownum
rownum rnk,sal
<&n+1
rownum rnk,sal
)
<&n
select *
from (
select rownum aa, sal
from (select distinct sal from emp order by sal))
where aa =&n
12. To view installed Oracle version information
SQL> select banner from v$version;
13. Display the number value in Words
SQL> select sal, (to_char(to_date(sal,'j'), 'jsp'))
from emp;
the output like,
SAL (TO_CHAR(TO_DATE(SAL,'J'),'JSP'))
--------- ----------------------------------------------------800 eight hundred
1600 one thousand six hundred
1250 one thousand two hundred fifty
If you want to add some text like,
Rs. Three Thousand only.
SQL> select sal "Salary ",
(' Rs. '|| (to_char(to_date(sal,'j'), 'Jsp'))|| ' only.'))
"Sal in Words" from emp
/
Salary Sal in Words
------- -----------------------------------------------------800 Rs. Eight Hundred only.
1600 Rs. One Thousand Six Hundred only.
1250 Rs. One Thousand Two Hundred Fifty only.
14. Display Odd/ Even number of records
Odd number of records:
select * from emp where (rowid,1) in (select rowid, mod(rownum,2) from emp);
1
3
5
Even number of records:
select * from emp where (rowid,0) in (select rowid, mod(rownum,2) from emp)
2
4
6
15. Which date function returns number value?
months_between
16. Any three PL/SQL Exceptions?
Too_many_rows, No_Data_Found, Value_Error, Zero_Error, Others
17. What are PL/SQL Cursor Exceptions?
Cursor_Already_Open, Invalid_Cursor
18. Other way to replace query result null value with a text
SQL> Set NULL N/A
to reset SQL> Set NULL
19. What are the more common pseudo-columns?
nce column values by old collection using keyword :old. column name.
Q. Can you change the inserted value in one of the columns in AFTER insert trigg
er code?
This is not possible as the column values supplied by the insert SQL query are a
lready inserted into the table. If you try to assign new value to the column in
AFTER insert trigger code then oracle error would be raised. To alter any values
supplied by insert SQL query create BEFORE insert trigger.
Q. Explain use of SYSDATE and USER keywords.
SYSDATE is a pseudo column and refers to the current server system date. USER is
a pseudo column and refers to the current user logged onto the oracle session.
These values come handy when you want to monitor changes happening to the table.
Normal Queries
Sub Queries
Co-related queries
Nested queries
Compound queries
12.
What is a transaction ?
Answer: A transaction is a set of SQL statements between any two COMMIT and ROLL
BACK statements.
13.
What is implicit cursor and how is it used by Oracle ?
Answer: An implicit cursor is a cursor which is internally created by Oracle.It
is created by Oracle for each individual SQL.
14.
Which of the following is not a schema object : Indexes, tables, public
synonyms, triggers and packages ?
Answer: Public synonyms
15.
What is PL/SQL?
Answer: PL/SQL is Oracle s Procedural Language extension to SQL.The language inc
ludes object oriented programming techniques such as encapsulation, function ove
rloading, information hiding (all but inheritance), and so, brings state-of-theart programming to the Oracle database server and a variety of Oracle tools.
16.
Is there a PL/SQL Engine in SQL*Plus?
Answer: No.Unlike Oracle Forms, SQL*Plus does not have a PL/SQL engine.Thus, all
your PL/SQL are send directly to the database engine for execution.This makes i
t much more efficient as SQL statements are not stripped off and send to the dat
abase individually.
17.
Is there a limit on the size of a PL/SQL block?
Answer: Currently, the maximum parsed/compiled size of a PL/SQL block is 64K and
the maximum code size is 100K.You can run the following select statement to que
ry the size of an existing package or procedure. SQL> select * from dba_object_s
ize where name = procedure_name
18.
Can one read/write files from PL/SQL?
Answer: Included in Oracle 7.3 is a UTL_FILE package that can read and write fil
es.The directory you intend writing to has to be in your INIT.ORA file (see UTL_
FILE_DIR=...parameter).Before Oracle 7.3 the only means of writing a file was to
use DBMS_OUTPUT with the SQL*Plus SPOOL command.
DECLARE
fileHandler UTL_FILE.FILE_TYPE;
BEGIN
fileHandler := UTL_FILE.FOPEN( /home/oracle/tmp , myoutput , W );
UTL_FILE.PUTF(fileHandler, Value of func1 is %sn , func1(1));
UTL_FILE.FCLOSE(fileHandler);
END;
19.
How can I protect my PL/SQL source code?
Answer: PL/SQL V2.2, available with Oracle7.2, implements a binary wrapper for P
L/SQL programs to protect the source code.This is done via a standalone utility
that transforms the PL/SQL source code into portable binary object code (somewha
t larger than the original).This way you can distribute software without having
to worry about exposing your proprietary algorithms and methods.SQL*Plus and SQL
*DBA will still understand and know how to execute such scripts.Just be careful,
there is no "decode" command available. The syntax is: wrap iname=myscript.sql
oname=xxxx.yyy
20.
Can one use dynamic SQL within PL/SQL? OR Can you use a DDL in a procedu
re ? How ?
Answer: From PL/SQL V2.1 one can use the DBMS_SQL package to execute dynamic SQL
statements.
Eg: CREATE OR REPLACE PROCEDURE DYNSQL AS
cur integer;
rc integer;
BEGIN
cur := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(cur, CREATE TABLE X (Y DATE) , DBMS_SQL.NATIVE);
rc := DBMS_SQL.EXECUTE(cur);
DBMS_SQL.CLOSE_CURSOR(cur);
END;
21.
What are the various types of Exceptions ?
it return No row.
71.
If all the values from a cursor have been fetched and another fetch is i
ssued, the output will be : error, last record or first record ?
Answer: Last Record
81.
When to create indexes ?
Answer: To be created when table is queried for less than 2% or 4% to 25% of the
table rows.
82.
How can you avoid indexes ?
Answer: To make index access path unavailable
91.
For which relational operators in where clause, index is not used ?
Answer: <> , like %... is NOT functions, field +constant, field||
91.
Answer:
92.
ot ?
Answer:
93.
Answer: Yes
101.
What is a package cursor ?
Answer: A package cursor is a cursor which you declare in the package specificat
ion without an SQL statement.The SQL statement for the cursor is attached dynami
cally at runtime from calling procedures.
Use INDEX or AND-EQUAL hint to optimizer to use one index or set to indexes inst
ead of another.
cursors
exceptions
32.
Why Create or Replace and not Drop and recreate procedures ?
Answer: So that Grants are not dropped.
33.
Can you pass parameters in packages ? How ?
Answer: Yes.You can pass parameters to procedures or functions in a package.
34.
What are the parts of a database trigger ?
Answer: The parts of a trigger are:
A trigger restriction
A trigger action
35.
What are the various types of database triggers ?
Answer: There are 12 types of triggers, they are combination of :
39.
What are the values of :new and :old in Insert/Delete/Update Triggers ?
Answer: INSERT : new = new value, old = NULL
DELETE : new = NULL, old = old value
UPDATE : new = new value, old = old value
40.
What are cascading triggers? What is the maximum no of cascading trigger
s at a time?
Answer: When a statement in a trigger body causes another trigger to be fired, t
he triggers are said to be cascading.Max = 32.
PL-SQL Interview Questions with Answers
1. Describe the difference between a procedure, function and anonymous pl/sql bl
ock.
Level: Low
Expected answer : Candidate should mention use of DECLARE statement, a function
must return a value while a procedure doesn t have to.
2. What is a mutating table error and how can you get around it?
Level: Intermediate
Expected answer: This happens with triggers. It occurs because the trigger is tr
ying to update a row it is currently using. The usual fix involves either use of
views or temporary tables so the database is selecting from one while updating
the other.
3. Describe the use of %ROWTYPE and %TYPE in PL/SQL
Level: Low
Expected answer: %ROWTYPE allows you to associate a variable with an entire tabl
e row.
The %TYPE associates a variable with a single column type.
4. What packages (if any) has Oracle provided for use by developers?
Expected answer: Oracle provides the DBMS_ series of packages. There are many
which developers should be aware of such as DBMS_SQL, DBMS_PIPE, DBMS_TRANSACTIO
N,
DBMS_LOCK, DBMS_ALERT, DBMS_OUTPUT, DBMS_JOB, DBMS_UTILITY, DBMS_DDL, UTL_FILE.
If they can mention a few of these and describe how they used them, even better.
If they include the SQL routines provided by Oracle, great, but not really what
was asked.
5. Describe the use of PL/SQL tables
Expected answer: PL/SQL tables are scalar arrays that can be referenced by a
binary integer. They can be used to hold values for use in later queries
or calculations. In Oracle 8 they will be able to be of the %ROWTYPE designation
, or RECORD.
6. When is a declare statement needed ?
The DECLARE statement is used in PL/SQL anonymous blocks such as with stand alon
e, non-stored PL/SQL procedures. It must come first in a PL/SQL stand alone file
if it is used.
7. In what order should a open/fetch/loop set of commands in a PL/SQL block be i
mplemented if you use the NOTFOUND cursor variable in the exit when statement? W
hy?
Expected answer: OPEN then FETCH then LOOP followed by the exit when. If not spe
cified in this order will result in the final return being done twice because of
the way the %NOTFOUND is handled by PL/SQL.
8. What are SQLCODE and SQLERRM and why are they important for PL/SQL developers
?
Expected answer: SQLCODE returns the value of the error number for the last erro
r encountered. The SQLERRM returns the actual error message for the last error e