SQL Queries 1688182703
SQL Queries 1688182703
SELECT DISTINCT SAL FROM EMP A WHERE &N=(SELECT COUNT (DISTINCT B.SAL) FROM
EMP B WHERE A.SAL<=B.SAL);
SELECT DNAME, DEPTNO FROM DEPT WHERE EXISTS (SELECT * FROM EMP WHERE
DEPT.DEPTNO = EMP.DEPTNO)
4. To Find The Not Null Column Alone In A Table.SELECT COLUMN_NAME FROM
USER_TAB_COLUMNS WHERE NULLABLE = 'N' AND TABLE_NAME = 'COUNTRY'
DELETE DEPT WHERE ROWID NOT IN (SELECT MAX (ROWID) FROM DEPT GROUP BY
DEPTNO HAVING COUNT (*) >=1)
2.SELECT SAL FROM EMP WHERE SAL >= ALL (SELECT SAL FROM EMP)
SELECT EMPNO, LPAD (‘ ‘, 6*(LEVEL – 1)) || ENAME “EMPLOYEE NAME” FROM EMP START
WITH ENAME=’KING’ CONNECT BY PRIOR EMPNO = MGR
Choose one of the following queries to identify or remove duplicate rows from a table leaving one
record:
Method 1:
-1- https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
DELETE FROM table_name A WHERE ROWID > (SELECT min (rowid) FROM table_name B
SQL> Delete from my_table where rowid not in (select max (rowid) from my_table group by
my_column_name);
SQL> delete from my_table t1 where exists (select 'x' from my_table t2 where t2.key_value1 =
t1.key_value1
And t2.key_value2 = t1.key_value2and t2.rowid > t1.rowid);
Note: If you create an index on the joined fields in the inner loop, you for all intensive purposes
eliminate N^2 operations (no need to loop through the entire table on each pass by a record).
Create your table with a NOT NULL column (say SEQNO). This column can now be populated with
unique values:
14. How can I get the time difference between two date columns?
Select dept, sum (decode (sex,'M', 1,0)) MALE, sum (decode (sex,'F', 1,0)) FEMALE, count
(decode (sex,'M', 1,'F', 1)) TOTAL from my_emp_table group by dept;
A value x will be between values y and z if GREATEST (x, y) = LEAST (x, z). Look at this example:
Select f2, count (decode (greatest (f1, 59), least (f1, 100), 1, 0)) "Range 60-100",
Count (decode (greatest (f1, 30), least (f1, 59), 1, 0)) "Range 30-59",
Count (decode (greatest (f1, 29), least (f1, 0), 1, 0)) "Range 00-29" From my_table
group by f2;
-2- https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
For equal size ranges it might be easier to calculate it with DECODE (TRUNC (value/range), 0,
rate_0, 1, rate_1,).
E.g.
Select ename "Name", sal "Salary", decode (trunc (f2/1000, 0), 0, 0.0,1, 0.1, 2, 0.2, 3, 0.31) "Tax
rate"
From my_table;
17. Can one only retrieve the Nth row from a table?
SELECT f1 FROM t1 WHERE rowid = (SELECT rowid FROM t1 WHERE rownum <= 10
MINUS
SELECT rowid FROM t1 WHERE rownum < 10); 18.
SELECT * FROM tableX WHERE rowid in (SELECT rowid FROM tableX WHERE rownum <= 7
MINUS
SELECT rowid FROM tableX WHERE rownum < 5);
19. How does one select EVERY Nth row from a table?
One can easily select all even, odd, or Nth rows from a table using SQL queries like this:
SELECT *FROM EMP WHERE (ROWID, 0) IN (SELECT ROWID, MOD (ROWNUM, 4) FROM
EMP);
SELECT * FROM (SELECT rownum rn, empno, ename FROM EMP) temp WHERE MOD
(temp. ROWNUM, 4) = 0;
20. How does one select the TOP N rows from a table?
SELECT * FROM my_table a WHERE 10 >= (SELECT COUNT (DISTINCT maxcol) FROM
my_table b
WHERE b.maxcol >= a.maxcol) ORDER BY maxcol DESC;
This is definitely non-relational (enough to kill Codd and then make him roll in his grave) and is a
feature I have not seen in the competition.
The definitive example is in the example SCOTT/TIGER database, when looking at the EMP table
(EMPNO and MGR columns). The MGR column contains the employee number of the "current"
employee's boss.
You have available an extra pseudo-column, LEVEL, that says how deep in the tree you are. Oracle
can handle queries with a depth up to 255.
Select LEVEL, EMPNO, ENAME, MGR from EMP connect by prior EMPNO = MGR start with MGR is
NULL;
-3- https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
You can get an "indented" report by using the level number to sub-string or lpad a series of spaces
and
Concatenate that to the string.
Select lpad (' ', LEVEL * 2) || ENAME...
You use the start with clause to specify the start of the tree(s). More than one record can match the
starting condition. One disadvantage of a "connect by prior" is that you cannot perform a join to other
tables. Still, I have not managed to see anything else like the "connect by prior" in the other vendor
offerings and I like trees. Even trying to doing this programmatic ally in embedded SQL is difficult as
you have to do the top level query, for each of them open a cursor to look for child nodes, for each of
these open a cursor.... Pretty soon you blow the cursor limit for your installation.
The way around this is to use PL/SQL, open the driving cursor with the "connect by prior" statement,
and the select matching records from other tables on a row-by-row basis, inserting the results into a
temporary table for later retrieval.
The Oracle decode function acts like a procedural statement inside an SQL statement to return
different values or columns based on the values of other columns in the select statement.
Some examples: Select decode (sex, 'M', 'Male', 'F', 'Female', 'Unknown')
from employees;
Select a, b, decode( abs (a-b), a-b, 'a > b',0, 'a = b','a < b') from tableX;
Select decode (GREATEST (A, B), A, 'A is greater than B', 'B is greater than A')...
Note: The decode function is not ANSI SQL and are rarely implemented in other RDBMS offerings. It
is one of the good things about Oracle, but use it sparingly if portability is required.
23. How can one dump/ examine the exact content of a database column?
DUMP (COL1)
-------------------------------------
Typ=96 Len=4: 65,66,67,32
For this example the type is 96, indicating CHAR, and the last byte in the column is 32, which is the
ASCII code for a space. This tells us that this column is blank-padded.
Oracle does not provide a way to DROP a column (reference: Enhancement Request 51118).
However, Joseph S. Testa wrote a DROP COLUMN package that can be downloaded from
Other workarounds:
2. Create table t2 as select <specific columns> from t1; Drop table t1;
Rename t2 to t1;
-4- https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
1. Rename t1 to t1_base;
Create view t1 <column list with new name> as select * from t1_base;
2. create table t2 <column list with new name> as select * from t1; Drop table t1;
Rename t2 to t1;
Declare
a integer;
b integer;
Begin a := dbms_pipe.create_pipe('kumaran');
dbms_pipe.pack_message('kumaran software is a good company');
b := dbms_pipe.send_message('kumaran'); if b = 0 then
dbms_output.put_line('successfully send');
else dbms_output.put_line('not send');
end if;
end;
declare a integer; b
varchar2(30);
begin a := dbms_pipe.receive_message('kumaran');
dbms_pipe.unpack_message(b); if a = 0 then
dbms_output.put_line('successfully received');
dbms_output.put_line(b);
else dbms_output.put_line('not received');
end if;
end;
-5- https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
Only local or packaged subprograms can be overloaded. Therefore, you cannot overload standalone
subprograms. Also, you cannot overload two subprograms if their formal parameters differ only in name
or parameter mode. For example, you cannot overload the following
Finally, you cannot overload two functions that differ only in return type (the datatype of the result value)
even if the types are in different families. For example, you cannot overload the following functions:
-6- https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
Sure there is, but it is hard to find them... In Server Manager from Oracle7.3: ORADEBUG HELP
SMON coalesces free space (extents) into larger, contiguous extents every 2 hours and even then only
for a short period of time. SMON will not coalesce free space if a tablespace's default storage parameter
"pctincrease" is set to 0. With Oracle 7.3 one can manually coalesce a tablespace using the ALTER
TABLESPACE ... COALESCE; command, until then use:
SQL> alter session set events 'immediate trace name coalesce level n';
Where 'n' is the tablespace number you get from SELECT TS#, NAME FROM SYS.TS$;
You can get status information about this process by selecting from the
DBA_FREE_SPACE_COALESCED view.
Always set PCTINCREASE to 0 or 100. Bizarre values for PCTINCREASE will contribute to
fragmentation. For example if you set PCTINCREASE to 1 you will see that your extents are going to
-7- https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
have weird and wacky sizes: 100K, 100K, 101K, 102K, etc. Such extents of bizarre size are rarely
reused in their entirety. PCTINCREASE of 0 or 100 gives you nice round extent sizes that can easily
be reused. E.g. 100K, 100K, 200K, 400K, etc.
6. Where can one find the high water mark for a table?
There is no system table which containts the high water mark (HWM) information. You can calculate
the HWM using the results from the following SQL statements:
• You can also use the DBMS_SPACE package and calculate the HWM = TOTAL_BLOCKS
UNUSED_BLOCKS - 1.
You can prevent ORA-600 space leak messages during database shutdown by telling the kernel not to
check for memory leakage. This undocumented feature :-) was introduced with Oracle 7.1.6 and can
be prevented by setting:
SQL> ALTER SESSION SET EVENTS "10262 trace name context forever, level 1024"
Oracle recommends that your database blocks size matches, or be multiples of your operating system
block size. One can go smaller, but the performance cost is significant. Your choice should depend on
the type of application you are running. If you have lots of small transaction like with OLTP, use a small
block size. With fewer but larger transactions, like with a DSS application, use a large block size. If you
are using a volume manager, consider your "operating system block size" to be 8K. This is because
volume manager products use 8K blocks (and this is not configurable).
-8- https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
You can manually increase or decrease the size of a datafile in Oracle 7.2 using the
Because you can change the sizes of datafiles, you can add more space to your database without
adding more datafiles. This is beneficial if you are concerned about reaching the maximum number of
datafiles allowed in your database. Manually reducing the sizes of datafiles allows you to reclaim
unused space in the database. This is useful for correcting errors in estimates of space requirements.
Also, datafiles can be allowed to automatically extend if more space is required. Look at the following
command:
While your production database is running, take an ON-LINE backup and restore it on duplicate
hardware. Note that an export will not work! On your standby database, issue the following commands:
Write a job to copy archived redo log files from your primary database to the standby system, and apply
the redo log files to the standby database (pipe it). Remember the database is recovering and will
prompt you for the next log file to apply.
When you need the standby database stop the recovery process and activate it:
The "alter session set SQL_TRACE = true" command generates trace files in USER_DUMP_DEST
that is used by developers as input to tkprof. On Unix the default file mask for these files are "rwx r-- --
-".
There is an undocumented INIT.ORA parameter that will allow everybody to read (rwx r-- r--) this trace
files:
_trace_files_public = true
Include this in your INIT.ORA file and bounce your database for it to take effect.
-9- https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
15. How can I see what the uptime for my database is?column STARTED format a18 head
'STARTUP TIME'
SELECT
C.INSTANCE,
TO_DATE(JUL.VALUE, 'J')
|| TO_CHAR(FLOOR(SEC.VALUE/3600), '09') || ':'
|| SUBSTR (TO_CHAR(MOD(SEC.VALUE/60, 60), '09'), 2, 2)|| '.'
|| SUBSTR (TO_CHAR(MOD(SEC.VALUE, 60), '09'), 2, 2) STARTED
FROM
V$INSTANCE JUL,
V$INSTANCE SEC,
V$THREAD C
WHERE
JUL.KEY LIKE '%JULIAN%'
AND SEC.KEY LIKE '%SECOND%';
Of course it is not advisable to bridge Oracle's security, but look at this example:
PASSWORD
-----------------------------
F894844C34402B67
If you allow people to log in with OPS$ accounts from Windows95, you cannot tell who that really is.
With terminals, you can rely on passwords, with Win95, you cannot. If you set
REMOTE_OS_AUTHENT=TRUE in your init.ora file, Oracle Assumes that the remote OS has
authenticated the user.
If REMOTE_OS_AUTHENT is set to FALSE, you have no exposure from remote clients - you also won't
be able to connect from a remote client without a password (recommended). IDENTIFIED
EXTERNALLY will only be in effect from the local host. Also, if you're using OPS$ as your prefix, you'll
be able to log on locally with or without a password, regardless of whether you've identified your ID with
a password or defined it to be IDENTIFIED EXTERNALLY.
- 10 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
For every user using temporary space, there is an entry in SYS.V$_LOCK with type 'TS'. All temporary
segments are named 'ffff.bbbb' where 'ffff' is the file it is in and 'bbbb' is first block of the segment.
If your temporary tablespace is set to TEMPORARY, all sorts are done in one large temporary
segment. For usage status, see SYS.V_$SORT_SEGMENT
1. Explain SCN.
Whenever a transaction is committed, LGWR writes transactions redo entries from the redo log buffer
of SGA to an online redo file and a (System Change Number) SCN is assigned to identify the redo
entries for each committed transaction.
High SCN:- During the prepare phase ( The Global coordinator asks participants to prepare (to promise
to Commit or Rollback the transaction, even if there is a failure). The highest SCN at all node in the
transaction is determined. The transaction is then committed with the high SCN at the commit point
site. The SCN is then sent to all prepared nodes along with the commit decision.
High water mark is the Highest Block Number in which data has been stored in the Segment.
- 11 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
Row Chaining: If an update to a row causes that row to no longer completely fit in a Single data block,
then that row may be moved to another data block or the row may be Chained to another block. If row
length is greater that the Oracle block size, the row will be chained.
Row Migration: If a row in a data block is updated so that 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. Oracle preserves the original row piece of a migrated
row to point to the new block containing the migrated row; the ROWID of a migrated row does not
change.
Chained rows data is stored in a chain of data blocks and in Row Migration the entire row is shifted to
a new location.
6. Coalesce Details.
Is the process by which SMON automatically Coalesces neighboring free extents in a single large free
space. It is done automatically if PCT Increase of the Tablespace is non zero or can be done manually
by issuing "ALTER TABLESPACE <table_space_name>COALESCE".
The Header contains general block information, such as Block Address, Segment Type, such as data,
Index or Rollback. Some headers are fixed in size, the total block overhead size is variable. On an
Average fixed & variable size of data block overhead is total 84 to 107 bytes.
When oracle process accesses a buffer the process moves the buffer to the most-recently used (MRU)
end of the LRU list. As most of the buffers moved to the MRU the dirty "Age" towards the LRU end of
the LRU list. This process is called Buffer Aging.
The Control file of a database is a small binary file necessary for the database to start and operate
successfully. A control file is updated continuously by Oracle during database use, so it must be
available for writing whenever the database is open. Each control file is associated with only one
Oracle Database. Among other things, a control file contains information such as
• The database name
• The timestamp of database creation
• The names and locations of associated database and online redo log files
• The current log sequence number
• Checkpoint information
Each time a data file or a online redo log file is added to, renamed in, or dropped from the database,
the control file is updated to reflect this physical structure change. These changes are recorded so that
• Oracle can identify the datafiles and online redo log files to open during database startup.
• Oracle can identify files that are required or available in case database recovery is necessary.
•
It is highly recommended that we backup up our Control file as soon as we make some change to the
physical structure of the database.
- 12 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
The PCTINCREASE parameter has been replaced by a parameter called OPTIMAL. This specifies the
optimal size of a rollback segment in bytes. It can also be specified in kilobytes or megabytes. The
RDBMS tries to keep the segment at its specified optimal size. The size is rounded up to the extent
boundary, which means that the RDBMS tries to have the fewest number of extents such that the total
size is greater than or equal to the size specified as OPTIMAL. If additional space is needed beyond
the optimal size, it will eventually deallocate extents to shrink back to this size. The process of
deallocating extents is performed when the head moves from one extent to the next. At this time, the
segment size is checked and the RDBMS determines if the next extent should be deallocated. The
extent can only be deallocated if there are no active transaction in it. If necessary, the RDBMS will
deallocate multiple extents at one time until the segment has shrunk back to its optimal size. The
RDBMS always deallocates the oldest inactive extents as they are the least likely to be used for read
consistency.
12. Checkpoint 0
Checkpoint process does not hamper the performance of the database but incorrect values for the
above two parameters can cause performance degradation.
13. Where analyzed information stored. The analyze information is stored in views like
• DBA_TABLES
• ALL_TABLES
• USER_TABLES
14. How to Activate/Deactivate Index.
There is nothing like activating an Index. But I can say "Oracle automatically maintains and uses indexes
once they are created." There is a possibility of forcing a specific index to be used in our query by using
Hints.
Example: SELECT (+INDEX name_idx) emp_id, name FROM EMP WHERE name = "ALAM";
The example can be considered as an Activation of an index. (If every reader agrees).
But we can deactivate or disable the indexes or make the optimizer not to use the indexes.
- 13 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
When executing the above statement Oracle optimizer will use the index available on the table to
resolve the query. But if we want oracle not to use the index we can rewrite the query as follows. Case
2: SELECT emp_id, name FROM EMPWHERE name ||' ' ="ALAM";
Two space management parameters, control the use of free space for inserts of and updates to the
row in data blocks.
PCTFREE: - The PCTFREE parameter is used to set the percentage of a block to be reserved (kept
free) for possible updates to rows that already are contained in the blocks.
PCTUSED: - After a data block becomes full, as determined by PCTFREE, oracle does not consider
the block is for the insertion of new rows until the percentage of the block being used falls below the
parameter PCTUSED.
When processing the queries, Oracles often requires TEMPORARY workspace for intermediate stages
of SQL statement processing. Oracle automatically allocates this disk space called a TEMPORARY
SEGMENT. Typically, oracle requires a temporary segment as a work area for sorting. Oracle does not
create a segment if the sorting operation can be done in memory or if oracle finds some other way to
perform the operation using indexes.
CREATE INDEX
SELECT …ORDER BY
SELECT DISTINCT…
SELECT … GROUP BY
SELECT … UNION
SELECT … INTERSECT
SELECT … MINUS
Unindexed joins
Certain correlated subqueries.
A profile is a named set of resource limits. If resources limits are turned on, oracle limits user 's use of
database and instance resources to that given in his profile. We can assign a profile to a user, and a
default profile to all users who do not have specific profiles.
Oracle stores data in DATA BLOCKS also called as oracle blocks. One data blocks correspond to a
specific number of bytes of physical database space on disk. It is set using the parameter
DB_BLOCK_SIZE usually 2K or 4K. No of blocks for an extents depends on the size of the Extent itself.
Extent is a logical unit of database storage space allocation made up of a number of contiguous data
blocks. The extents are allocated based on the storage parameters specified, while creating the objects.
- 14 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
No matter what type, each segment in a database is created with at least one extent to hold its data.
This extent is called the segment's Initial extent. Exception to this rule is the Rollback Segments; they
always have at least two extents.
ORACLE database is comprised of three types of files: one or more Data files, two or more Redo
log file, and one or more Control files.
3. What is a Tablespace?
A database is divided into logical storage units called TABLESPACES.
A Tablespace is used to group related logical structures together.
Every ORACLE database contains a Tablespace named SYSTEM, which is automatically created when
the database is created. The SYSTEM Tablespace always contains the data dictionary tables for the
entire database.
Each database is logically divided into one or more tablespaces. One or more data files are explicitly
created for each Tablespace.
6. What is a Schema?
- 15 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
Schema objects are logical structures that directly refer to the database's data. Schema objects include
tables, views, sequences, synonyms, indexes, clusters, database triggers, procedures, functions,
packages and database links.
Yes.
Yes.
Ans : B
5. LGWR process writes information intoa] Database files, b] Control files, c] Redolog
files, d] All the above. Ans : C
- 16 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
Ans : False
11. What is difference between a DIALOG WINDOW and a DOCUMENT WINDOW regarding
moving the window with respect to the application window a] Both windows behave the
same way as far as moving the window is concerned. b] A document window can
be moved outside the application window while a dialog window cannot be
moved
c] A dialog window can be moved outside the application window while a document
window cannot be moved Ans : C
12. What is the difference between a MESSAGEBOX and an ALERTa] A messagebox can be used
only by the system and cannot be used in user application while an alert can be used in user
application also.
b] A alert can be used only by the system and cannot be use din user application while an
messagebox can be used in user application also.
c] An alert requires an response from the userwhile a messagebox just flashes a message
and only requires an acknowledment from the user
d] An message box requires an response from the userwhile a alert just flashes a
message an only requires an acknowledment from the user
Ans : C
13. Which of the following is not an reason for the fact that most of the processing is done at the
server ?
a] To reduce network traffic. b] For application sharing, c] To implement
business rules centrally, d] None of the above Ans : D
16. What is the difference between a LIST BOX and a COMBO BOX ?
a] In the list box, the user is restricted to selecting a value from a list but in a
combo box the user can type in a value which is not in the list
b] A list box is a data entry area while a combo box can be used only for
control purposesc] In a combo box, the user is restricted to selecting a value from a list but
in a list box the user can type in a value which is not in the list d] None of the above Ans
:A
17. In a CLIENT/SERVER environment , which of the following would not be done at the client ?
- 17 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
18. Why is it better to use an INTEGRITY CONSTRAINT to validate data in a table than to use a
STORED PROCEDURE ?
a] Because an integrity constraint is automatically checked while data is
inserted into or
updated in a table while a stored procedure has to be specifically invoked b]
Because the stored procedure occupies more space in the database than a integrity
constraint definition
c] Because a stored procedure creates more network traffic than a integrity constraint
definition
Ans : A
22. The system variable that records the select statement that SQL * FORMS most recently used
to populate a block is
a] SYSTEM.LAST_
RECORDb]
SYSTEM.CURSOR_RECORD c]
SYSTEM.CURSOR_FIELD d]
SYSTEM.LAST_QUERY Ans: D
23. Which of the following is TRUE for the ENFORCE KEY fielda] ENFORCE KEY field characterstic
indicates the source of the value that SQL*FORMS uses to populate the field
b] A field with the ENFORCE KEY characterstic should have the INPUT ALLOWED
charaterstic turned off
a] Only 1 is
TRUEb] Only 2 is TRUE c] Both
1 and 2 are TRUE d] Both 1 and
2 are FALSE Ans : A
- 18 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
a] Characters wide
& 265 characters lengthb]
Characters wide & 265
characters length c] Characters
wide & 80 characters length d]
None of the above Ans : B
25. A FORM is madeup of which of the following objectsa] block, fields only, b] blocks, fields, pages
only,
c] blocks, fields, pages, triggers and form level procedures,
d] Only blocks.
Ans : C
27. The packaged procedure that makes data in form permanent in the Database is
a] Post b] Post form c] Commit form d] None of the above
Ans : C
28. Which of the following is TRUE for the SYSTEM VARIABLE $$date$$
a] Can be assigned to a global variable
b] Can be assigned to any field only during design time c]
Can be assigned to any variable or field during run time
d] None of the above
Ans : B
30. Identify the RESTRICTED packaged procedure from the followinga] USER_EXIT,
b] MESSAGE, c] BREAK, d] EXIT_FORM Ans : D
31. What is SQL*FORMSa] SQL*FORMS is a 4GL tool for developing & executing
Oracle based interactive
applications. b] SQL*FORMS is a 3GL tool for connecting to
the Database. c] SQL*FORMS is a reporting tool d] None of the above.
Ans : A
32. Name the two files that are created when you generate a form using Forms 3.0 a]
FMB & FMX, b] FMR & FDX, c] INP & FRM, d] None of the above
Ans : C
33. What is a triggera] A piece of logic written in PL/SQL b] Executed at the arrival of a
SQL*FORMS event c] Both A & B d] None of the above Ans : C
- 19 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
35. All datafiles related to a Tablespace are removed when the Tablespace is
droppeda] TRUE b] FALSE
Ans : B
- 20 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
47. Which of the following does not affect the size of the
SGAa] Database buffer b] Redolog buffer c] Stored
procedure d] Shared pool Ans : C
Ans : A
Ans : C
- 21 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
Ans : D
55. Which of the following statement is false a] Any procedure can raise an error and return an
user message and error number b] Error number ranging from 20000 to 20999 are
reserved for user defined messages c] Oracle checks Uniqueness of User defined
errors d] Raise_Application_error is used for raising an user defined error.
Ans : C
Ans : A
Ans : B
Ans : A
61. Which of the following is not correct about the “TABLE” datatype ?
a] Can contain any no of columns
b] Simulates a One-dimensional array of
unlimited sizec] Column datatype of any Scalar type d]
None of the above Ans : A
62. Find the ODD one out of the followinga] OPEN b] CLOSE c]
INSERT d] FETCH
Ans C
Ans : B
- 22 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
Ans : C
Ans : C
67. Does the Database trigger will fire when the table is
TRUNCATED ?
a] Yes
b] No Ans : B
Ans : A
71. EMPNO ENAME SAL
Select SAL from EMP E1 where 3 > ( Select count(*) from Emp E2
where E1.SAL > E2.SAL ) will retrieve
a] 3500,5000,2500
b] 5000,2850 c]
2850,5750 d]
5000,5750 Ans : A
- 23 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
74. Which is not part of the Data Definiton Language ?a] CREATE b] ALTER
c] ALTER SESSION Ans : C
Ans : D
76. EMPNO ENAME SAL
A822 RAMASWAMY 3500
A973 UMESH
Ans : C
77. If an UNIQUE KEY constraint on DATE column is created, will it accept the rows that are
inserted with SYSDATE ?
a] Willb]
Won’t Ans : B
Ans : C
- 24 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
Ans : A
Ans : B
Ans : C
Ans : A
86. What is built_in Subprogram ?a] Stored procedure & Function b] Collection of Subprogram c]
Collection of Packages d] None of the above Ans : D
87. GET_BLOCK property is aa] Restricted procedure b] Unrestricted procedure c] Library function d]
None of the above Ans : D
Ans : C - Please check the Correcness of this Answer ( The correct answer is 2 )
- 25 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
90. List of Values (LOV) supportsa] Single column b] Multi column c] Single or Multi column d] None
of the above
Ans : C
Ans : B
Ans : B
94. What type of file is used for porting Forms 4.5 applications to various platforms ?
a] .
FMB fileb]
.FMX file c]
.FMT file d]
.EXE file
Ans : C
96. When a form is invoked with CALL_FORM does Oracle forms issues SAVEPOINT ?
a] Y
esb] No Ans
:A
97. Can we attach the same LOV to different fields in Design time ?
a] Y
esb] No Ans
:A
98. How do you pass values from one form to another form ?
a] L
OVb]
Parameters
- 26 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
c] Local
variables d]
None of the
above
Ans : B
99. Can you copy the PROGRAM UNIT into an Object group ?
a] Yes
b] No
Ans : B
Ans : A
Ans : C
Ans : D
Ans : A
Ans : C
Ans : B
- 27 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
a] Yes
b] No
Ans : A
Ans : B
Ans D
Ans : D
Ans : D
111. What is the appropriate destination type to send the output to a printer ?
a] Screen b]
Previewer c] Either
of the above d] None
of the above
Ans : D
Ans : A
113. If the maximum records retrieved property of a query is set to 10, then a summary value will
be calculated a] Only for 10 records b] For all the records retrieved c] For all therecords in the
referenced table d] None of the above
Ans : A
114. With which function of a summary item in the COMPUTE AT option required ?
- 28 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
a] Sum b] Standard
deviation c] Variance
d] % of Total function
Ans : D
115. For a field in a repeating frame, can the source come from a column which does not exist in
the datagroup which forms the base of the frame ?
a] Yes
b] No
Ans : A
116. What are the different file extensions that are created by Oracle Reports ?
a] .RDF file & .RPX file
b] .RDX file & .RDF file
c] .REP file & .RDF file
d] None of the above
Ans : C
117. Is it possible to Disable the Parameter form while running the report ?
a] Yes
b] No
Ans : A
118.What are the SQL clauses supported in the link property sheet ?
a] WHERE & START WITH b]
WHERE & HAVING c} START WITH
& HAVING d] WHERE, START WITH
& HAVING
Ans : D
120. If two groups are not linked in the data model editor, what is the hierarchy between them ?
a] There is no hierarchy betweeen unlimked groups
b] The group that is right ranks higher than the group that is to the left
c] The group that is above or leftmost ranks higher than the group that is to right or below it
d] None of the above
Ans : C
Ans : B
- 29 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
Ans : B
Ans : A
Ans : B
Ans : A
Ans : B
Ans : A
128. The following parameters are optional in init.ora parameter file DB_BLOCK_SIZE,
PROCESS
a} TRUE
b] FALSE
Ans : B
Ans : B
Ans : B
131. It is very difficult to grant and manage common priveleges needed by different groups of
database users using roles
a] TRUE
b] FALSE
Ans : B
- 30 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
d] DBA_ROLLBACK_SEG
Ans : D
Ans : A
Ans : A
Yes. For example, if we had a table DEPT_SUMMARY, we could update the number of employees’
field as follows:
update DEPT_SUMMARY s
set NUM_EMPS = (
select count(1)
from EMP E
where E.DEPTNO = S.DEPTNO
);
Yes, using the ROWID field. The ROWID is guaranteed unique. There are many variations on this
theme, but the logic is to delete all but one record for each key value.
- 31 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
Yes! Those migrating from non-RDBMS application commonly ask this. This is definitely nonrelational
(enough to kill Codd and then make him roll in his grave) and is a feature I have not seen in the
competition.
The definitive example is in the example SCOTT/TIGER database, when looking at the EMP table
(EMPNO and MGR columns). The MGR column contains the employee number of the "current"
employee's boss.
You have available an extra pseudo-column, LEVEL, that says how deep in the tree you are. Oracle
can handle queries with a depth up to 255.
select LEVEL, EMPNO, ENAME, MGR from EMP connect by prior EMPNO = MGR start with MGR is
NULL;
You can get an "indented" report by using the level number to sub-string or lpad a series of spaces and
concatenate that to the string. select lpad(' ‘, LEVEL * 2) || ENAME ........
You use the start with clause to specify the start of the tree(s). More than one record can match the
starting condition.
One disadvantage of a "connect by prior" is that you cannot perform a join to other tables. Still, I have
not managed to see anything else like the "connect by prior" in the other vendor offerings and I like
trees. Even trying to do this programmatically in embedded SQL is difficult, as you have to do the
toplevel query, for each of them open a cursor to look for lower levelrows, for each of these...
The way around this is to use PL/SQL, open the driving cursor with the "connect by prior" statement,
and the select matching records from other tables on a row-by-row basis, inserting the results into a
temporary table for later retrieval.
Note that you can't trick Oracle by using CONNECT BY PRIOR on a view that does the join.
Imagine we have the EMP table and want details on the employee who has the highest salary. You
need to use a sub query.
You could get similar info on employees with the highest salary in their departments as follows
How can I get a name for a temporary table that will not clash?
Use a sequence, and use the number to help you build the temporary table name. Note that SQL-92
is developing specific constructs for using temporary tables.
- 32 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
Oracle maintains a live set of views that you can query to tell you what you have available. In V6, the
first two to look at are DICT and DICT_COLUMNS, which act as a directory of the other dictionary
views. It is a good idea to be familiar with these. Not all of these views are accessible by all users. If
you are a DBA you should also create private DBA synonyms by running
$ORACLE_HOME/rdbms/admin/dba_syn.sql in your account.
There is no way a column can be renamed using normal SQL. It can be done carefully by the DBA
playing around with internal SYS dictionary tables and bouncing the database, but this is not supported.
(I have successfully done it in V4 through V7). Do backup the database first unless you feel brave. I've
written a quick and dirty script rncol.sql to do this. If you can't figure out how to use it from the source
you definitely should not run it. You can use a similar dirty trick for changing ownership of tables if
storage space is limited.
There are a number of "beautifiers" for various program languages. The CB and indent programs for
the C language spring to mind (although they have slightly different conventions). As far as I know there
is no PD formatter for SQL available.
Given that there are PD general SQL parsers and that the SQL standards are drafted in something
close to BNF, maybe someone could base a reformatted based on the grammar.
Note that you CANNOT use CB and indent with Pro *C as both these programs will screw up the
embedded SQL code.
I have recently heard that Kumaran Systems (see Vendor list) have a Forms PL/SQL and SQL
formatter, but I do not now if they have unbundled it.
You *know* there are records for that day - but none of them are coming back to you.
What has happened is that your records are not set to midnight (which is the default value if time of
day not specified)?
You can either use to_char and to_date functions, which can be a bad move regarding SQL
performance, or you can say
WHERE date_field >= '18-jun-60' AND date_field < '19-jun-60'
When converting to dates from characters when you only have two characters for the year, the picture
format "RR" will be interpreted as the year based on a guess that that date is between 1950 and 2049.
There are a number of tables/views beginnings with V$ that holds gory details for performance
monitoring. These are not guaranteed to be stable from minor release to minor release and are for
DBAs only.
- 33 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
There are usually no real underlying tables (unlike SYS.OBJ$) and are dummied up by the RDBMS
kernel software in much the same way that UNIX System V.4 dummies up the files in the /proc or
/dev/proc directories.
If you have any code depending on these (and the widely used tools supplied by Oracle but unsupported
are in this category) then you need to verify that everything works each time you upgrade your
database. And when a major revision changes, all bets are off.
This question often gets the response WHERE ROWNUM <= 10 but this will not work (except
accidentally) because the ROWNUM pseudo column is generated before the ORDER or WHERE
clauses come into effect.
[email protected] (although it will be a bitch on a large table) suggested one elegant SQL-only
approach
I do not believe that straight SQL is the way to go for such problems when you have PL/SQL
available.
My approach is to use PL/SQL instead (in SQL*Plus):
Late news: index-descending hint to SQL works if you use a dummy restriction to force use of the
index. Needs V7, etc.
In SQL, you may need to control the rollback segment used as the default rollback segment may be too
small for the required transaction, or you may want to ensure that your transaction runs in a special
rollback segment, unaffected by others. The statement is as follows:
On a related note, if all you are doing are SELECTS, it is worth telling the database of this using the
following:
- 34 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
Say we are getting a list of names and codes and want it ordered by the name, using both EMP and
DEPT tables:
These three users are common in many databases. See the glossary entries under SCOTT, SCOTT
and SYS. Another common user/password is PLSQL/SUPERSECRET used for PL/SQL demo Stuff.
The simple answer is make sure you have them big enough and keep your transactions small, but that
is being a smartness. More recent versions of Oracle have an option for the session that you can set
that commits every so many DML statements. This is OK except for where you are doing your work in
a single statement rather than using PL/SQL and a loop construct.
Imagine you have a HUGE table and need to update it, possibly updating the key. You cannot update it
in one go because your rollback segments are too small. You cannot open a cursor and commit every
n records, because usually the cursor will close. You cannot have a number of updates of a few records
each because the keys may change - causing you to visit records more than once.
The solution I have used was to have one process select ROWID from the appropriate rows and pump
these (via standard I/O) to another process that looped around reading ROWIDs from standard input,
updating the appropriate record and committing every 10 records or so. This was very easy to program
and also was quite fast in execution. The number of locks and size of rollback segments required was
minimal.
If you are writing in Pro *C and use MODE=ORACLE, there are ways around it too, but not if you are
using MODE=ANSI.
OK, so this is really a DBA question, but it is worth putting in here because it involves SQL regardless
of interface.
First, look at the PASSWORD column in DBA_USERS. It looks like gobbledygook because it is an
encrypted password.However you can use this if you have saved it somewhere else. Say you want to
impersonate a user in a batch run overnight.First stash the gobbledygook password away somewhere,
grant connect to the user identified by some password you know and then run your batches using the
new known password.
To restore the password to what it was use the following syntax (which I think is undocumented).
How you organize your SQL and indices controls what access methods will be used. The following
ranking is valid for V6. I do not know about V7. QUERY PATH RANKING (lowest rank is the best)
Rank Path
1 ROWID = constant
2 Unique index column(s) = constant(s)
- 35 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
Views
---------
The typical example is the view on EMP limited to a department and not including salary. Also see
CHECK OPTION discussion.
Imagine we have created a view of EMP limited to a department, (where DEPTNO = 10). Now, that is
fine for querying, but you can still write records through this view (either by update or insert) with a value
of 20 for DEPTNO. (Next time you query the view, such records will be invisible.)
Now if you want to stop someone doing this (and consider whether you want them to be able to do
this or not very carefully) use the "check option" when creating the view:
Yes, that is the whole idea of views. The only thing Oracle stores for a view is the text of the definition.
When you select from a view, Oracle looks up the text used to define the view and then executes that
query.
Because view queries that involve sorting, grouping, etc can lead to a high performance overhead, it
might be better to write some reports with a procedural component that fills up a temporary table and
then does a number of queries from it.
While this is non-relational, it can be justified for some cases. Nevertheless, it is useful to have the view
definition in the database. You can then test the output from the view against the output from your
procedural manipulations. The view definition can also be used as the unambiguous gospel.
- 36 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
There are a number of dictionary views that include the text of views. You can select these quite happily,
but remember, if using SQL*Plus to use the SET command to fiddle with ARRAYSIZE, MAXDATA and
LONG parameters
- 37 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
- 38 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
- 39 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
DBA_TS_QUOTAS
Tablespace quotas for all users
DBA_USERS
Information about all users of the database
DBA_VIEWS
Text of all views in the database
DICT Synonym for DICTIONARY
DICTIONARY
Description of data dictionary tables and views
DICT_COLUMNS
Description of columns in data dictionary tables and views
DUAL
GLOBAL_NAME
global database name IND
Synonym for USER_INDEXES
INDEX_HISTOGRAM
statistics on keys with repeat count
INDEX_STATS
statistics on the b-tree
OBJ Synonym for USER_OBJECTS
RESOURCE_COST
Cost for each resource
ROLE_ROLE_PRIVS
Roles which are granted to roles
ROLE_SYS_PRIVS
System privileges granted to roles
ROLE_TAB_PRIVS
Table privileges granted to roles
SEQ Synonym for USER_SEQUENCES
SESSION_PRIVS
Privileges which the user currently has set
SESSION_ROLES
Roles which the user currently has enabled.
SYN Synonym for USER_SYNONYMS
TABLE_PRIVILEGES
Grants on objects for which the user is the grantor, grantee, owner, or an enabled role or PUBLIC
is the grantee
TABS Synonym for USER_TABLES
USER_AUDIT_OBJECT
Audit trail records for statements concerning objects, specifically: table, cluster, view, index,
sequence, [public] database link, [public] synonym, procedure, trigger, rollback segment, tablespace,
role, user
USER_AUDIT_SESSION
USER_AUDIT_STATEMENT
Audit trail records concerning grant, revoke, audit, noaudit and alter system
USER_AUDIT_TRAIL
Audit trail entries relevant to the user
USER_CATALOG
Tables, Views, Synonyms and Sequences owned by the user
USER_CLUSTERS
Descriptions of user's own clusters
USER_CLU_COLUMNS
Mapping of table columns to cluster columns
USER_COL_COMMENTS
Comments on columns of user's tables and views
USER_COL_PRIVS
Grants on columns for which the user is the owner, grantor or grantee
- 40 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
USER_COL_PRIVS_MADE
All grants on columns of objects owned by the user
USER_COL_PRIVS_RECD
Grants on columns for which the user is the grantee
USER_CONSTRAINTS
Constraint definitions on user's own tables
USER_CONS_COLUMNS
Information about accessible columns in constraint definitions
USER_DB_LINKS
Database links owned by the user
USER_DEPENDENCIES
Dependencies to and from a users objects
USER_ERRORS
Current errors on stored objects owned by the user
USER_EXTENTS
Extents comprising segments owned by the user
USER_FREE_SPACE
Free extents in tablespaces accessible to the user
USER_INDEXES
Description of the user's own indexes
USER_IND_COLUMNS
COLUMNs comprising user's INDEXes or on user's TABLES
USER_OBJECTS
Objects owned by the user
USER_OBJECT_SIZE
Sizes, in bytes, of various PL/SQL objects
USER_OBJ_AUDIT_OPTS
Auditing options for user's own tables and views
USER_RESOURCE_LIMITS
Display resource limit of the user
USER_ROLE_PRIVS
Roles granted to current user
USER_SEGMENTS
Storage allocated for all database segments
USER_SEQUENCES
Description of the user's own SEQUENCEs
USER_SNAPSHOTS
Snapshots the user can look at
USER_SNAPSHOT_LOGS
All snapshot logs owned by the user
USER_SOURCE
Source of stored objects accessible to the user
USER_SYNONYMS
The user's private synonyms
USER_SYS_PRIVS
System privileges granted to current user
USER_TABLES
Description of the user's own tables
USER_TABLESPACES
Description of accessible tablespaces
USER_TAB_COLUMNS
Columns of user's tables, views and clusters
USER_TAB_COMMENTS
Comments on the tables and views owned by the user
USER_TAB_PRIVS
Grants on objects for which the user is the owner, grantor or grantee
USER_TAB_PRIVS_MADE
- 41 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
- 42 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
- 43 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
Structured Query Language (SQL) is a language that provides an interface to relational database
systems. SQL was developed by IBM in the 1970s for use in System R. SQL is a defacto standard, as
well as an ISO and ANSI standard. SQL is often pronounced SEQUEL.
- 44 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
In common usage SQL also encompasses DML (Data Manipulation Language), for INSERTs,
UPDATEs, DELETEs and DDL (Data Definition Language), used for creating and modifying tables and
other database structures.
The development of SQL is governed by standards. A major revision to the SQL standard was
completed in 1992 called SQL2. SQL3 supports object extensions and will be (partially?) implemented
in Oracle8.
Choose one of the following queries to identify or remove duplicate rows from a table leaving one
record:
Method 1:
DELETE FROM TABLE_NAME A WHERE ROWID > (SELECT MIN (ROWID) FROM TABLE_NAME B
WHERE A.KEY_VALUES = B.KEY_VALUES); Method 2:
Method 3:
DELETE FROM MY_TABLE WHERE ROWID NOT IN (SELECT MAX(ROWID) FROM MY_TABLE
GROUP BY MY_COLUMN_NAME );
Method 4:
DELETE FROM MY_TABLE T1 WHERE EXISTS (SELECT 'X' FROM MY_TABLE T2 WHERE
T2.KEY_VALUE1 = T1.KEY_VALUE1 AND T2.KEY_VALUE2 = T1.KEY_VALUE2 AND T2.ROWID >
T1.ROWID);
Note: If you create an index on the joined fields in the inner loop, you for all intensive purposes
eliminate N^2 operations (no need to loop through the entire table on each pass by a record).
Create your table with a NOT NULL column (say SEQNO). This column can now be populated with
unique values:
How can I get the time difference between two date columns?
- 45 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
SELECT DEPT, SUM (DECODE (SEX,'M', 1,0)) MALE, SUM (DECODE (SEX,'F', 1,0)) FEMALE,
COUNT (DECODE (SEX,'M', 1,'F', 1)) TOTAL FROM MY_EMP_TABLE GROUP BY DEPT; How does
one count/sum RANGES of data values in a column?
A value x will be between values y and z if GREATEST (x, y) = LEAST(x, z). Look at this example:
SELECT F2, COUNT (DECODE (GREATEST (F1, 59), LEAST (F1, 100), 1, 0)) "RANGE 60-100",
COUNT (DECODE (GREATEST (F1, 30), LEAST (F1, 59), 1, 0)) "RANGE 30-59", COUNT (DECODE
(GREATEST (F1, 29), LEAST (F1, 0), 1, 0)) "RANGE 00-29" FROM MY_TABLE GROUP BY F2;
For equal size ranges it might be easier to calculate it with DECODE (TRUNC (value/range), 0,
rate_0, 1, rate_1...).
Example:
SELECT ENAME "NAME", SAL "SALARY", DECODE (TRUNC (F2/1000, 0), 0, 0.0,1, 0.1, 2, 0.2, 3,
0.31) "TAX RATE" FROM MY_TABLE;
SELECT * FROM TABLEX WHERE ROWID IN (SELECT ROWID FROM TABLEX WHERE
ROWNUM <= 7
MINUS
SELECT ROWID FROM TABLEX WHERE ROWNUM < 5); How
One can easily select all even, odd, or Nth rows from a table using SQL queries like this:
SELECT * FROM EMP WHERE (ROWID, 0) IN (SELECT ROWID, MOD (ROWNUM,4) FROM
EMP);
SELECT * FROM (SELECT ROWNUM RN, EMPNO, ENAME FROM EMP) TEMP WHERE MOD
(TEMP.ROWNUM, 4) = 0;
SELECT * FROM MY_TABLE A WHERE 10 >= (SELECT COUNT (DISTINCT MAXCOL) FROM
MY_TABLE B WHERE B.MAXCOL >= A.MAXCOL) ORDER BY MAXCOL DESC; How does one code
a tree-structured query?
This is definitely non-relational (enough to kill Codd and then make him roll in his grave) and is a
feature I have not seen in the competition.
- 46 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
The definitive example is in the example SCOTT/TIGER database, when looking at the EMP table
(EMPNO and MGR columns). The MGR column contains the employee number of the "current"
employee's boss.
You have available an extra pseudo-column, LEVEL, that says how deep in the tree you are. Oracle
can handle queries with a depth up to 255.
SELECT LEVEL, EMPNO, ENAME, MGR from EMP connect by prior EMPNO = MGR start with MGR
is NULL;
You can get an "indented" report by using the level number to sub-string or lpad a series of spaces
and concatenate that to the string.
You use the start with clause to specify the start of the tree(s). More than one record can match the
starting condition. One disadvantage of a "connect by prior" is that you cannot perform a join to other
tables. Still, I have not managed to see anything else like the "connect by prior" in the other vendor
offerings and I like trees. Even trying to doing this programmatic ally in embedded SQL is difficult as
you have to do the top level query, for each of them open a cursor to look for child nodes, for each of
these open a cursor. Pretty soon you blow the cursor limit for your installation.
The way around this is to use PL/SQL, open the driving cursor with the "connect by prior" statement,
and the select matching records from other tables on a row-by-row basis, inserting the results into a
temporary table for later retrieval.
The Oracle decode function acts like a procedural statement inside an SQL statement to return different
values or columns based on the values of other columns in the select statement. Some examples:
SELECT DECODE (SEX, 'M', 'MALE', 'F', 'FEMALE', 'UNKNOWN') FROM EMPLOYEES;
SELECT A, B, DECODE (ABS (A-B), A-B, 'A > B', 0, 'A = B','A < B') FROM TABLEX;
SELECT DECODE (GREATEST (A, B), A, 'A IS GREATER THAN B', 'B IS GREATER THAN A')...
Note: The DECODE function is not ANSI SQL and are rarely implemented in other RDBMS offerings.
It is one of the good things about Oracle, but use it sparingly if portability is required.
How can one dump/ examine the exact content of a database column?
DUMP (COL1)
-------------------------------------
Typ=96 Len=4: 65,66,67,32
For this example the type is 96, indicating CHAR, and the last byte in the column is 32, which is the
ASCII code for a space. This tells us that this column is blank-padded.
Oracle does not provide a way to DROP a column (reference: Enhancement Request 51118).
However, Joseph S. Testa wrote a DROP COLUMN package that can be downloaded from
- 47 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
Other workarounds:
2. Create table t2 as select <specific columns> from t1; Drop table t1;
Rename t2 to t1;
1. Rename t1 to t1_base;
Create view t1 <column list with new name> as select * from t1_base;
2. Create table t2 <column list with new name> as select * from t1; Drop table t1;
Rename t2 to t1;
From Oracle8 you can just type "password" from SQL* Plus, or if you need to change another user's
password, type "password username".
How does one find the next value of a sequence?
Perform an "ALTER SEQUENCE ... NOCACHE" to unload the unused cached sequence numbers from
the Oracle library cache. This way, no cached numbers will be lost. If you then select from the
USER_SEQUENCES dictionary view, you will see the correct high water mark value that would be
returned for the next NEXTVALL call. Afterwards, perform an "ALTER SEQUENCE ... CACHE" to
restore caching.
You can use the above technique to prevent sequence number loss before a SHUTDOWN ABORT, or
any other operation that would cause gaps in sequence values.
You can use the SQL* Plus COPY command instead of snapshots if you need to copy LONG and
LONG RAW variables from one location to another. E.g.
COPY TO SCOTT/TIGER@REMOTE
CREATE IMAGE_TABLE USING SELECT
IMAGE_NO, IMAGE - FROM IMAGES;
Note: If you run Oracle8, convert your LONGs to LOBs, as it can be replicated.
PL/SQL is Oracle's Procedural Language extension to SQL. PL/SQL's language syntax, structure and
data types are similar to that of ADA. The language includes object oriented programming techniques
such as encapsulation, function overloading, information hiding (all but inheritance) and is commonly
used to write data-centric programs to manipulate Oracle data.
- 48 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
PL/SQL V2.2, available with Oracle7.2, implements a binary wrapper for PL/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 (somewhat 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:
One can use the DBMS_OUTPUT package to write information to an output buffer. This buffer can be
displayed on the screen from SQL* Plus if you issue the SET SERVEROUTPUT ON; command. For
example:
begin
dbms_output.put_line ('Look Ma, I can print from PL/SQL!!!');
end;
/
But what if you forget to set server output on? No problem, just type SET SERVEROUTPUT ON once
you remember, and then EXEC NULL; If you haven't cleared the DBMS_OUTPUT buffer with the
disable or enable procedure, SQL* Plus will display the entire contents of the buffer when it executes
this dummy PL/SQL block.
Included in Oracle 7.3 is an UTL_FILE package that can read and write operating system files. 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('/tmp', 'myfile', 'w');
UTL_FILE.PUTF(fileHandler, 'Look ma, I''m writing to a file!!!\n');
UTL_FILE.FCLOSE(fileHandler);
EXCEPTION
WHEN utl_file.invalid_path THEN
raise_application_error(-20000, 'ERROR: Invalid path for file or
path not in INIT.ORA.');
END;
From PL/SQL V2.1 one can use the DBMS_SQL package to execute dynamic SQL statements. E.g.:
- 49 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
Another example:
How does one get the value of a sequence into a PL/SQL variable?
i := sq_sequence.NEXTVAL;
In Oracle7 there is no direct way to execute an operating system command from PL/SQL. However,
one can write an external program (using one of the pre-compiler languages, OCI or Perl with Oracle
access modules) to act as a listener on a DBMS_PIPE. Your PL/SQL then places requests to run
commands in the pipe, the listener picks it up and runs them. Results are passes back on a different
pipe. For a Pro *C example, see chapter 8 of the Oracle Application Developers Guide. This example
is also on the Support Notes CD-ROM that all supported customers should be getting quarterly. Just
search on "DBMS_PIPE".
In Oracle8 you can call external 3GL code in a dynamically linked library (DLL or shared object). So you
just write a library in C doing what you want, ie in your case a host function taking the command line as
input argument. And that function will be callable from PL/SQL.
- 50 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
Let's say I had a PL/SQL block and I wanted to do a "ls -l" to get a directory listing. Is there any way
to do that?
In C Language, I can do
{
x = system("ls -l");
}
The way most people do that is to use the pipe facility of the DBMS kernel. Set up a pipe for use by a
sender (the PL/SQL program that needs to invoke a command) and a receiver, written in Pro *C. This
is responsible for executing the command piped by the sender. Maybe there are some tools around so
one doesn't need to code this, as it involves a listener and multiple server processes on your machine.
Alternatively I have a more complex solution, which uses a table to pass arguments and the command
to execute - just as the DBMS_PIPE package does internally. You would insert a row into the table and
the listener would execute a command, passing back succession status and indicating "in progress" on
long-running commands. This tool allows for non-blocking execution of commands.
DECLARE
CURSOR dept_cur IS
SELECT deptno
FROM dept
ORDER BY deptno;
-- Employee cursor all employees for a dept number
CURSOR emp_cur (v_dept_no DEPT.DEPTNO%TYPE) IS
SELECT ename
FROM emp
WHERE deptno = v_dept_no;
BEGIN
FOR dept_rec IN dept_cur LOOP
dbms_output.put_line('Employees in Department
'||TO_CHAR(dept_rec.deptno));
FOR emp_rec in emp_cur(dept_rec.deptno) LOOP
dbms_output.put_line('...Employee is '||emp_rec.ename);
END LOOP;
END LOOP;
END;
Yes, the max size is not an explicit byte limit, but related to the parse tree that is created when you
compile the code.
You can run the following select statement to query the size of an existing package or procedure:
I switched the page size to 11x8.5, but the printer still prints in portrait.
- 51 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
Even though you set the page size in the report properties, there is a another variable in the system
parameters section under the data model in the object navigator called orientation. This sets the printer
orientation. Oracle starts by setting it to "default" which means that no matter how you set the page
size, the user's default printer setup will be used. You can also set it to either "Landscape" or "Portrait"
to force the printer orientation no matter what the user has set as default. These sorts of picky, minor
details are the ones, which are invariably forgotten when you are designing your report and are the
reason I created our two report templates, reptmp_p and reptmp_l (portrait and landscape). For anyone
who wants a consistent look in their reports I strongly recommend building a similar pair to save yourself
an ulcer, unless you actually like starting from scratch every time.
I moved this field into that repeating frame, but I'm still getting a "frequency below it's group" error.
Moving fields around does not change what enclosing object is considered it's parent group. Oracle
carefully remembers what repeating frame a field was originally placed in and assigns that as it's parent.
If you then reference a column further down the line of the query structure it will return that error. If you
are not exactly sure which repeating frame a field belongs to, try dragging it out of all of them. Whichever
frame will not allow it to escape is it's parent. To change a field's parent, first click on the lock button on
the speed button bar. It should now look like an unlocked padlock. Now all of the fields on the layout
can be repositioned regardless of their original parent items. When you are satisfied with the
repositioning click the lock button again to lock the layout. Oracle will parse the layout and assumes
that any item fully enclosed in a repeating frame is a child object of that frame. This can be confirmed
again by trying to drag an object out of it's parent. (CTRL - Z or EDIT…. UNDO will put it back where it
came from)
Sometimes, for unknown and mysterious reasons, this method does not work. The alternative in this
case is to highlight the field (or fields), cut it (CTRL-X), and then paste it into the desired frame. The
paste does not initially set it into the right frame, but if you drag and drop it there before clicking on any
other objects, and then click on something else, Oracle will usually figure what your intent was and
assign the object(s) as a child of that frame. This is my preferred method of changing a field's parent
as it works much more consistently then the unlock/lock method. One note though, if you are
reassigning a group of fields, make sure the frame you are going to move them into is large enough to
accept the whole group at once before you do the cut/paste. If you do the paste and then try to grow
the frame to fit, you will have to cut and paste again. Once you de-select an object that has just been
pasted, Oracle will assign it as a child of whatever it is in at the time.
If this technique also fails, you are probably going to have to delete and then recreate the objects within
the desired frame. If the object has triggers attached, save yourself some typing by creating the new
object in the right frame, copying over the trigger code, and then deleting the old object.
I must put a repeating frame around these fields. How do I do this easily?
Well congratulations, you have just discovered one of the main reasons why good planning goes a long
way. Oracle looks at the layout as a sort of layered inheritance model such that anything created on top
of and completely inside another object is by definition a child of that object. Creation order is therefor
critical to the layout process. This means that placing a repeating frame on top of a field but larger than
that field fails the ownership criteria. At best, if the new frame is fully enclosed within the same higher
level frame as the field thenthe two will be considered sibling children of the higher level frame.
From this point you have two options. First, you can place the new repeating frame in the correct place
and then, use the techniques shown above in the "I moved this field but am still getting a frequency
error" to reassign the fields into the new frame. There is also a second choice (which can also be used
as a solution to the above). Go ahead and draw the new frame around the fields you want to have
placed in it. Now if you try to click on one of the fields you will not be able to as they are fully covered
by the new frame. Now go to the "Arrange" menu. You will find the options send to back, bring to front,
move forwards and move backwards. These are used to alter an object position in the Reports layer
ordering. You use the "send backwards" option to move the frame backwards until all of the fields have
popped to the front and are now enclosed in it. Oracle reassigns the new repeating frame as each
object's parent as they pop to the front.
- 52 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
Note that you can only move an object back and forth amongst it's siblings. You cannot set it back below
its parent, or in front of its children. This means that once an object has popped to the front and had a
reassignment of parent, you cannot move it back using these tools.
Why does part of a row sometimes get shifted to the next page, but not all of it?
This is due to the way the scan works when Oracle is parsing the layout. If the tops of all the fields in a
row are aligned and the fields are all of the same height and font, they should all stay together. I suspect,
however, that Reports bases it's decision on the printed size rather than the field size you define to
determine which objects are too large and must be shifted to the next page. This means that even if
you set two fields top-aligned with the same height and font but one of them is bolded, the bolded field
could get shifted to the next page due to it's bigger footprint. The solution is to put the whole row into a
regular frame, which is page protected.
The print condition type First, All, All but first, Last, All but last refer to the frequency with which you want
to appear based upon the setting of the print condition object. A print condition object of Enclosing
Object is whichever object encloses the current object (could be the parent or a frame within the parent),
while Anchoring Object is the parent object (unless you have explicitly anchored the object in which
case it is the object to which it is anchored). The key here is that this is about the pages on which the
Print Condition Object appears, not the current object. Oracle views First as the first page on which any
part of the Print Condition Object is printed, likewise Last is the last page on which any part of the Print
Condition Object is printed. For objects inside a repeating frame, this condition is re-evaluated for each
instance of the frame.
As an example, assume we have created a field inside a repeating frame with Print Condition Object
set to 'anchoring object', and Print Condition Typeset to 'All But First'. On every instance of that
repeating frame which is printed entirely within a single page, our object will not print. However, if an
instance of that frame spans more than one page then our object will print on the second and every
subsequent page that this instance of the repeating frame spans.
For most objects you will not have to play with this print condition setting as the default setting is pretty
good at determining what pages to print on, even though it only chooses between 'first' and 'last'. Only
such things as heading objects you want reprinted on multiple pages are normally candidates for fooling
around with this setting.
How do I create a truly dynamic 'where' condition which the user can input on the parameter form for
my select statement
While setting a simple parameter for use in defining the select statement, such as a date, bill_period_id
etc. Is simple, there are times when you may wish to allow a user to add any "where" statement they
wish. However, if you create a VARCHAR user variable and try to reference it as an SQL condition (
e.g. Select * from account where :user condition) you will get an error. The secret is that the variable
must be initialized to a valid SQL condition before the Data Model will accept it. This is done in the
"Initial Value" spot on the variable's property form. The usual default is "1 = 1" which simply means all
rows meeting whatever other conditions are included in the select statement will pass this condition if
the user does not change it in the parameter form.
Quite simply, you can't. Once the BeforeReport trigger has fired, reports locks down the user parameters
until the report is finished. Oh, I know you can put a statement into a layout trigger at design time and
the compiler will accept it, but the moment you run the report you will get a nasty error and the report
will die. Why they couldn't catch those problems at compile time I have no idea, except that it probably
uses the same PL/SQL compiler as Forms which uses that same syntax for the perfectly acceptable
function of changing field values.
That being said, there is valid technique to mimic having a user variable, which can be changed over
the course of the report execution. What you have to do is create a PL/SQL package that contains a
- 53 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
variable as well as the functions to read and write to that variable. Since variables inside a package are
both local to that package and persistent over the duration of the run, you use this to save and change
your variable value. I know that this seems like overkill, but it is the most efficient way of handling an
issue that is very rarely encountered. As you can probably guess, this technique is a last resort to finding
an SQL work around if one exists.
How do I set the initial values of parameters for the parameter form at runtime?
This is what the BeforeForm trigger is primarily used for. Even if you have used a select statement to
create a lookup list for the parameter, this statement is fully parsed before the parameter form is opened.
Simply setting the parameter to a given value in the BeforeForm trigger will select that option as the
default value displayed to the user. For example, assume you have a parameter called p_input_date,
which is intended to hold an invoice date. The following example will select the most recent invoice date
as the default, and note that it properly handles exceptions to ensure that the report does not arbitrarily
die if this default setting fails. Note also that like all report triggers, it must return a true or false value.
Why can't I highlight a bunch of fields and change their entire format masks or prints conditions at
once?
You can. If you highlight a bunch of objects and then right click and select "properties..", Oracle gives
you a stacked set of the individual properties forms for each of the selected objects. While this may be
useful for some things, it requires changing values individually for each object. However, instead you
can select the group of fields and then select "Common properties" from the "Tools" menu which will
allow you to set the format mask , print conditions etc. for the whole set of objects at once.
Triggers are intended to simply provide a true or false return value to determine whether an object
should be, printed. It is generally not allowed to change any values held in the cursor, make changes
to the database, or change the value of it's objects value. That being said, there is a highly unpublicized
method of doing just that using the SRW. Set_Field_Char procedure. The syntax is
SRW.Set_Field_char (0,) and the output of the object that the current trigger is attached to will be
replaced by. There are also RW.set_fileld_num and SRW.set_field_date for numeric or date fields.
While these options do work, they should only be used if a suitable NVL or DECODE statement in the
original query is not possible as they are much, much slower to run. Also, note that this change of value
only applies to the formatted output. It does not change the value held in the cursor and so can not be
used for evaluating summary totals.
SQL* Loader is a utility used for moving data from external files into the Oracle database. Its syntax is
similar to that of the DB2 Load utility, but comes with more options. SQL* Loader supports various load
formats, selective filters, and multi-table loads.
One load data into the Oracle database by using the sqlldr (sqlload on some platforms) utility. Look at
the following example:
- 54 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
load data
infile *
replace
into table departments
( dept position (02:05) char(4),
deptname position (08:27) char(20)
)
begindata
COSC COMPUTER SCIENCE
ENGL ENGLISH LITERATURE
MATH MATHEMATICS
POLY POLITICAL SCIENCE
Yes, look at the following control file examples. In the first we will load delimited data (variable length):
LOAD DATA
INFILE *
INTO TABLE load_delimited_data
FIELDS TERMINATED BY "," OPTIONALLY ENCLOSED BY '"'
TRAILING NULLCOLS
( data1,
data2
)
BEGINDATA
11111,AAAAAAAAAA
22222,"A,B,C,D,"
If you need to load positional data (fixed length), look at the following control file example:
LOAD DATA
INFILE *
INTO TABLE load_positional_data
( data1 POSITION(1:5), data2
POSITION(6:15)
)
BEGINDATA
11111AAAAAAAAAA
22222BBBBBBBBBB
LOAD DATA
INFILE *
INTO TABLE modified_data
( rec_no "my_db_sequence.nextval",
region CONSTANT '31',
time_loaded "to_char(SYSDATE, 'HH24:MI')",
data1 POSITION(1:5) ":data1/100",
data2 POSITION(6:15) "upper(:data2)"
- 55 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
)
BEGINDATA
11111AAAAAAAAAA
22222BBBBBBBBBB
LOAD DATA
INFILE 'mail_orders.txt'
BADFILE 'bad_orders.txt'
APPEND
INTO TABLE mailing_list
FIELDS TERMINATED BY ","
( addr,
city,
state,
zipcode,
mailing_addr "decode(:mailing_addr, null, :addr,:mailing_addr)",
mailing_city "decode(:mailing_city, null, :city,:mailing_city)",
mailing_state
)
LOAD DATA
INFILE *
REPLACE INTO TABLE EMP
WHEN empno != ' '
( empno POSITION(1:4) INTEGER EXTERNAL,
ename POSITION(6:15) CHAR, deptno
POSITION(17:18) CHAR, mgr POSITION(20:23)
INTEGER EXTERNAL
)
INTO TABLE proj
WHEN projno != ' '
( projno POSITION(25:27) INTEGER EXTERNAL,
empno POSITION(1:4) INTEGER EXTERNAL
)
Can one selectively load only the data that you need?
Look at this example, (01) is the first character, (30:37) are characters 30 to 37:
LOAD DATA
APPEND INTO TABLE db_trace_19980517
WHEN (01) <> 'H' and (01) <> 'T' and (30:37) = '19980517'
(
region CONSTANT '31',
service_key POSITION(01:11) INTEGER EXTERNAL,
call_b_no POSITION(12:29) CHAR
)
One can create one logical record from multiple physical records using one of the following two
clauses:
CONCATENATE: - use when SQL* Loader should add the same number of physical records together
to form one logical record.
- 56 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
CONTINUEIF - use if a condition indicates that multiple records should be treated as one, e.g. '#' in
line 1.
How can get SQL* Loader to commit only at the end of the load file?
You can not, but by setting the ROWS= parameter to a large value, committing can be reduced. Make
sure you have big rollback segments ready when you use a high value for ROWS=.
1. A very simple but easily overlooked hint, do not have any indexes and/or constraints (primary
key) on your load tables during the load process. This will significantly slowdown load times even
with ROWS= set to a high value.
2. Add the following option in the command line: DIRECT=TRUE. This will effectively bypass most
of the RDBMS processing. However, there are cases when you can't use direct load. Refer to
chapter 8 on Oracle server Utilities manual.
3. Turn off database logging by specifying the UNRECOVERABLE option. This option can only be
used with direct data loads.
Oracle doesn't supply any data unload tools. However, you can use SQL* Plus to select and format
your data and then spool it to a file:
set echo off newpage 0 space 0 pagesize 0 feed off head off
trimspool on spool oradata.txt
select col1 || ',' || col2 || ',' || col3
from tab1 where col2 = 'XYZ';
spool off
oracle server
/ \
Oracle database oracle instance
/ \
Physical database structure Logical database structure
(An oracle database's physical structure is datermined by the O.S files that constitute database)
Oracle Instance
- 57 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
System global area(SGA) is an area of memory used for database admin. shared by the
database servers. The combination of the background process and memory buffers is called an
instance.
Oracle Instance
/ \
User process Oracle process
/ \
server process background process
1. Which package construct must be declared and defined within the package body?
After creating this trigger, you test it by inserting a row into the PLAYER table. You receive
this Error message
- 58 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
The storage of the PLAYER table is so fragmented that the trigger cannot run successfully. Triggers
cannot change data in the primary key, foreign key, or unique key of a constraining table. (Answer)
References to sequences are not allowed in triggers.
Triggers, unless otherwise specified, are read only.
3. You have been granted the necessary privilege to invoke a function created by another
developer. You are having problems calling this function from your procedure & want to
contact the developer who created the function. Which table would you query to determine
the owner of this function?
• USER_OBJECTS
• ALL_FUNCTIONS
• ALL_OBJECTS (Answer) • USER_FUNCTION_CODE
PROCEDURE UPD_PLAYER_STAT
(V_ID IN NUMBER, V_AB IN NUMBER DEFAULT 4, V_HITS IN NUMBER)
IS
BEGIN
UPDATE PLAYER_BAT_STAT SET AT_BATS = AT_BATS + V_AB, HITS = HITS + V_HITS
WHERE PLAYER_ID = V_ID;
COMMIT;
END UPD_PLAYER_STAT;
PROCEDURE ADD_PLAYER
(V_ID IN NUMBER, V_LAST_NAME VARCHAR2, V_SALARY NUMBER)
IS
BEGIN
INSERT INTO PLAYER(ID,LAST_NAME,SALARY) VALUES (V_ID, V_LAST_NAME,
V_SALARY);
UPD_PLAYER_STAT(V_ID,0,0);
END ADD_PLAYER;
END BB_PACK;
/
• The outside procedure and the package body are invalidated. (Answer)
• Only the standalone procedure is invalidated.
• Only the package body is invalidated.
• There will be no effect.
- 59 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
Answer:
CREATE OR REPLACE FUNCTION CALC_PLAYER_AVG
(V_ID IN NUMBER)
RETURN NUMBER
IS
V_AVG NUMBER;
BEGIN
SELECT HITS/AT_BATS
INTO V_AVG
FROM PLAYER_BAT_STAT
WHERE PLAYER_ID = V_ID;
RETURN (V_AVG);
END;
• PACKAGE BODY
- 60 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
• DATABASE TRIGGER
• PACKAGE SPECIFICATION (Answer)
• each procedure's DECLARE section
• USER_PROCEDURES
• USER_PROCS
• USER_OBJECTS (Answer)
• USER_PLSQL_UNITS
Which statement should be added if you want this trigger to execute just once for each
INSERT operation on the PLAYER table?
9. Which statement best describes the difference between auditing objects with triggers and auditing
objects within the server?
- 61 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
PROCEDURE UPD_PLAYER_STAT
(V_ID IN NUMBER, V_AB IN NUMBER DEFAULT 4, V_HITS IN NUMBER)
IS
BEGIN
UPDATE PLAYER_BAT_STAT SET AT_BATS = AT_BATS + V_AB, HITS = HITS + V_HITS
WHERE PLAYER_ID = V_ID;
COMMIT;
END UPD_PLAYER_STAT;
PROCEDURE ADD_PLAYER
(V_ID IN NUMBER, V_LAST_NAME VARCHAR2, V_SALARY NUMBER)
IS
BEGIN
INSERT INTO PLAYER(ID,LAST_NAME,SALARY) VALUES (V_ID, V_LAST_NAME,
V_SALARY);
UPD_PLAYER_STAT(V_ID,0,0);
END ADD PLAYER;
END BB PACK;
/
12. One of your procedures must create a table during execution. Which Oracle supplied
package must you use to accomplish this task?
• DBMS_CREATE_OBJECT
• DBMS_SQL (Answer)
• DBMS_PIPE
• DBMS_TRANSACTION
- 62 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
RETURN NUMBER
IS
v_team_tax_amnt number(11,2);
BEGIN
SELECT SUM(SALARY) * .07
INTO v_team_tax_amnt
FROM PLAYER
WHERE TEAM_ID = V_TEAM_ID;
RETURN V_TEAM_TAX_AMNT;
END;
Which two statements will successfully invoke this function in SQL* Plus? (Choose two.)
• EXECUTE TEAM_TAX(1)
• VARIABLE G_TEAM_TAX_AMNT NUMBER
EXECUTE :G_TEAM_TAX_AMNT := TEAM_TAX(1)
• RUN TEAM_TAX(1)
• SELECT NAME, TEAM_TAX(ID)
FROM TEAM
WHERE TEAM_TAX(ID) > 300000;
• TEAM_TAX(ID);
PROCEDURE UPD_PLAYER_STAT
(V_ID IN NUMBER, V_AB IN NUMBER DEFAULT 4, V_HITS IN NUMBER)
IS
BEGIN
UPDATE PLAYER_BAT_STAT
SET AT_BATS = AT_BATS + V_AB,
HITS = HITS + V_HITS
WHERE PLAYER_ID = V_ID;
COMMIT;
END UPD_PLAYER_STAT;
PROCEDURE ADD_PLAYER
(V_ID IN NUMBER, V_LAST_NAME VARCHAR2, V_SALARY NUMBER)
IS
BEGIN
INSERT INTO PLAYER(ID,LAST_NAME,SALARY)
VALUES (V_ID, V_LAST_NAME, V_SALARY);
UPD_PLAYER_STAT(V_ID,0,0);
END ADD_PLAYER;
END BB_PACK;
- 63 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
• PACKAGE SPECIFICATION
• DECLARE SECTION of the first procedure declared in the package.
• PACKAGE BODY (Answer)
• PACKAGE EXCEPTION
PROCEDURE UPD_PLAYER_STAT
(V_ID IN NUMBER, V_AB IN NUMBER DEFAULT 4, V_HITS IN NUMBER)
IS
BEGIN
UPDATE PLAYER_BAT_STAT
SET AT_BATS = AT_BATS + V_AB,
HITS = HITS + V_HITS
WHERE PLAYER_ID = V_ID;
COMMIT;
VALIDATE_PLAYER_STAT(V_ID); END
UPD_PLAYER_STAT;
PROCEDURE ADD_PLAYER
(V_ID IN NUMBER, V_LAST_NAME VARCHAR2, V_SALARY NUMBER)
IS
BEGIN
INSERT INTO PLAYER(ID,LAST_NAME,SALARY) VALUES (V_ID, V_LAST_NAME,
V_SALARY);
UPD_PLAYER_STAT(V_ID,0,0); END
ADD_PLAYER;
END BB_PACK;
SCOTT is responsible for updating the statistics of players. He cannot add players. Which
command must you issue to allow SCOTT the use of this package to accomplish his job?
16. Your can enter new ballplayers to the PLAYER table from different Oracle Forms applications
and from an application written in C. For each new ballplayer, a record must be inserted
into the PLAYER_BAT_STAT table. Which action should you perform to accomplish this
requirement?
- 64 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
17. Which table and column can you query to see all procedures and functions that have been
marked invalid?
18. Your procedure references a function created by another application developer. You need
to contact this person to discuss the code contained in the function. Which table can you
query to determine the owner of this function?
• USER_DEPENDENCIES (Answer)
• USER_REFERENCES
• USER_CONSTRAINTS
• USER_LINKS
• Both the ADD_PLAYER and UPD_PLAYER_STAT procedures are marked invalid. (Answer)
• The ADD_PLAYER procedure is marked invalid.
• The UPD_PLAYER_STAT procedure is marked invalid.
• Neither procedure is marked invalid.
21. Examine this package:
- 65 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
PROCEDURE ADD_PLAYER
(V_ID IN NUMBER, V_LAST_NAME VARCHAR2, V_SALARY NUMBER)
IS
BEGIN
INSERT INTO PLAYER(ID,LAST_NAME,SALARY)
VALUES (V_ID, V_LAST_NAME, V_SALARY);
UPD_PLAYER_STAT(V_ID,0,0); END
ADD_PLAYER;
END BB_PACK;
SCOTT is responsible for adding new ball players to the system. Which command must you
issue to allow SCOTT the use of this package to accomplish his job?
Which set of commands must be added to handle the non-predefined error: ORA-02292?
• STATS_EXIST_EXCEPTION NUMBER;
PRAGMA EXCEPTION_INIT(STATS_EXISTS_EXCEPTION, -2292);
• STATS_EXIST_EXCEPTION EXCEPTION;
PRAGMA EXCEPTION_INIT(-2292, STATS_EXISTS_EXCEPTION);
• STATS_EXIST_EXCEPTION EXCEPTION;
PRAGMA EXCEPTION_INIT(STATS_EXISTS_EXCEPTION, -2292);
• STATS_EXIST_EXCEPTION EXCEPTION;
PRAGMA EXCEPTION_INIT(STATS_EXISTS_EXCEPTION, 2292);
23. Which statement will successfully create the procedure ADD_PLAYER in SQL* Plus?
(Answer)
CREATE OR REPLACE PROCEDURE ADD_PLAYER
(V_ID IN NUMBER, V_LAST_NAME VARCHAR2)
IS
BEGIN
INSERT INTO PLAYER (ID,LAST_NAME) VALUES (V_ID, V_LAST_NAME);
- 66 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
COMMIT;
END;
PROCEDURE ADD_PLAYER
(V_ID IN NUMBER, V_LAST_NAME VARCHAR2)
IS
BEGIN
INSERT INTO PLAYER (ID,LAST_NAME) VALUES (V_ID, V_LAST_NAME);
COMMIT;
END;
PROCEDURE UPD_PLAYER_STAT
(V_ID IN NUMBER, V_AB IN NUMBER DEFAULT 4, V_HITS IN NUMBER)
IS
BEGIN
UPDATE PLAYER_BAT_STAT
SET AT_BATS = AT_BATS + V_AB,
HITS = HITS + V_HITS
WHERE PLAYER_ID = V_ID;
COMMIT;
END UPD_PLAYER_STAT;
PROCEDURE ADD_PLAYER
(V_ID IN NUMBER, V_LAST_NAME VARCHAR2, V_SALARY NUMBER)
IS
BEGIN
INSERT INTO PLAYER(ID,LAST_NAME,SALARY) VALUES (V_ID, V_LAST_NAME,
V_SALARY);
- 67 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
UPD_PLAYER_STAT(V_ID,0,0); END
ADD_PLAYER;
END BB_PACK;
Which statement will successfully execute the ADD_PLAYER procedure from within SQL*
Plus?
PROCEDURE UPD_PLAYER_STAT
(V_ID IN NUMBER, V_AB IN NUMBER DEFAULT 4, V_HITS IN NUMBER)
IS
BEGIN
UPDATE PLAYER_BAT_STAT
SET AT_BATS = AT_BATS + V_AB,
HITS = HITS + V_HITS
WHERE PLAYER_ID = V_ID;
COMMIT;
END UPD_PLAYER_STAT;
PROCEDURE ADD_PLAYER
(V_ID IN NUMBER, V_LAST_NAME VARCHAR2, V_SALARY NUMBER)
IS
BEGIN
INSERT INTO PLAYER(ID,LAST_NAME,SALARY) VALUES (V_ID, V_LAST_NAME,
V_SALARY);
UPD_PLAYER_STAT(V_ID,0,0); END
ADD_PLAYER;
END BB_PACK;
Which statement will successfully execute the UPD_PLAYER_STAT procedure from within
SQL* Plus?
26. Adding ball players to the PLAYER table is limited to the baseball season. You decide to
create a database trigger.
- 68 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
Which trigger timing should you use to prevent users from inserting into this table during the
offseason?
on-change
after
before on-
insert
• Procedures and functions are re-parsed for multiple users by exploiting shared SQL areas.
• Procedures and functions avoid re-parsing for multiple users by exploiting shared SQL areas.
(Answer)
• Procedures and functions increase the number of calls to the database.
• Testing of procedures and functions requires the database to be restarted to clear out shared
SQL areas for future access.
28. Which statement must be added to make this trigger execute after updating the SALARY
column of the PLAYER table?
30. Which code is stored in the database when a procedure or function is created in SQL* Plus?
• only SOURCE CODE
• both SOURCE CODE and P-CODE (Answer)
• only P-CODE
• neither SOURCE CODE or P-CODE
31. The ADD_PLAYER procedure residing in your local database in Austin executes the
UPD_PLAYER_STAT procedure residing in Chicago. The procedure in Chicago has just
been changed and recompiled.
• An error will occur next time the ADD_PLAYER procedure is executed. (Answer)
• There will be no effect if the UPD_PLAYER_STAT procedure compiled successfully.
• The ADD_PLAYER procedure will automatically recompile the next time you invoke it.
- 69 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
A user informs you that she is getting an error whenever she inserts a row into the PLAYER
table. After researching the problem, you realize that the database trigger on the
PLAYER table is inserting a row into the PLAYER_BAT_STAT table. The PLAYER_BAT_STAT
table is offline.
Which action should you take to allow users to insert into the PLAYER table until the
PLAYER_BAT_STAT table is online?
Which two statements will successfully invoke this function in SQL* Plus? (Choose two.)
• EXECUTE CALC_PLAYER_AVG(31);
• SELECT CALC_PLAYER_AVG(31) FROM PLAYER_BAT_STAT;
• VARIABLE G_AVG NUMBER
EXECUTE :G_AVG := CALC_PLAYER_AVG(31);
• CALC_PLAYER_AVG(31);
• START CALC_PLAYER_AVG(31);
34. For every new ballplayer added to the PLAYER table, a record must be inserted into the
PLAYER_BAT_STAT table. You have written a trigger to accomplish this task.
• STATEMENT
• PRE-INSERT
• AFTER (Answer)
• BEFORE
- 70 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
• Create a SQL* Plus script file that contains each procedure's CREATE statement
• Create a package specification. Place the name of each procedure in the new specification.
• Create a package specification and body with the source code of each procedure. Keep the
stand-alone procedures for the specification to reference.
• Create a package specification and body with the source code of each procedure. Drop the
old stand-alone procedures. (Answer)
36. The ADD_PLAYER procedure calls the UPD_PLAYER_STAT procedure. Both procedures
areINVALID.
Which command can you issue to recompile both procedures?
SCOTT needs the privilege to invoke this procedure. Which set of privileges must you
issue?
Which two statements will successfully invoke this procedure from SQL* Plus? (Choose
two.)
• EXECUTE UPD_BAT_STAT
• EXECUTE UPD_BAT_STAT(31)
• EXECUTE UPD_BAT_STAT(31,'FOUR','TWO')
- 71 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
39. The ADD_PLAYER procedure must calculate the amount of social security tax that the team needs
to pay. This algorithm is already written in a C program. You decide to call this program from the
ADD_PLAYER procedure.
Which Oracle Procedure Builder built-in package must you use to accomplish this task?
• ORA_PROF
• ORA_FFI (Answer)
• TOOL_ENV
• STPROC
Why?
• This is a statement level trigger and therefore cannot reference :new. (Answer)
• This is a row level trigger and therefore cannot reference :new.
• This is a statement level trigger and therefore cannot perform data manipulation statements.
• This is a row level trigger and therefore cannot perform data manipulation statements.
41. Using the debugger in Procedure Builder, which action must you take to temporarily halt the
execution of a procedure?
SQL*PLUS QUESTIONS
2. User can have 100 many numbers of variables per SQL command.
3. User can have 500 many number of lines (assuming 80 characters per line) per SQL command.
5. Start command is used to run the contents of the specified command file.
6. The intersect operator is used to get only those rows that returned by both the query.
7. The Grand command is used to set the System privileges, Object privileges.
8. The Savepoint command is used to identify the point in a transaction to which you can later
Rollback.
- 72 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
command is used.
10. The to-char function is used to convert the number datatype to a value of varchar2 datatype.
11. The Truncate command is used to remove all rows in a Table or Cluster instantly. Note : We can
not truncate rows from a table, which is part of a cluster.
We cannot truncate rows from a table, which has a referenced integrity constraint.
12. The Cluster is a schema object that contains one or more tables that have one or more columns
in common.
13. The Create Role command is used to set a set of privileges that can be granted to users or to
other roles.
* To collect statistics about the object used by the optimizer and store them in the data
dictionary. * To delete statistics about the object from the data dictionary.
* To validate the structure of the object.
* To identify migrated and chained rows of the table or cluster.
a] 255b] 21 c]
16
d] None of the above
Ans: 16
a] 255b] 254
c] 030 d] None of
the above Ans: 254
3. The maximum number of components in the Decode expression, including searches, results and
default is
a] No
limitationb] 255
Ans: 255
4. ___ Is an alternative name for a table, view, sequence, procedure, stored function,
package,snapshot or another synonym.
a] Synonymb]
Data block c] View
d] None of the
above
- 73 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
Ans: Synonym
5. The _________ operator is used in character string comparisons with pattern matching
a] Between..
Andb] Equal
operator c] Set
operator d] Like
Ans: Like
6. _________ returns only one copy of each set of duplicate rows selected.
a] Uniqueb]
Distinct c] Group
By d] None of the
above
a] Lock
tableb] For update
of c] Object
privileges d] Row
share
8. _____ Clause restricts the groups of rows returned to those groups for the specified condition id
True
a] Where
clauseb] Having
Clause c] Distinct
d] Exists
Ans: Having
10. The ________ function is used to return the number of bytes in the internal representation
ofexpression
a] Lengthb]
Vsize c] LengthLB
d] None of the
above
Ans: Vsize
- 74 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
Questions Answers
What is a Database ?
A Database can be one of the two definitions:
• A set of dictionary tables and user tables that are treated as a unit.
• One or more operating system files in which ORACLE stores the tables, views,
and other objects, also, the set of database objects used by a given application.
Note:-
A DBMS must be able to reliably manage a large amount of data in a
multi-user environment so that many users can concurrently access the same
data.
A DBMS must also be secure from unauthorized access and provides efficient
solutions for failure recovery.
What is an RDBMS ?
A relational database Management System (RDBMS) is a computer program for
general purpose data storage and retrieval that organizes data into tables consisting
of one or more units of information (rows), each containing the same set of data
items (columns). ORACLE is a relational database management system.
What is SQL ?
• S.Q.L - Structured Query Language. SQL is the ANSI industry standard
language, used to manipulate information in a relational database and used in
ORACLE and IBM DB2 relational database management systems. SQL is
formally pronounced “sequel”, although common usage also pronounces it
“SQL”
• SQL is a set of commands that all programmers must use to access data within
the tables of Database.
- 75 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
2. It is a non-procedural language. It
a] Processes set of records rather than just one at a
time and b] Provides automatic navigation to the
data.
What is SQL*PLUS ?
SQL*PLUS is the ORACLE database language which includes ANSI standard SQL
commands plus additional commands for accessing data in ORACLE database.
What is PL/SQL ?
It is a Procedural Language extension of SQL. It can contain any no of SQL
statements integrated with flow of control statements. Thus it combine the Data
Manipulating power of SQL with data processing power of Procedural language.
- 76 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
What is a Commit ?
• COMMIT commits any changes made to the database since the last COMMIT
was executed implicitly or explicitly. WORK is optional and has no effect on
usage.
What is a Rollback ?
• A ROLLBACK discards part or all of the work you have done in the current
transaction, since the last COMMIT or SAVEPOINT.
What is locking ?
To lock is to temporarily restrict other user’s access to data. The restriction is placed
on such data is called “a lock”. The modes are SHARE, SHARE
UPDATE,EXCLUSIVE,ROW SHARE AND ROW EXCLUSIVE. Not all locks can be
acquired in all modes.
EXCLUSIVE locks permit users to query the locked table but not to do anything else.
No other user may lock the table.
SHARED locks permit concurrent queries but no updates to the locked table.
With a ROW SHARE or SHARE UPDATE lock, no users can lock the whole table
for exclusive access, allowing concurrent access for all users to the table. The two
types of locks are synonymous, and SHARE UPDATE exists for compatibility with
previous versions of ORACLE.
ROW EXCLUSIVE locks are similar to ROW SHARE but they prohibit shared
locking, so only one user may access the table at the same time.
What is a Savepoint ?
The Savepoint is used to identify the point in a transaction to which you can later
Rollback.
- 77 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
What is REFERENTIAL
INTEGRITY ? REFERENTIAL INTEGRITY is the property that guarantees that values from one
column depend on values from another column. This property is enforced through
integrity constraints.
What is a SEQUENCE ?
A SEQUENCE is a database object used to generate UNIQUE INTEGERS for use
as PRIMARY KEYS.
- 78 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
What is a VIEW ?
A View is a database object that is a logical representation of a table. It is derived
from a table but has no storage space of its own and often may be used in the same
manner as a table.
What is a SYNONYM ?
A SYNONYM is a name assigned to a table or view that may thereafter be used to
refer it. If you access to another user’s table, you may create a synonym for it and
refer to it by the synonym alone, without entering the user’s name as a qualifier.
What is a ROWID ?
ROWID is the logical address of a row, and it is unique within the database. The
ROWID is broken into three sections: left, middle,, and right (corresponding to
00001F20,000C, AND 0001, just shown). The numbering is in hexadecimal notation.
The left section is the block in the file, the middle is the row sequence number within
the block(numbering starts with 0, not 1), and the right is the file number within the
database. Note that the file numbers are unique within the whole database. The
tablespace they are in is not relevant to the ROWID.
What is INDEX ?
INDEX is a general term for an ORACLE / SQL feature used primarily to speed
execution an impose UNIQUENESS upon certain data. INDEX provides a faster
access method to one table’s data than doing a full table scan. There are several
types of Indexes :
UNIQUE INDEX, COMPRESSED INDEX, CONCATENATED INDEX. An Index has
an entry for each value found in the table’s Indexed field(s) ( except those with a
NULL value ) and pointer(s) to the rows having that value.
What is a COMPRESSED
INDEX ? A COMPRESSED INDEX is an index for which only enough index information is
stored to identify unique entries; information that an index stores with the previous
or following key is “compressed” (truncated) and not stored to reduce the storage
overhead required by an index.
What is CONCATENATED
INDEX or KEY? A CONCATENATED INDEX is one that is created on more than one column of a
table. It can be used to guarantee that those columns are unique for every row in
the table and to speed access to rows via those columns
- 79 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
What is NULL ?
What is EXPRESSION ?
An expression is any form of a column. This could be a literal, a variable, a
mathematical computation, a function, or virtually any combination of functions and
columns whose final result is a single value, such as a string, a number, or a value.
What is a CONDITION ?
A Condition is an expression whose value evaluates to either TRUE or FALSE, such
as AGE > 16.
What is a PROFILE ?
A PROFILE is a collection of settings on ORACLE7 that limit database resources.
- 80 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
A ROLE is a set of privileges that an ORACLE7 user can grant to another user or to
a role. ORACLE version 6 privileges DBA, CONNECT, AND RESOURCE have
become system-supplied roles in ORACLE7, and there are also two new roles for
importing and exporting a database. ORACLE has five system-supplied roles :
CONNECT,RESOUCE,DBA,EXP_FULL_DATABASE, IMP_FULL_DATABASE.
What is a SEGMENT ?
A SEGMENT is another way to classify the space allocated to a table, index, or
cluster. A table has one segment that consists of all of its extents. Every index has
one segment similarly defined. A cluster has atleast two segments, one for its data
and one for its cluster key index.
PCTFREE parameters ? PCTFREE is a portion of the data block that is not filled by rows as they are inserted
into a table. but is reserved for future updates made to the rows in that block.
PCTUSED is the percentage of space in a data block, which ORACLE attempts to
fill before it allocates another block.
CLIENT
A Client or front-end database application acts as an interface between the user and
the Database. It also checks for validation against the data entered by the user.
CLIENT is a general term for a user , software application, or computer that requires
the services, data, or processing of another application or computer.
SERVER
A Database server or Back End is used to manage the Database tables optimally
among multiple clients who concurrently request the server for the same data. It also
enforces data integrity across all client applications and controls database access
and other security requirements.
SERVER system is the configuration of the ORACLE when a remote user accesses
ORACLE via SQL*NET.
What is a SESSION ?
A SESSION is a sequence of events that happens between the time a user connects
to SQL and the time he or she disconnects.
What is an INSTANCE ?
An INSTANCE is everything required for ORACLE to run: background processes
(programs), memory, and so on. An INSTANCE is the means of accessing a
database.
- 81 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
What is a
BACKROUND A BACKROUND process is one of the processes used by an instance of
PROCESS ? multipleprocess ORACLE to perform and coordinate tasks on behalf of concurrent
users of the database. The base process are named ARCH (achiever),DBWR
(database writer), LGWR (log writer), PMON (process monitor), and SMON (system
monitor), and exists as long as an instance does.
A Block is a logical container for items. It is also a separate object, with its own set
of properties.
The properties of the block determine how end users interact with the interface items
it contains.
What is READ
CONSISTENCY ? READ CONSISTENCY is a state that guarantees that all data encountered by a
statement / transaction is a consistent set throughout the duration of the statement /
transaction.
What is SGA ?
SGA is a shared storage area in main or virtual memory (depending on your
operating system) that is the center of ORACLE activity while the database is
running. The size of the SGA ( and performance of the system ) depends on the
values of the variable init.ora parameters. The SGA provides communication
between the user and the background processes.
What is a Datadictionary in
ORACLE ? The DATA DICTIONARY is a comprehensive set of tables and views owned by the
DBA users SYS and SYSTEM, which activates when ORACLE is initially installed,
and is a central source of information for the ORACLE RDBMS itself and for all
users of ORACLE. The tables are automatically maintained by ORACLE, and holds
a set of views and tables containing information about the database objects, users,
privileges, events, and use.
What is Sqldba ?
SQL * DBA is an ORACLE utility used by DBAs while performing database
maintenance and monitoring.
- 82 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
What is
Startup and STARTUP is the process of starting an instance, presumably with the intent of
Shutdown ? mounting and opening a database in order to make a database system available for
use.
- 83 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
• Post-Change triggers.
• Pre- and Post- Field, Pre- and Post- Record, Pre- and Post-Block, Pre- and
Post-Form triggers.
• Pre- and Post-Insert, Pre- and Post-Update, Pre- and Post-Delete, Pre- and
Post-Commit triggers.
- 84 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
What is a Schema ?
A SCHEMA is a collection of objects.
SCHEMA objects are logical structures that directly refer to the database’s data.
SCHEMA objects include structures such as tables, views, synonyms,
sequences, indexes, clusters, and stored procedures and data links.
Operations : Operations are clearly defined actions that allow the user to manipulate
the data and structure of the database. The operation on a database must adhere to
a pre-defined set of integrity rules.
Integrity rules : Integrity rules are the laws that govern which operations are allowed
on the data and structure of a database. Integrity rules protect the data and the
structures of a database.
- 85 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
- 86 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
What is Application
Partitioning ? PL/SQL is the language used for both client-side Oracle forms applications and
server-side database triggers and stored procedures and there is a PL/SQL engine
in both Oracle forms Runform and the Oracle7 Server.
This means that you can take advantage of application partitioning to execute
application code on either the client or the server.
Application partitioning allows you to optimize performance and resource usage by
storing and executing procedures either locally or at the server, which makes the
most sense for your particular application and configuration.
- 87 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
structure of the Oracle The physical structure of an ORACLE database includes datafiles, redolog files
database ? and control files.
1. Datafiles:
Note: Modified or new data is not necessarily written to a data file immediately. To
reduce the amount of disk output and increase performance, data is pooled in
memory and written to the appropriate data file all at once, as determined by the
DBWR background process of ORACLE.
Every ORACLE database has a set of two or more Redo log files. The set of redo
log files for a database is collectively known as the Database’s redolog.
The primary function of a redo log is to record changes made to data. Should
a failure prevent modified data to be written to the data files , the changes can be
obtained from the redo log and the work is never lost. Thus redo log files are critical
in protecting a database against failures.
The process of applying the redo log during a recovery operation is called Rolling
forward. To protect against failures of the redo log itself, ORACLE allows a mirrored
redo log so that two or more copies of the redo log can be maintained on different
disks.
3. Control files:
Every ORACLE database has a Control file. A control file records the physical
structure of the database. For example, it contains the following information :
Database name, names and locations of a database’s data files and redolog
files and the time stamp of database creation.
Every time an instance of an ORACLE is started, its control file is used to identify
database and the redo log files that must be opened for database operation to
proceed. If the physical makeup of the database is altered ( for example, if a new
data file or redo log file is created ), the database’s control file is automatically
modified by the ORACLE to reflect the change.
Note:
A database’s control file is also used if database recovery is necessary.
- 88 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
The data in the SGA is shared among the users currently connected to the database.
For optimal performance , the entire SGA should be as large as possible to store as
much data as possible in memory and minimize disks I/O.
The information stored within the SGA is divided into several types of memory
structures, including the database buffers, redo log buffers and the shared pool.
These area have fixed size and are created during instance startup.
Database buffers of the SGA store the most recently used blocks of database
data; the set of database buffers in an instance is the database buffer cache. These
buffers can contain modified data that has not yet been written to disk. Because
the most recently used data is kept in memory, less disk I/O is necessary and
performance is increased.
The redo log buffer of the SGA stores redo entries - a log of changes made to
the database. The redo entries stored in the redo log buffers are written to an online
redo log file, which is used if database recovery is necessary. Its size is static.
3. Shared Pool:
The shared pool is a portion of the SGA that contains shared SQL constructs
such as shared SQL areas. A shared SQL area is required to process every unique
SQL statement submitted in a database.
A shared SQL area contains information such as the parse tree and execution
plan for the corresponding statement. A single shared SQL area is used by
multiple application that issue the same statement leaving more control over cursors.
4. Cursors:
- 89 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
The 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. The
information in a PGA depends on the configuration of Oracle.
What is a Process ?
A Process is a “thread of control” or a mechanism in a operating system that
can execute a series of steps.
Some operating system use the term job as task.
Explain the types of
Processes used by Oracle ? An Oracle database system has two types of processes :
1) User Process.
2) Oracle Process.
User Process :
Oracle Processes:
The different types of Oracle processes and their specific functions are as follows :
The background processes asynchronously perform I/O and monitor other Oracle
processes to provide increased parallelism for better performance and reliability.
- 90 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
What is a Checkpoint ?
At specific times, all modified database buffers in the SGA are written to the
data files by DBWR; this event is called a Checkpoint.
The checkpoint process is responsible for signaling DBWR at checkpoints and
updating all the data files and control files of the database to indicate the most recent
checkpoint. CKPT is optional; if CKPT is not present, LGWR assumes the
responsibilities of CKPT.
These transactions are eventually recovered by SMON when the tablespace or file
is brought back. SMON also coalesces free extents within the database, to make
free space contiguous and easier to allocate.
PMON is responsible for cleaning up the cache and freeing resources that the
process was using. PMON also checks on the Dispatcher and server processes and
restarts them if they have failed.
What is an Achiever ?
The Achiever copies the on-line redo log files to archival storage when they
are full.
ARCH is active only when a database’s redo log is used in ARCHIEVELOG mode.
What is a Recoverer?
The recoverer is used to resolve distributed transactions that are pending due
to a NETWORK or system failure in a distributed database.
- 91 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
What is a Dispatcher ?
Dispatchers are optional background processes, present only when a
Multithreaded server configuration is used.
Atleast one dispatcher process is created for every communication protocol in use
(D000,...Dnnnn).
Each dispatcher process is responsible for routing requests from connected user
processes to available shared server processes and returning the response back to
the appropriate user processes.
A View is a database object that is a logical representation of a table. It is derived from a table but
has no storage space of its own and often may be used in the same manner as a table.
Difference: A View can be based on MULTIPLE Tables whereas a SYNONYM is based on a single
object only.
- 92 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
DBMS_OUTPUT_PACKAGE allows you to use 3 debugging functions within your package. You must
use “SET SERVER OUTPUT ON” before executing the procedure object you will be debugging.
PUT - Puts multiple O/P’s on same line.
PUT_LINE Puts each O/P on a separate line.
NEW_LINE Used with PUT; Signals the end of current O/P line.
DATABASE triggers are executed automatically in response to specific events. But the DATABASE
procedures are to be explicitly invoked to execute the code contained in them.
8. What is a CURSOR?
A work area in memory where ORACLE stores the current SQL statement. For a query , the area in
memory also includes column headings and one row retrieved by the SELECT statement.
11. How to write a SQL statement that should have a best RESPONSE TIME ?
Use the _____ in the optimizer hint inorder to obtain a best response time. Use “FIRST_ROW” Cost
based Optimizer Hint.
Specifies a hint string that Oracle Forms passes on to the RDBMS optimizer when constructing
queries. Using the optimizer can improve the performance of database transactions.
%TYPE provides the datatype of a variable, constant or column. It is useful when you declare
a variable that refers to a database column in the table.
%ROWTYPE attribute is based on a record variable that has the same structure as a row in a
table or view or as a row fetched from a cursor.
[ If the structure is what we define in ‘C’ then we can create objects of type structure using RECORD
variable available in PL/SQL. ]
Yes, Using the PL/SQL tables. PL/SQL tables are temporary array like objects used in a PL/SQL block.
PL/SQL tables can have one column and a primary key. The column data type can belong to any
scalar data type, but the primary key must only belong to the type binary integer.
Size - UNLIMITED.
- 93 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
Yes. E.g.: INSERT INTO EMP(COMM ) VALUES ( SAL*0.05 ) WHERE DEPTNO = 20;
TRUNCATE table is a DDL command used to remove all the rows from the specified table or cluster
instantly.
E.g.: TRUNCATE TABLE table_name; Advantage
over DELETING:
ROWID is the logical address of a row, and it is unique within the database. The ROWID is broken into
three sections: left, middle and right (corresponding to 00001F20,000C AND 0001 just shown). The
numbering is in hexadecimal notation. The left section is the block in the file, the middle is the row
sequence number within the block(numbering starts with 0, not 1), and the right is the file number within
the database. Note that the file numbers are unique within the whole database. The tablespace they
are in is not relevant to the ROWID. ROWID can be selected, or used in a where clause, but cannot
be changed by an insert, update, or delete. However it can change if the table it is in is exported and
imported.
TRANSLATE looks at each character in string, and then checks if to see if that character is there, if
it is, TRANSLATE notes the position in if where it found the character, and then looks the same position
in then. Whatever character it finds there it substitutes the character in string
The text of an Oracle Forms trigger is an anonymous PL/SQL block. It consists of three sections:
- 94 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
Syntax:
DECLARE --- declarative statements (optional)
BEGIN --- executable statements (required)
EXCEPTION --- exception handlers (optional)
END;
• CURSOR_ALREADY_OPEN.
• NO_DATA_FOUND.
• INVALID_NUMBER.
In the DECLARATION part define a variable of type exception. In the execution part call the exception
using RAISE exception_name. In the exception part handle the exception using WHEN
exception_name.
It is a directive to the COMPILER, rather than a piece of executable code. Even though it appears in
the program, it is not executable. It gives instructions to the compiler.
CHAR (size) - It is a fixed length character data, size characters long. It is padded with BLANKS ON
RIGHT to the full length of size. DEFAULT - 1 bytes, MAX - 255 bytes.
VARCHAR2 (size) - It is a variable length char string having a maximum of size bytes.
MAX -2000 bytes.
The CURSOR FOR LOOP lets you implicitly OPEN a cursor, FETCH each row returned by the query
associated with the cursor and CLOSE the cursor when all rows have been processed.
NOT NULL, UNIQUE KEY, PRIMARY KEY, FOREIGN KEY and CHECK constraints.
PL/SQL is the language used for both client-side Oracle forms applications and server-side database
triggers and stored procedures and there is a PL/SQL engine in both Oracle forms Runform and the
Oracle7 Server. This means that you can take advantage of application partitioning to execute
application code on either the client or the server.
Application partitioning allows you to optimize performance and resource usage by storing and
executing procedures either locally or at the server, which makes the most sense for your particular
application and configuration.
Unlike procedures, FUNCTIONS returns a VALUE to the caller. This value is returned through the
RETURN command/keyword within the function.
Functions don’t use the IN, OUT | IN OUT arguments, which are available for PROCEDURES.
- 95 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
Use SHOW_ERRORS. this will display all the errors associated with the most recently created
procedural object. This command will check the VIEW_ERRORS data dictionary for the ERRORS
associated with the most recent compilation attempt for that procedural object. SHOW_ERRORS will
display the LINE and COLUMN NO. for each error, as well as the text of the error message.
TRAPPING ERORS:
DBMS_OUTPUT package allows you to use 3 debugging functions within your package. You must set
‘SERVER OUTPUT ON’ before executing the procedure object you will be debugging.
This happens with TRIGGERS. It occurs when a trigger is trying to update a row, which is being used
currently. The usual fix involves either use of VIEWS or TEMPORARY TABLES so the database is
selecting from one while updating the other.
33. How to know what are all the CONSTRAINTS present on a table?
• Using the USER_CONSTRAINTS view we can get the type of constraints declared on a table.
• Use ALL_CONSTRAINTS to list the constraints on all of the tables that the user has access.
• DBA_CONSTRAINTS lists all of the constraints in the database.
34. What is MASTER - DETAIL relationship? Can we write a master-detail relationship programswithout
using the settings at design time. If so how?
It is an association between TWO BASE TABLE blocks - a MASTER block and a DETAIL block. The
relationship between the blocks reflects a PRIMARY KEY - FOREIGN KEY relationship between the
tables on which the blocks are based.
35. What does BUFFER RECORDS option and ARRAY SIZE parameter?
- 96 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
ARRAY SIZE - Specifies the minimum no. of records that get fetched each time forms goes to the
database.
BUFFER RECORDS - Specifies the minimum no of records that should be placed in memory when
records are fetched from the database. Even if you specify a low value of 3, the minimum per form is
slightly over 300.
36. During VALIDATION WHAT CHECKS are done with respective to FIELDS / ITEMS ?
• Data Type
• Maximum Length
• Fixed Length
• Required
• Range Low value / Range High value.
37. What is the difference between PRIMARY KEY and UNIQUE KEY?
• The UNIQUE KEY column restricts entry of duplicate values but entry of NULL value is allowed.
• In case of PRIMARY KEY columns entry of duplicate as well as NULL value is restricted.
39. What are RESTRICTED PACKAGED PROCEDURES? Why are they restricted from using?
Any PACKAGED PROCEDURE that affects the basic functions of SQL*FORMS is a RESRICTED
PACKAGED PROCEDURE. You should use restricted packaged procedure only in KEY-
TRIGGERS, USER-NAMED TRIGGERS that are invoked by KEY-TRIGGERS, and
ON_NEW_FIELD_INSTANCE triggers. You should not use restricted packaged procedures in any of
the following types of triggers.
40. What is the DIFFERENCE between EXPLICIT CURSOR & IMPLICIT CURSOR?
Issuing a SELECT statement automatically opens IMPLICIT CURSORS, but the EXPLICIT cursors
are to be opened using OPEN, fetching is done using FETCH and closing using CLOSE.
ROWID is the logical address of the row, whereas ROWNUM returns the sequence no. in which the
row was retrieved when first fetched from a table.
- 97 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
Using SQL TRACE. It is a utility that can monitor and report on database performance when one or
more queries are run against the database. It is used to gather statistics when running the query (i.e.)
reports on CPU time spent on the query, the total no. of rows processed and statistics related to parsing
and cache performance.
It is a utility that shows how Oracle will access data for a given query. Use EXPLAIN PLAN to determine
the effective way to write queries and decide whether to INDEX CERTAIN COLUMNS or TO USE
CLUSTERS. It shows:
SQL PROF
There are 5 types of locks. To lock is to temporarily restrict other user’s access to data. The restriction
is placed on such data is called “a lock”. The modes are SHARE, SHARE UPDATE,EXCLUSIVE,ROW
SHARE AND ROW EXCLUSIVE. Not all locks can be acquired in all modes.
A SHARE lock is one that permits other users to query data, but not to change it.
An EXCLUSIVE LOCK is one that permits other users to query data, but not to change it. It differs from
the SHARE lock because it does not permit another user to place any type of lock on the same data;
several users may place SHARE locks on the same data at the same time.
With a ROW SHARE or SHARE UPDATE lock, no users can lock the whole table for exclusive access,
allowing concurrent access for all users to the table. The two types of locks are synonymous, and
SHARE UPDATE exists for compatibility with previous versions of ORACLE. ROW EXCLUSIVE locks
are similar to ROW SHARE but they prohibit shared locking, so only one user user may access the
table at the same time.
- 98 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
A DEAD lock is a rare situation in which two or more user processes of a database cannot complete
their transactions. This occurs because each process is holding a resource that the other process
requires (such as a row in a table) in order to complete. Although these situations occur rarely,
ORACLE detects and resolves deadlocks by rolling back the work of one of the processes.
53. How do you analyze which resources has locked for what?
It is a utility in SQL*FORMS for making use of HOST 3 GL languages for the purpose like ONLINE
PRINTING etc.
At FORMS STARTUP Oracle navigates to the first navigable item in the first navigable block. This
trigger fires after successful completion of any Navigational trigger (i.e.) It will not fire if the control
returns to the CALLING FORM from the CALLED FORM.
INDEX is a general term for an ORACLE / SQL feature used primarily to speed execution an impose
UNIQUENESS upon certain data. INDEX provides a faster access method to one table’s data than
doing a full table scan. There are several types of Indexes :
UNIQUE INDEX, COMPRESSED INDEX and CONCATENATED INDEX. An Index has an entry for
each value found in the table’s Indexed field(s) ( except those with a NULL value ) and pointer(s) to
the rows having that value.
An UNIQUE INDEX is an index that imposes uniqueness on each value in indexes. The index may be
one column or concatenated columns.
59. What is a COMPRESSED INDEX?
It is an index, for which only enough index information is stored to identify unique entries; information
that an index stores with the previous or following key is “compressed” (truncated) and not stored to
reduce the storage overhead required by an index.
It is one that is created on more than one column of a table. It can be used to guarantee that those
columns are unique for every row in the table and to speed access to rows via those columns
• The UNION operator returns ALL DISTINCT ROWS selected by either query.
• The UNION ALL operator returns ALL ROWS selected by either query including duplicates.
• The INTERSECTION operator returns ONLY ROWS that are COMMON to both the queries.
• The MINUS operator returns ALL DISTINCT ROWS selected only by the first query and not by
the second.
- 99 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
GROUP BY statement causes a SELECT statement to produce ONE SUMMARY ROW for all selected
rows that have identical values in one or more specified column or expressions. Each expression in
the SELECT clause must be one of the following :
1] A CONSANT
2] A Function without parameters
3] A GROUP function like SUM , AVG.
4] Matched IDENTICALLY to a expression in the ‘GROUP BY’ clause.
UNION returns all distinct rows selected by either of the query, whereas UNION ALL returns ALL
ROWS selected by either query including duplicates.
64. Give one example where you will use DATABASE TRIGGERS?
65. Do you have any idea about ROW-CHAINING? How will you resolve the issue if there is
rowchaining in a table?
When a row NO LONGER FITS WITHIN THE DATABLOCK, it is stored in more than one database
block, and that therefore has several row pieces.
Resolving: Use ANALYZE to identify chained rows and also provides statistics on the chained rows.
OPTIMIZER is a utility used to determine how to access data requested in the query by the USER or
APPLICATION PROGRAM. The output of an optimizer is EXECUTION PLAN.
67. How the Oracle in case of a query does OPTIMIZATION?
RULE based optimization USES A FIXED SET OF RULES to determine how to access the data.
COST based optimization USES STASTISTICS STORED IN THE DATA DICTIONARY WITH
CERTAIN RULES to determine how to access the data.
With the help of ALTER SESSION SET OPTIMIZER_GOAL = ALL_ROWS / FIRST_ROW, We can
alter the modes of cost based optimizer.
69. The KEYWORD comes into the mind immediately when we talk about security in ORACLE 7.0?
- 100 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
GRANT.
Syntax: GRANT privileges (SELECT, INSERT, UPDATE, DELETE, ALTER and INDEX) ON object
TO user WITH
GRANT OPTION;
70. What KEWORD is used to withdraw the PRIVILEGE you have granted to other user?
REVOKE
A SINGLE MACHINE can run more than one instance at a time. Each instance is connected to its
own database.
Different instances on different machines can communicate with each other using DATABASE LINKS
and the DISTRIBUTED option. Oracle supports full two-phase commits which means that inserts,
updates and deletes can occur on REMOTE database via a network running SQL*Net.
The Oracle parallel server allows multiple instances to share a single database on a shared disk
system. The instance can run on a parallel computer or on different computers in a cluster.
3. Procedural Capabilities.
3. It provides command for a variety of tasks including:
A. Querying Data.
B. Creating, Updating and Replacing objects
C. Inserting, Updating and Deleting.
- 101 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
76. How to fetch description of a code in the base table block where code is a base table field and
thedescription is a non-base table field?
Use SELECT with INTO clause to fetch the description value into the NON-BASE table field.
An OUTER JOIN returns all the rows returned by simple join as well as those rows from one table that
do not match any row from the other table. The symbol (+) represents the outer join.
EQUI JOIN returns rows from both the tables provided they both have the same column_name in the
where clause. The symbol (=) represents the EQUI JOIN. For OUTER JOIN see previous answer.
NORMALIZATION is the process of putting things right, making them normal. It is a part of analysis
necessary to understand a business, and build a useful application.
• Ensure that all the ENTITIES are uniquely identified by a combination of attributes.
• Remove repeated attributes or group of attributes, to place the entities in the first normal form.
• Remove attributes that are dependent on only part of the identifier.
• Remove attributes that are dependent on attributes, which are not part of the identifier.
REFERENTIAL INTEGRITY is the property that guarantees that values from one column depend on
values from another column. This property is enforced through integrity constraints. Referential
integrity is the automatic enforcement of referential constraints that exists between a reference table
and a referencing table. When referential integrity is enforced , the value of a foreign key exists as a
primary key value in the reference table.
SELECT DEPT.DEPTNO, DNAME, JOB, ENAME FROM DEPT, EMP WHERE DEPT.DEPTNO =
EMP.DEPTNO (+) AND DEPTNO IN (30,40) ORDER BY DEPT.DEPTNO;
82. Explain with example how to use a select statement with GROUP BY HAVING clause? (or)
Where and when is the HAVING clause used and what does it have?
- 102 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
The HAVING clause is coded after the GROUP BY clause in the query that is summarizing results by
one or more grouping columns. The HAVING clause behaves the same as the WHERE clause except
that it is used to specify the conditions each returned group must satisfy. If one row in the group fails
the condition of the HAVNG clause, the entire group is not returned as part of the result.
Ex: SELECT MAX (CUSTID), REPID FROM CUSTOMER GROUP BY REPID HAVING COUNT (*) >
2;
ENFORCE KEY field characteristic indicates the source of the value that SQL*FORMS uses to
populate the field
ERASE removes an indicated global variable & releases the memory associated with it
A referential integrity constraint designates a column or combination of columns 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 called the parent table.
A package is an encapsulated collection of related program objects stored together the database.
Program objects in the sense - procedures, functions, variables, constants, cursors & exceptions.
- 103 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
In a package
• Public objects (declared in the package), can be referenced outside the package as well as by
other objects in the package.
• Private objects (defined in the package body), can only be referenced by other objects in the
package. They cannot be referenced outside the package.
• Private procedure or other objects - defined only in package body.
• Public procedure or other objects - declared only in package.
Once any objects first called, package get initialized (may be).
93. How will you find out number of rows inserted after an INSERT statement?
94. What do you mean by cluster and what is the advantage of using the cluster?
A cluster is a schema object that contains one or more tables that all have one or more columns in
common.
Advantage: Rows of one or more tables that share the same value in these common columns are
physically stored together within the database. Clustering provides more control over the physical
storage of rows within the database. Clustering can reduce both the time it takes to access clustered
tables and the space needed to store the table.
An index is a database object that contains an entry for each value that appears in the indexed
column(s) of the table or clusters and provides direct, fast access to rows. An index can contain a
maximum of 16 columns. Unlimited indexes can be created for a table provided that the combination of
columns differs for each index. You can create more than one index using the same columns provided
that you specify distinctly different combinations of the columns. Nulls are not indexed.
96. How will you force the query to look at the index while searching for a record?
97. How will you avoid using indexes while searching for a record?
In where clause, manipulating the data type of the column will avoid using index.
The above query does not use an index created on the DEPTNO column, b'cos the data type of
DEPTNO is NUMBER.
- 104 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
Also, if we change the combination of multiple columns indexed in the where clause.
The above query does not use an multiple column index created on the SAL, DEPTNO column.
above query does not use an index created on the DEPTNO column.
Foreign key, which references the primary key of the same table, is called self-referential integrity.
Row, Table & Database level locks are admitted in Oracle. Page level lock is not supported by Oracle.
This command insert a row describing each step of the execution plans of a particular table into a
specified another table.
104. What is the use of PCTFREE and PCTUSED and they can be used effectively?
• PCTUSED - specifies the limit that Oracle7 uses to determine when additional rows can be added
to a cluster's data block. The value of this parameter is expressed as a whole number and
interpreted as a percentage.
• PCTFREE - specifies the space reserved in each of the cluster's data blocks for future expansion.
The value of the parameter is expressed as a whole number and interpreted as a percentage.
ROWID is a unique identification for each row in a table. It is a pseudo column. Other pseudo columns
are ROWNUM, LEVEL, CURVAL & NEXTVAL. ROWID column is made of BLOCK.ROW.FILE
Where,
BLOCK: A hexadecimal string identifying the data blocks of the data file containing the row.
The length of this
String may vary depending on your operating system.
ROW : A four-digit hexadecimal string identifying the row in the data block.
The first row in the block has the number 0. File is a hexadecimal string identifying the database file
containing the row. The first data file has the number 1. The length of this string may vary depending
on your operating system.
Example:
Consider this ROWID value:
- 105 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
0000000F.0000.0002
The row corresponding to this ROWID is the first row (0000) in the fifteenth data block (0000000F) of
the second data file (0002).
106. What are the logical storage units of oracle database? How are they mapped with
physical storage?
Logical storage units: Tables, Views, Indexes, Tablespaces, Segments, Extents, Synonyms, etc.
108. After deleting a row from a table, will the rowid used by the deleted row be reused?
No.
112. How the uncommitted transactions are recovered after the failure of two-phase commit?
113. What is the roll of redo log file and rollback segment?
114. How will you use START WITH and CONNECT BY clauses with a select statement?
To define a hierarchical relationship in a query, you must use the START WITH and CONNECT BY
clauses.
115. Is it possible to use a stored function in a select statement? If yes, what needs to be
taken care in the stored function?
12 TRIGGERS
When you query the same table in which the trigger has been defined, it is trigger mutation.
PL/SQL tables are objects of type TABLE, which are modeled as (but not the same as) database
tables. PL/SQL tables use a primary key to give you array-like access to rows.
Yes.
121. How will you trap the user defined exception number in a PL/SQL block?
- 106 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
A pseudocolumn behaves like a table column, but is not actually stored in the table. You can select
from pseudocolumns, but you cannot insert, update, or delete their values.
124. What are the role of dispatcher and other background processes of oracle database?
126. How oracle maintains database recovery incase the case of instance failure?
SQL Commands
The tables in the following sections provide a functional summary of SQL commands and are divided
into these categories:
- 107 - https://www.linkedin.com/in/sushant-singh-chauhan-
COMPLEX QUERIES
Data Definition Language (DDL ) commands allow you to perform these tasks:
The CREATE, ALTER and DROP command require exclusive access to the object being acted upon.
For example, an ALTER TABLE command fails if another user has an open transaction on the specified
table.
The GRANT, REVOKE, ANALYZE, AUDIT, and COMMENT commands do not required exclusive
access to the object being acted upon. For example, you can analyze a table while other users are
updating the table.
Oracle7 implicitly commits the current transaction before and after every Data Definition Language
statement.
Many Data Definition Language statements may cause Oracle7 to recompile or reauthorize schema
objects. For information on how Oracle7 recompiles and reauthorize schema objects and the
circumstances under which a Data Definition Language statement would cause this, see the
"Dependencies Among Schema Objects" chapter of Oracle7 Server Concepts.
Data Definition Language commands are not directly supported by PL/SQL, but may be available using
packaged procedures supplied by Oracle corporation. For more information, see PL/SQL User's Guide
and Reference.
ALTER CLUSTER : To change the storage characteristics of a cluster and to allocate an extent for a
cluster.
Oracle7.To choose archive log / no archive log mode. To perform media recovery. To add/drop/clear
redo log file groups members. To rename a data file/redo log file member. To backup the current control
file. To backup SQL commands (that can be used to re-create the database) to the trace file. To create
ALTER FUNCTION : To recompile a stored function.
- 108 -
COMPLEX QUERIES
recovery purposes. To enable/disable autoextending the size of datafiles. To take a data file
online/offline. To enable/disable a thread of redo log file groups. To change the database's global
name. To change the MAC mode. To set the DBHIGH or DBLOW labels. resources used by a session.
ALTER USER : To change a user's password, default tablespace, temporary tablespace, tablespace
quotas, profile, or default roles.
ANALYZE : To collect performance statistics, validate structure, or identify chained rows for a table,
cluster, or index.
AUDIT operations on schema : To choose auditing for specified SQL commands or
objects.
- 109 -
COMPLEX QUERIES
CREATE TABLE constraints, and : To create a table, defining its columns, integrity
storage allocation.
- 110 -
COMPLEX QUERIES
DROP USER schema : To remove a user and the objects in the user's
from the database.
REVOKE : To revoke system privileges, roles, and object privileges from users and roles.
TRUNCATE : To remove all rows from a table or cluster and free the space that the rows used.
Data Manipulation Language (DML) commands query and manipulates data in schema objects.
These commands do not implicitly commit the current transaction.
Transaction Control commands manage changes made by Data Manipulation Language commands.
COMMIT : To make permanent the changes made by statements issued and the
beginning of a transaction.
ROLLBACK : To undo all changes since the beginning of a transaction or since a savepoint.
:
- 111 -
COMPLEX QUERIES
Session Control commands dynamically manage the properties of a user session. These commands
do not implicitly commit the current transaction. PL/SQL does not support session control commands.
ALTER SESSION : To enable/disable the SQL trace facility. To enable/disable global name resolution.
To change the values of the session's NLS parameters. For Trusted Oracle7, to change the session
label. To change the default label format. In a parallel server, to indicate that the session must access
database files as if the session was connected to another instance. To close a database link. To send
advice to remote databases for forcing an indoubt distributed transaction. To permit or prohibit
procedures and stored procedures from issuing COMMIT and ROLLBACK statements. To change the
goal of the cost-based optimization approach.
The single System Control command dynamically manages the properties of an Oracle7 instance.
This command does not implicitly commit the current transaction.
Embedded SQL commands place Data Definition Language, Data Manipulation Language, and
- 112 -
COMPLEX QUERIES
DECLARE TABLE : To declare the structure of a table for semantic checking of embedded SQL
statements by the Oracle pre-compiler.
- 113 -
COMPLEX QUERIES
Editor
Host
Program --------------------------- With embedded SQL statements
- 114 -
COMPLEX QUERIES
Oracle
Precompiler
Source
Program ------------------------------ With all SQL statements replaced by library calls
Compiler
Object
Program
Executable
Program
- 115 -
COMPLEX QUERIES
Requirements
ANSI standard X3.135-1992 (known informally as SQL92) provides three
levels of compliance:
• Full SQL
• Intermediate SQL (a subset of Full SQL)
• Entry SQL (a subset of Intermediate SQL)
ANSI standard X3.168-1992 specifies the syntax and semantics for embedding
SQL statements in application programs written in a standard programming
- 116 -
COMPLEX QUERIES
Compliance
Under Oracle8, the Pro*C/C++ Precompiler complies 100% with current
ANSI/ISO standards.
The Pro*C/C++ Precompiler also complies 100% with the NIST standard. It
provides a FIPS Flagger and an option named FIPS, which enables the FIPS
Flagger. For more information, see “FIPS Flagger” on page 1-8.
Certification
NIST tested the Pro*C/C++ Precompiler for ANSI SQL92 compliance using the
SQL Test Suite, which consists of nearly 300 test programs. Specifically, the
programs tested for conformance to the C embedded SQL standard. The
result: the Oracle Pro*C/C++ Precompiler was certified 100% ANSI-compliant
for Entry SQL92.
- 117 -
COMPLEX QUERIES
Question: Does Pro*C/C++ generate calls to the Oracle Call Interface (OCI)?
Answer: No. Pro*C/C++ generates data structures, and calls to its runtime library:
SQLLIB (libsql.a in UNIX). SQLLIB, in turn, calls the UPI to communicate with the
database.
Question: Then why not just code using SQLLIB calls, and not use Pro*C/C++?
Answer: SQLLIB is not externally documented, is unsupported, and might change from
release to release. Also, Pro*C/C++ is an ANSI/ISO compliant product, that follows the
standard requirements for embedded SQL.
If you need to do low-level coding, use the OCI. It is supported, and Oracle is
committed to supporting it.
You can also mix OCI and Pro*C/C++. See “SQLLIB Extensions for OCI
Release 8 Interoperability” on page 4-50.
Question: Can I call a PL/SQL stored procedure from a Pro*C/C++ program?
Answer: Certainly. See Chapter 6, “Using Embedded PL/SQL”. There’s a demo
program starting on page 6-21.
Question: Can I write C++ code, and precompile it using Pro*C/C++?
Answer: Yes. Starting with Pro*C/C++ release 2.1, you can precompile C++
applications. See Chapter 7, “Using C++”.
Question: Can I use bind variables anyplace in a SQL statement? For example, I’d like to
be able to input the name of a table in my SQL statements at runtime. But when I use
host variables, I get precompiler errors.
Answer: In general, you can use host variables at any place in a SQL, or PL/SQL,
statement where expressions are allowed. See page 3-32. The following SQL
statement, where table_name is a host variable, is illegal:
EXEC SQL SELECT ename,sal INTO :name, :salary FROM :table_name;
To solve your problem, you need to use dynamic SQL. See Chapter 13, “Using
Dynamic SQL”. There is a demo program that you can adapt to do this starting
on page 13-9.
Question: I am confused by character handling in Pro*C/C++. It seems that there are
many options. Can you help?
Answer: There are many options, but we can simplify. First of all, if you need
compatibility with previous V1.x precompilers, and with both Oracle V6 and
Oracle7, the safest thing to do is use VARCHAR[n] host variables. See page 3-
43.
The default datatype for all other character variables in Pro*C/C++ is CHARZ; see
page 3-27. Briefly, this means that you must null-terminate the string on input, and
it is both blank-padded and null-terminated on output.
- 118 -
COMPLEX QUERIES
Question: Where can I find the on-line versions of the sample programs?
Answer: Each Oracle installation should have a demo directory. On UNIX systems, for
example, it is located in $ORACLE_HOME/proc/demo. If the directory is not there, or it
does not contain the sample programs, see your system or database administrator.
Question: How can I compile and link my application?
Answer: Compiling and linking are very platform specific. Your system-specific Oracle
documentation has instructions on how to link a Pro*C/C++ application. On UNIX
systems, there is a makefile called proc.mk in the demo directory. To link, say, the
demo program sample1.pc, you would enter the command line make -f proc.mk
sample1
If you need to use special precompiler options, you can run Pro*C/C++
separately, then do the make. Or, you can create your own custom makefile.
For example, if your program contains embedded PL/SQL code, you can enter
proc cv_demo userid=scott/tiger sqlcheck=semantics make -f proc.mk
cv_demo
On VMS systems, there is a script called LNPROC that you use to link your
Pro*C/C++ applications.
Question: I have been told that Pro*C/C++ now supports using structures as host
variables. How does this work with the array interface?
Answer: You can use arrays inside a single structure, or an array of structures with the
array interface. See page 3-35 and page 3-41.
Question: Is it possible to have recursive functions in Pro*C/C++, if I use embedded SQL
in the function?
Answer: Yes. With release 2.1 of Pro*C/C++, you can also use cursor variables in
recursive functions.
Question: Can I use any release of the Oracle Pro*C or Pro*C/C++ Precompiler with any
version of the Oracle Server?
Answer: No. You can use an older version of Pro*C or Pro*C/C++ with a newer version
of the server, but you cannot use a newer version of Pro*C/C++ with an older version of
the server.
For example, you can use release 2.2 of Pro*C/C++ with Oracle8, but you
cannot use Pro*C/C++ release8.0 with the Oracle7 server.
Question: When my application runs under Oracle8, I keep getting an ORA-1405 error
(fetched column value is null). It worked fine under Oracle V6. What is
happening?
Answer: You are selecting a null into a host variable that does not have an associated
indicator variable. This is not in compliance with the ANSI/ISO standards, and was
changed beginning with Oracle7.
- 119 -
COMPLEX QUERIES
If possible, rewrite your program using indicator variables, and use indicators
in future development. Indicator variables are described on page 3-33.
Alternatively, if precompiling with MODE=ORACLE and DBMS=V7 or V8,
specify UNSAFE_NULL=YES the command line (see “UNSAFE_NULL” on
page 9-36 for more information) to disable the ORA-01405 message, or
precompile with DBMS=V6.
Question: Are all SQLLIB functions private?
Answer: No. There are some SQLLIB functions that you can call to get information
about your program, or its data. The SQLLIB public functions are shown here:
SQLSQLDAAlloc() Used to allocate a SQL descriptor array
(SQLDA) for dynamic SQL Method 4.See
“How is the SQLDA Referenced?” on
page 14-3.
SQLCDAFromResultSetCursor() Used to convert a Pro*C/C++ cursor variable
to an OCI cursor data area. See “SQLLIB Public Functions -- New Names” on
page 4-34.
SQLSQLDAFree() Used to free a SQLDA allocated using
SQLSQLDAAlloc(). See “SQLLIB Public Functions --
New Names” on page 4-34 .
SQLCDAToResultSetCursor() Used to convert an OCI cursor data area to a
Pro*C/C++ cursor variable. See “SQLLIB
Public Functions -- New Names” on
page 4-34.
SQLErrorGetText() Returns a long error message. See “sqlerrm”
on page 11-20.
SQLStmtGetText) Used to return the text of the most recently
executed SQL statement. See “Obtaining the Text of SQL
Statements” on page 11-30.
In the preceding list, the functions are thread-safe SQLLIB public functions.
Use these functions in multi-threaded applications. The names of the functions
have been changed for release 8.0, but the old names are still supported in
Pro*C/C++. For more information about these thread-safe public functions
(including their old names), see the table “SQLLIB Public Functions -- New
Names” on page 4-34.
Question: How does Oracle8 support the new Object Types?
Answer: See the chapters Chapter 8, “Object Support in Pro*C/C++” and Chapter 16,
“Using the Object Type Translator” for how to use Object types in Pro*C/C++
applications.
SQLLDAGetNamed() Used to obtain a valid Logon Data Area for a
named connection, when OCI calls are used in a Pro*C/C++
program. See “SQLLIB Public Functions -- New Names” on page
4-34.
SQLLDAGetCurrent() Used to obtain a valid Logon Data Area for
the most recent connection, when OCI calls are used in a
Pro*C/C++ program. See “SQLLIB Public Functions -- New
Names” on page 4-34.
SQLColumnNullCheck() Returns an indication of null status for
dynamic SQL Method 4. See page 14-16.
SQLNumberPrecV6() Returns precision and scale of numbers. See
page 14-15.
SQLNumberPrecV7() A variant of SQLNumberPrecV6(). See page 14-
15.
SQLVarcharGetLength() Used for obtaining the padded size of a
VARCHAR[n]. See page 3-45.
- 120 -
COMPLEX QUERIES
CHAPTER
2 Learning the Basics
This chapter explains how embedded SQL programs do their work. You examine
the special environment in which they operate and the impact of this environment
on the design of your applications.
After covering the key concepts of embedded SQL programming and the steps you
take in developing an application, this chapter uses a simple program to illustrate
the main points. Topics are:
• Key Concepts of Embedded SQL Programming
• Steps in Developing an Embedded SQL Application
• Sample Tables
• Sample Program: A Simple Query
- 121 -
COMPLEX QUERIES
and end them with a semicolon. Pro*C/C++ translates all EXEC SQL
statements into calls to the runtime library SQLLIB.
Many embedded SQL statements differ from their interactive counterparts only
through the addition of a new clause or the use of program variables. The
following example compares interactive and embedded ROLLBACK
statements:
ROLLBACK WORK: -- interactive
EXEC SQL ROLLBACK WORK; -- embedded
These statements have the same effect, but you would use the first in an
interactive SQL environment (such as when running SQL*Plus), and the
second in a Pro*C/C++ program. Static Versus Dynamic SQL
Statements
Most application programs are designed to process static SQL statements and
fixed transactions. In this case, you know the makeup of each SQL statement
and transaction before runtime; that is, you know which SQL commands will
be issued, which database tables might be changed, which columns will be
updated, and so on.
However, some applications might be required to accept and process any
valid SQL statement at runtime. So, you might not know until runtime all the
SQL commands, database tables, and columns involved.
Dynamic SQL is an advanced programming technique that lets your program
accept or build SQL statements at run time and take explicit control over
datatype conversion.
Embedded PL/SQL Blocks
The Pro*C/C++ Precompiler treats a PL/SQL block like a single embedded SQL
statement. So, you can place a PL/SQL block anywhere in an application program
that you can place a SQL statement. To embed PL/SQL in your host program, you
simply declare the variables to be shared with PL/SQL and bracket the PL/SQL block
with the keywords EXEC SQL EXECUTE and END-EXEC. From embedded PL/SQL
blocks, you can manipulate Oracle data flexibly and safely because PL/SQL
supports all SQL data manipulation and transaction processing commands. For
more information about PL/SQL, see Chapter 6, “Using Embedded PL/SQL”.
Oracle Datatypes
Typically, a host program inputs data to Oracle, and Oracle outputs data to the
program. Oracle stores input data in database tables and stores output data in
program host variables. To store a data item, Oracle must know its datatype,
which specifies a storage format and valid range of values.
Oracle recognizes two kinds of datatypes: internal and external. Internal
datatypes specify how Oracle stores data in database columns. Oracle also
uses internal datatypes to represent database pseudocolumns, which return
specific data items but are not actual columns in a table.
External datatypes specify how data is stored in host variables. When your
host program inputs data to Oracle, if necessary, Oracle converts between the
external datatype of the input host variable and the internal datatype of the
target database column. When Oracle outputs data to your host program, if
necessary, Oracle converts between the internal datatype of the source
database column and the external datatype of the output host variable.
Arrays
Pro*C/C++ lets you define array host variables called host arrays and operate
on them with a single SQL statement. Using the array SELECT, FETCH,
DELETE, INSERT, and UPDATE statements, you can query and manipulate
large volumes of data with ease. You can also use host arrays inside a host
variable struct.
Datatype Equivalencing
- 122 -
COMPLEX QUERIES
- 123 -
COMPLEX QUERIES
Sample Tables
Most programming examples in this guide use two sample database tables:
DEPT and EMP. Their definitions follow:
CREATE TABLE DEPT
(DEPTNO NUMBER(2) NOT NULL,
DNAME VARCHAR2(14),
LOC VARCHAR2(13))
CREATE TABLE EMP
(EMPNO NUMBER(4) NOT NULL,
ENAME VARCHAR2(10),
JOB VARCHAR2(9),
MGR NUMBER(4),
HIREDATE DATE,
SAL NUMBER(7,2),
COMM NUMBER(7,2),
DEPTNO NUMBER(2))
Sample Data
Respectively, the DEPT and EMP tables contain the following rows
of data:
DEPTNO DNAME LOC
------- ---------- ---------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
----- ------- --------- ------ --------- ------ ------ -------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 30
Sample Tables
Most programming examples in this guide use two sample database tables:
DEPT and EMP. Their definitions follow:
CREATE TABLE DEPT
(DEPTNO NUMBER(2) NOT NULL,
DNAME VARCHAR2(14),
LOC VARCHAR2(13))
CREATE TABLE EMP
(EMPNO NUMBER(4) NOT NULL,
ENAME VARCHAR2(10),
JOB VARCHAR2(9),
MGR NUMBER(4),
HIREDATE DATE,
SAL NUMBER(7,2),
COMM NUMBER(7,2),
DEPTNO NUMBER(2))
Sample Data
- 124 -
COMPLEX QUERIES
Respectively, the DEPT and EMP tables contain the following rows
of data:
DEPTNO DNAME LOC
------- ---------- ---------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
----- ------- --------- ------ --------- ------ ------ -------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 30
- 125 -
COMPLEX QUERIES
- 126 -
COMPLEX QUERIES
printf(”%6.2f\n”, emprec.commission);
total_queried++;
} /* end inner for (;;) */
if (emp_number == 0) break;
printf(”\nNot a valid employee number - try again.\n”);
} /* end outer for(;;) */
printf(”\n\nTotal rows returned was %d.\n”, total_queried);
printf(”\nG’day.\n\n\n”);
/* Disconnect from ORACLE. */
EXEC SQL COMMIT WORK RELEASE;
exit(0);
}
void sql_error(msg)
char *msg;
{
char err_msg[128];
int buf_len, msg_len;
EXEC SQL WHENEVER SQLERROR CONTINUE;
printf(”\n%s\n”, msg); buf_len = sizeof (err_msg);
sqlglm(err_msg, &buf_len, &msg_len);
printf(”%.*s\n”, msg_len, err_msg);
EXEC SQL ROLLBACK RELEASE;
exit(1); }
- 127 -