Tuesday, April 29, 2014

Toad for Oracle - Issues Solutions Tricks and Tips


Toad for Oracle

I am using Toad for Oracle for long time for my projects. Here, I have listed out few tricks and tips and issues/solution which I faced during my work. I happy to share this post to help someone :)


1.    Is there a way to disable the popup for Statement Processing window?

The below solution for

In case it is happening at the moment and want to cancel, the solution is just press Alt+F4 button.
I faced this problem many times and finally I closed the entire toad window, it causes I wanted to lost other queries from other tabs.
Just I found this Alt+F4 solution.

How to disable  "Statement processing" dialog in future?

Yes, there is an option to disable this popup window.
    1.    Go to View -> Options -> Oracle -> Transactions
    2.    Click on "Execute queries in threads [Creates separate session]"
You have to do it before login into any database to activate this option.

Remember, if any query running background, it will be indicated by double arrow on the tab.

If you love to see the window back, just un-check the above option.


2.    How to display the query execution time?

    1.    Go to View -> Options -> SQL Editor
    2.    Click on "Persist display of execution time"
   
   
3.    How to resolve "Object xxx not found" when press Ctrl+Mouse click?

 
Solution:
    1.    Ctrl+A
    2.    Ctrl+X
    3.    Ctrl+V


I will keep updating this post.


Wednesday, February 22, 2012

PLSQL -Interview QA - 2012 - Part4


How to find dependencies referenced Inside PL/SQL Store Procedure

The Oracle data dictionary tracks the object types referenced in PL/SQL with the dba_dependencies view. To track the dependency among packages and tables, try this dictionary query:

select
  referenced_owner,
  referenced_name,
  referenced_type
from
  DBA_DEPENDENCIES
where
  name= 'YOUR_PROCEDURE or PACKAGE NAME' and   owner = 'SCOTT'
order by
  referenced_owner, referenced_name, referenced_type;
 

Finding PL/SQL compilation errors

PL/SQL does not always tell you about compilation errors.

SQL>SHOW ERRORS
No errors.

But how to see the error?

You have to give the full command as follows:

SQL>SHOW ERROR PROCEDURE


Show Errors syntax: 

Usage: SHOW ERRORS [{ FUNCTION | PROCEDURE | PACKAGE |
   PACKAGE BODY | TRIGGER | VIEW
   | TYPE | TYPE BODY | DIMENSION
   | JAVA SOURCE | JAVA CLASS } [schema.]name] 
 
   
Finding Record count of all tables?
 
   PROMPT
     PROMPT ROWCOUNT for Table &Table_Name.

     SET FEEDBACK OFF
     SET SERVEROUTPUT ON
     DECLARE N NU MBER ;
     V VARCHAR2(100) ;
     BEGIN
     V := 'SELECT COUNT(*) FROM ' || UPPER('&Table_Name.') ;
     EXECUTE IMMEDIATE V INTO N ;
     DBMS_OUTPUT.PUT_LINE (N);
     END;
     /

SQL>SELECT COUNT(*) FROM EMP;
14 Records.   
SQL>SELECT COUNT(*) FROM DEPT;
4 Records.   
...
...

How do you find when an object was created , last modified date?

SELECT OWNER, OBJECT_NAME, CREATED, LAST_DDL_TIME
FROM DBA_OBJECTS
WHERE OBJECT_NAME = 'enter_object_name_here';
   
   
Sending E-Mail in PL/SQL

Oracle allows us to send email from PL/SQL. You can create a procedure to send mail as follows:

CREATE OR REPLACE PROCEDURE SEND_MAIL (
    msg_from     VARCHAR2 := 'sender@domain.com'
  , msg_to       VARCHAR
  , msg_subject  VARCHAR2 := 'E-Mail message from your database'
  , msg_text     VARCHAR2 := ''
)
IS
  c   UTL_TCP.CONNECTION;
  rc  INTEGER;
BEGIN
  c  := UTL_TCP.OPEN_CONNECTION('localhost', 25);       -- open the SMTP port 25 on local machine
  rc := UTL_TCP.WRITE_LINE(c, 'HELO localhost');
  rc := UTL_TCP.WRITE_LINE(c, 'MAIL FROM: '||msg_from);
  rc := UTL_TCP.WRITE_LINE(c, 'RCPT TO: '||msg_to);
  rc := UTL_TCP.WRITE_LINE(c, 'DATA');                  -- Start message body
  rc := UTL_TCP.WRITE_LINE(c, 'Subject: '||msg_subject);
  rc := UTL_TCP.WRITE_LINE(c, '');
  rc := UTL_TCP.WRITE_LINE(c, msg_text);
  rc := UTL_TCP.WRITE_LINE(c, '.');                     -- End of message body
  rc := UTL_TCP.WRITE_LINE(c, 'QUIT');
  UTL_TCP.CLOSE_CONNECTION(c);                          -- Close the connection
EXCEPTION
  WHEN others THEN
    RAISE_APPLICATION_ERROR(-20000, 'Unable to send e-mail message from PL/SQL routine.');
END;

SQL>exec send_mail('sender@domain.com','recipient@domain.com','Test message from first PLSQL','your message here ');


Wednesday, May 11, 2011

PL/SQL -Q&A - 2011 - Part 3


What is difference between Materialized View and Materialized Log?

Materialized views are schema objects that can be used to summarize, precompute, replicate, and distribute data. E.g. to construct a data warehouse or in multi-master replication environment.

A materialized view is a database object that contains the results of a query. The FROM clause of the query can name tables, views, and other materialized views. Collectively these objects are called master tables (a replication term) or detail tables (a data warehousing term). This reference uses "master tables" for consistency. The databases containing the master tables are called the master databases.

When you create a materialized view, Oracle Database creates one internal table and at least one index, and may create one view, all in the schema of the materialized view. Oracle Database uses these objects to maintain the materialized view data. You must have the privileges necessary to create these objects.


Materialized View Log - When DML changes are made to master table data, Oracle Database stores rows describing those changes in the materialized view log and then uses the materialized view log to refresh materialized views based on the master table. This process is called incremental or fast refresh. Without a materialized view log, Oracle Database must reexecute the materialized view query to refresh the materialized view. This process is called a complete refresh. Usually, a fast refresh takes less time than a complete refresh.


When DML changes are made to master table data, Oracle Database stores rows describing those changes in the materialized view log and then uses the materialized view log to refresh materialized views based on the master table. This process is called incremental or fast refresh. Without a materialized view log, Oracle Database must re-execute the materialized view query to refresh the materialized view. This process is called a complete refresh. Usually, a fast refresh takes less time than a complete refresh.

A materialized view log is located in the master database in the same schema as the master table. A master table can have only one materialized view log defined on it. Oracle Database can use this materialized view log to perform fast refreshes for all fast-refreshable materialized views based on the master table.

To fast refresh a materialized join view, you must create a materialized view log for each of the tables referenced by the materialized view.


Difference between Bigfile & Smallfile?

Big and small file tablespaces in the Oracle 10g database
It is the Oracle Database 10g feature. A bigfile tablespace (BFT) is a tablespace containing a single file that can have a very large size and on the other hand, a smallfile tablespace can contain many data files.
The size of a bigfile can reach to 128TB depending on the Oracle block size.

An Oracle database can contain both bigfile and smallfile tablespaces.
You can change the default tablespace type to BIGFILE or SMALLFILE.


How to sorting (Order By) LOB column data?
DBMS_LOB.SUBSTR is used to sort the LOB column


Can you give an example for the above?
Yes.

SQL> create table tab1(col1 number, col2 clob);
Table created.


SQL> insert into tab1 values (1,'this is a test record fro clob column');
1 row created.


SQL> insert into tab1 values (2, 'alangottai');
1 row created.


SQL>  insert into tab1 values (3,'mannargudi');
1 row created.


SQL> select * from tab1 order by col2;
select * from tab1 order by col2
       *
ERROR at line 1:
ORA-00932: inconsistent datatypes


SQL> select col1, dbms_lob.substr(col2,50,1) from tab1 order by 2;
         col1 DBMS_LOB.SUBSTR(col2,50,1)
---------- ----------------------------------------------
         2 alangottai
         3 mannargudi
         1 this is a test record fro clob column
 

What are the uses of database trigger?

  • Automatically generate derived column values
  • Enforce complex security authorizations
  • Prevent invalid transactions
  • Enforce referential integrity across nodes in a distributed database
  • Enforce complex business rules
  • Provide transparent event logging
  • Provide auditing
  • Maintain synchronous table replicates
  • Gather statistics on table access
  • Modify table data when DML statements are issued against views


Difference between Row Level Trigger and Statement Trigger?

Row Level Trigger:
A row trigger is fired each time the table is affected by the triggering statement. For example, if an UPDATE statement updates multiple rows of a table, a row trigger is fired once for each row affected by the UPDATE statement. If a triggering statement affects no rows, a row trigger is not run.

Row triggers are useful if the code in the trigger action depends on data provided by the triggering statement or rows that are affected. For example, Figure 22-2 illustrates a row trigger that uses the values of each row affected by the triggering statement.

Statement Triggers
A statement trigger is fired once on behalf of the triggering statement, regardless of the number of rows in the table that the triggering statement affects, even if no rows are affected. For example, if a DELETE statement deletes several rows from a table, a statement-level DELETE trigger is fired only once.

Statement triggers are useful if the code in the trigger action does not depend on the data provided by the triggering statement or the rows affected. For example, use a statement trigger to:

Make a complex security check on the current time or working hours, weekday, or user
Generate a single audit record.


Latest Interview QA for PLSQL with basic DBA experience Part 1


Where is the alert log files located on Oracle11g?

The alert.log file normally is in the $ORACLE_BASE//bdump location
Oracle 11g in the database specific location in the diagnostic_dest. Run the below query to find the location,
select value from v$parameter where name='background_dump_dest';


One of the most vexing problems that Oracle DBAs around the world face every day? What is that?
ORA-01555


How to resolve that "ORA-01555: snapshot too old" issue?
The common reason is that the Rollback segments are too small. If in AUM (Automatic Undo Management) mode, increase UNDO_RETENTION setting, otherwise use larger Rollback segments.

Info:  In Oracle database during the DML  (Insert / Update / Delete) operations for any changes to the data records, a snapshot of the record before the changes were made is copied to a rollback segment.


What is the main difference between Data Guard and Oracle RAC (Real Application Clusters)?
An Oracle Data Guard configuration can consist of any combination of single-instance and Oracle Real Application Clusters (RAC) multiple-instance databases.


How does one get the value of a sequence into a PL/SQL variable?
One can use embedded SQL statements to obtain sequence values:
select sq_sequence.NEXTVAL into :i from dual;

But direct assignment can be used in Oracle11g, it is a new feature in 11g.
i := sq_sequence.NEXTVAL;


Can create two before_insert trigger on same table?
Yes.
Oracle allows more than one trigger to be created for the same timing point, but it has never guaranteed the execution order of those triggers.

The Oracle 11g trigger syntax now includes the FOLLOWS clause to guarantee execution order for triggers defined with the same timing point.


What is Compound trigger?
Compound trigger is one the new feature in Oracle11g. It allows for writing a single trigger incorporating STATEMENT and ROW LEVEL and BEFORE and AFTER.


Oracle Forms Interview Questions & Answers Part 1


Oracle Forms – Technical – Interview – Question Answers

What are the Various Master and Detail Relation ships.
The various Master and Detail Relationship are
a) NonIsolated = The Master cannot be deleted when a child is existing
b) Isolated = The Master can be deleted when the child is existing
c) Cascading = The child gets deleted when the Master is deleted.

What are the master-detail triggers?
On-heck_delete_master
On_clear_details
On_populate_details These are automatically created when you create Master-Details block.

What are the types of Blocks in Forms?
Base Table block  - based on database table/views
Control Block  - non-database items are placed here like Calculation values,buttons,checkbox etc.

What are the Various Block Coordination Properties
The various Block Coordination Properties are
a) Immediate
Default Setting. The Detail records are shown when the Master Record are shown.
b) Deffered with Auto Query
Oracle Forms defer fetching the detail records until the operator navigates to the detail block.
c) Deffered with No Auto Query
The operator must navigate to the detail block and explicitly execute a query


Can a property clause itself be based on a property clause?
Yes


What are the different windows events activated at runtimes?
When_window_activated
When_window_closed
When_window_deactivated
When_window_resized
Within this triggers, you can examine the built in system variable system. event_window to determine the name of the window for which the trigger fired.

What are the trigger associated with image items?
When-image-activated fires when the operators double clicks on an image itemwhen-image-pressed fires when an operator clicks or double clicks on an image item


What is trigger associated with the timer?
When-timer-expired.

What is the difference between CALL_FORM, NEW_FORM and OPEN_FORM?
CALL_FORM: start a new form and pass control to it. The parent form will be suspended until the called form is terminated.
NEW_FORM: terminate the current form and replace it with the indicated new form. The old form's resources (like cursors and locks) will be released.
OPEN_FORM: Opens the indicated new form without suspending or replacing the parent form.

When a form is invoked with call_form, Does oracle forms issues
a save point?
Yes


What is new_form built-in?
When one form invokes another form by executing new_form oracle form exits the first form and releases its memory before loading the new form calling new form completely replace the first with the second. If there are changes pending in the first form, the operator will be prompted to save them before the new form is loaded.

What are visual attributes?
Visual attributes are the font, color, pattern proprieties that you set for form and menu objects that appear in your application interface.


Can one issue DDL statements from Forms?
DDL (Data Definition Language) commands like CREATE, DROP and ALTER are not directly supported from Forms because your Forms are not suppose to manipulate the database structure.
A statement like CREATE TABLE X (A DATE); will result in error:
Encountered the symbol "CREATE" which is a reserved word.
However, you can use the FORMS_DDL built-in to execute DDL statements. Eg:
FORMS_DDL('CREATE TABLE X (A DATE)');

Can one execute dynamic SQL from Forms?
Yes, use the FORMS_DDL built-in or call the DBMS_SQL database package from Forms. Eg:
FORMS_DDL('INSERT INTO X VALUES (' || col_list || ')');
Just note that FORMS_DDL will force an implicit COMMIT and may de-synchronize the Oracle Forms COMMIT mechanism.

What is the difference between the following statements?
Form A:   Insert into emp(ename) values ('MK Maran');
Form B:  FORMS_DDL('insert into emp(ename) values('||''MK Maran')');

User have to commit the form manually for Form A
Once the Form B statement executes, it will be implicitly commited.


Tuesday, April 12, 2011

Oracle Reports Interview Questions & Answers Part 1


racle Reports - Technical Interview Questions & Answers

How many different triggers are available in Report?

There are five types of triggers in report 6i
1) Before report trigger
2) After report trigger
3) Before Parameter trigger
4) After parameter trigger
5) Between pages trigger


What is the Firing sequence of report trigger?
First the before parameter trigger will raise, after firing this trigger parameter form will displayed,

after passing parameter after parameter trigger will fire query will parsed &

then before report trigger will fired then if there are number of pages in your report


then the between pages trigger will fired but it will fire between first & second & so on pages but it will not fired in reverse condition the after report trigger will fire


after closing the run time parameter form is closed.



What is the difference between After Parameter Trigger and Before Report Trigger? 

After parameter Trigger: It will fire after the parameter form is displayed.here we can do validation on parameter values
Before Report Trigger: It will fire before the report is executed and after the query is parsed and date is fetched.


What is the Format Trigger?
Format Trigger is a PL/SQL function. This trigger is going to fire before an object is printed in report output. it return boolean-true then go to print -false then don't print.


What is the diff. when Flex mode is mode on and when it is off?
When flex mode is on, reports automatically resizes the parent when the child is resized.


What is the diff. when confine mode is on and when it is off?
When confine mode is on, an object cannot be moved outside its parent in the layout.
 

What is a lexical parameter?
Lexical Parameter is used to replace the where, order by conditions at run time.


What are bind variables?
Bind variables are used in report 6i for replacing the single parameter in the select statement

 
How many different layouts are available in Reports?
There are eight different layout formats:
1. Tabular
2. Form Like
3. Form Letter
4. Mailing Label
5. Group Left
6. Group Above
7. Matrix
8. Matrix with group


What is the minimum number of groups required for a matrix report?
The minimum of groups required for a matrix report are 4

 
What is the lock option in reports layout?
By using the lock option we cannot move the fields in the layout editor outside the frame. This is useful for maintaining the fields.


What is the Anchoring in Reports?
Anchor is used to make fixed distance between two objects in Reports Layout.

 
What is the difference between Frame and Repeating Frame?
Frames are used to surround other objects and protect them from being overwritten or pushed by other objects. For example a frame might be used to surround all objects owned by a group to surround column headings or to surround summaries.

When you default the layout for a report Report Builder creates frames around report objects as needed; you can also create a frame manually in the Layout Model view.

Repeating frames surround all of the fields that are created for a group’s columns. The repeating frame prints (is fired) once for each record of the group.
When you default the layout for a report Report Builder creates repeating frames around fields as needed; you can also create a repeating frame manually in the Layout Model view


What are different types of column in reports?
There are three types of columns in the report 6i these are:
1) Placeholder Column – Placeholder column is used to store a value for a variable.
2) Formula Column
3) Summary Column


How many types of columns are there and what are they?
Formula columns: For doing mathematical calculations and returning one value

Summary Columns: For doing summary calculations such as summations etc.

Place holder Columns: These columns are useful for storing the value in a variable


Can u have more than one layout in report?
It is possible to have more than one layout in a report by using the additional layout option in the layout editor. Yes it is possible to run the report without parameter form by setting the PARAM value to Null


Oracle Forms Interview Questions & Answers Part 2


What are the vbx controls?
Vbx control provide a simple method of building and enhancing user interfaces. The controls can use to obtain user inputs and display program outputs.vbx control where originally develop as extensions for the ms visual basic environments and include such items as sliders, rides and knobs.

What is the "LOV of Validation" Property of an item? What is the use of it?

When LOV for Validation is set to True, Oracle Forms compares the current value of the text item to the values in the first column displayed in the LOV. Whenever the validation event occurs. If the value in the text item matches one of the values in the first column of the LOV, validation succeeds, the LOV is not displayed, and processing continues normally. If the value in the text item does not match one of the values in the first column of the LOV, Oracle Forms displays the LOV and uses the text item value as the search criteria to automatically reduce the list.

How do you use the same lov for 2 columns
We can use the same lov for 2 columns by passing the return values in global values and using the global values in the code

What are the difference between lov & list item?
Lov is a property where as list item is an item. A list item can have only one column, lov can have one or more columns

What is the difference between static and dynamic lov
The static lov contains the predetermined values while the dynamic lov contains values that come at run time

What are the different types of Record Groups?
Query Record Groups
NonQuery Record Groups
State Record Groups

What are the different display styles of list items?
Text_list
Pop_list
Combo box

Can on bypass the Oracle login screen?
The first thing that the user sees when using runform is the Oracle logon prompt asking them for their username, password, and database to connect to. You can bypass this screen or customise it by displaying your own logon screen.

Eg:

ON-LOGIN  Form-Level Trigger

declare
uname varchar2(10);
pass varchar2(10);
con_string varchar2(30);

begin
uname := 'scott';
pass :='tiger';
con_string='orcl';

logon(uname, pass||'@'||con_string);
end;

What are parameters?
Parameters provide a simple mechanism for defining and setting the valuesof inputs that are required by a form at startup. Form parameters are variables of type char,number,date that you define at design time.

What are difference between post database commit and post-form commit?
Post-form commit fires once during the post and commit transactions process, after the database commit occurs. The post-form-commit trigger fires after inserts, updates and deletes have been posted to the database but before the transactions have been finalized in the issuing the command. The post-database-commit trigger fires after oracle forms issues the commit to finalized transactions.

Can one Maximize/ Minimize a Window in Forms?
On MS-Windows, Forms run inside a Windows Multiple-Document Interface (MDI) window. You can use SET_WINDOW_PROPERTY on the window called FORMS_MDI_WINDOW to resize this MDI (or any other named) window. Examples:
set_window_property(FORMS_MDI_WINDOW, WINDOW_STATE, MINIMIZE);
set_window_property(FORMS_MDI_WINDOW, POSITION, 7, 15);
set_window_property('my_window_name', WINDOW_STATE, MAXIMIZE);

What are the different modals of windows?
Modalless windows
Modal windows

What are modal windows?
Modal windows are usually used as dialogs, and have restricted functionality compared to modelless windows. On some platforms for example operators cannot resize, scroll or iconify a modal window.


PL/SQL -Q&A2


What is Raise_application_error ?

Raise_application_error is a procedure of package DBMS_STANDARD which allows to
issue an user_defined error messages from stored sub-program or database trigger.


What are the return values of functions SQLCODE and SQLERRM ?
SQLCODE returns the latest code of the error that has occured.
SQLERRM returns the relevant error message of the SQLCODE.



Where the Pre_defined_exceptions are stored ?

In the standard package.
Procedures, Functions & Packages ;



What is difference between a PROCEDURE & FUNCTION ?

A FUNCTION is always returns a value using the return statement.
A PROCEDURE may return one or more values through parameters or may not
Return at all.



What are advantages of Stored Procedures?

Extensibility, Modularity, Reusability, Maintainability and one time compilation.



What are the modes of parameters that can be passed to a procedure ?

IN,OUT,IN-OUT parameters.

What are the two parts of a Pakage?
Pakage Specification and Pakage Body.



Give the structure of the procedure ?

PROCEDURE name (parameter list.....)
is
local variable declarations
BEGIN
Executable statements.
Exception.
exception handlers
end;

Give the structure of the function ?
FUNCTION name (argument list .....) Return datatype is
local variable declarations
Begin
executable statements
Exception
execution handlers
End;



Explain how procedures and functions are called in a PL/SQL block ?

Function is called as part of an expression.
sal := calculate_sal ('a822');
procedure is called as a PL/SQL statement
calculate_bonus ('A822');
26. What is Overloading of procedures ?
The Same procedure name is repeated with parameters of different datatypes and
parameters in different positions, varying number of parameters is called overloading of
procedures.

e.g. DBMS_OUTPUT put_line



What is a package ? What are the advantages of packages ?

Package is a database object that groups logically related procedures.
The advantages of packages are Modularity, Easier Applicaton Design, Information.
Hiding,. reusability and Better Performance.



What are two parts of package ?

The two parts of package are PACKAGE SPECIFICATION & PACKAGE BODY.

Package Specification contains declarations that are global to the packages and local to the schema.
Package Body contains actual procedures and local declaration of the procedures and cursor declarations.


What is difference between a Cursor declared in a procedure and Cursor
declared in a package specification ?

A cursor declared in a package specification is global and can be accessed by other
procedures or procedures in a package.
A cursor declared in a procedure is local to the procedure that can not be accessed by
other procedures.
30. Name the tables where characteristics of Package, procedure and functions are stored ?
User_objects, User_Source and User_error.


What is an Exception ? What are types of Exception ?

Exception is the error handling part of PL/SQL block. The types are Predefined and
user_defined. Some of Predefined execptions are.

CURSOR_ALREADY_OPEN
DUP_VAL_ON_INDEX
NO_DATA_FOUND
TOO_MANY_ROWS
INVALID_CURSOR<>INVALID_NUMBER
LOGON_DENIED
NOT_LOGGED_ON
PROGRAM-ERROR
STORAGE_ERROR
TIMEOUT_ON_RESOU RCE
VALUE_ERROR
ZERO_DIVIDE
OTHERS.


PL/SQL -Q&A1


What is PL/SQL ?

PL/SQL is a procedural language that has both interactive SQL and procedural
programming language constructs such as iteration, conditional branching.


What is the basic structure of PL/SQL ?

PL/SQL uses block structure as its basic structure. Anonymous blocks or nested blocks
can be used in PL/SQL.

Declarative part, Executable part and Execption part.

Declaration
;
Begin
Exception
End;


What are the datatypes a available in PL/SQL ?

Some scalar data types such as
NUMBER,VARCHAR2,DATE,CHAR,LONG,BOOLEAN.
Some composite data types such as RECORD & TABLE.


 What are % TYPE and % ROWTYPE ? What are the advantages of using these over datatypes?

% TYPE provides the data type of a variable or a database column to that variable.

% ROWTYPE provides the record type that represents a entire row of a table or view or
columns selected in the cursor.

The advantages:
i. Need not know about variable's data type
ii. If the database definition of a column in a table changes, the data type of a variable
changes accordingly.


What is difference between % ROWTYPE and TYPE RECORD ?

% ROWTYPE is to be used whenever query returns a entire row of a table or view.
TYPE rec RECORD is to be used whenever query returns columns of different table or views and variables.

E.g. TYPE r_emp is RECORD (eno emp.empno% type,ename emp ename %type );
e_rec emp% ROWTYPE
cursor c1 is select empno,deptno from emp;
e_rec c1 %ROWTYPE.


What is PL/SQL table ?

Objects of type TABLE are called "PL/SQL tables", which are modelled as (but not the same as) database tables, PL/SQL tables use a primary PL/SQL tables can have one column and a primary key.

What is a cursor ? Why Cursor is required ?
Cursor is a named private SQL area from where information can be accessed.
Cursors are required to process rows individually for queries returning multiple rows.

Explain the two type of Cursors ?

There are two types of cursors, Implict Cursor and Explicit Cursor.
PL/SQL uses Implict Cursors for queries.
User defined cursors are called Explicit Cursors. They can be declared and used.

What are the PL/SQL Statements used in cursor processing ?

DECLARE CURSOR cursor name, OPEN cursor name, FETCH cursor name INTO or Record types, CLOSE cursor name.

What are the cursor attributes used in PL/SQL ?

%ISOPEN - to check whether cursor is open or not
% ROWCOUNT - number of rows featched/updated/deleted.
% FOUND - to check whether cursor has fetched any row. True if rows are featched.
% NOT FOUND - to check whether cursor has featched any row. True if no rows are featched.
These attributes are proceded with SQL for Implict Cursors and with Cursor name for Explict Cursors.

What is a cursor for loop ?

Cursor for loop implicitly declares %ROWTYPE as loop index,opens a cursor, fetches
rows of values from active set into fields in the record and closes when all the records have
been processed.

eg. FOR emp_rec IN C1 LOOP
salary_total := salary_total +emp_rec sal;
END LOOP;


Explain the usage of WHERE CURRENT OF clause in cursors ?

WHERE CURRENT OF clause in an UPDATE,DELETE statement refers to the latest
row fetched from a cursor.

What is Pragma EXECPTION_INIT ? Explain the usage ?
The PRAGMA EXECPTION_INIT tells the complier to associate an exception with an
oracle error. To get an error message of a specific oracle error.

e.g. PRAGMA EXCEPTION_INIT (exception name, oracle error number)


Useful Scripts Collection Part 1


Do you have your own Blog or Website? Try PuppyURL - Free and Automated Directory Submission.


SCRIPT COLLECTION - How-to find global name of your database?
ora9i$maran> select * from global_name;

GLOBAL_NAME
-------------------------------------------------------
tifa.prod.com.sg

find Primary key constraints for a given table name?
ora9i$maran> Select
2 c.CONSTRAINT_NAME as PCN , c.TABLE_NAME PTN, c.COLUMN_NAME PCOL
3 from
4 USER_CONS_COLUMNS C ,user_constraints T
5 where
6 t. CONSTRAINT_NAME= c.CONSTRAINT_NAME AND
7 t.TABLE_NAME =c.TABLE_NAME AND
8 T.CONSTRAINT_TYPE='P' AND
9 c.table_name = '&TNAM'
10 /
Enter value for tnam: RIGHTS
PCN ; PTN ; PCOL
----------------------------------------------------------------------
SYS_C001420 RIGHTS &n bsp; RIGHTS_ID

find available indexes for a given table name?
ora9i$maran> select table_name||' - '|| COLUMN_NAME||' - '|| INDEX_NAME
2 from user_ind_columns where table_name like UPPER('%&TN%')
3 /
TABLE_NAME||'-'||COLUMN_NAME||'-'||INDEX_NAME
------------------------------------------------- -------
ACCT_CODE_MAS$ - ACCT_ID - ACCT_ID$_PK
ACCT_TRANS_MAS$ - ACCT_TRANS_ID - ACCT_TRANS_ID$_PK

find Primary key and Unique key for a given table?
SQL> SELECT B.TABLE_NAME||' - '||B.COLUMN_NAME||' -'||B.CONSTRAINT_NAME||' '|| DECODE(A.CONSTRAINT_TYPE, 'P', ' Primary Key ','U', ' Unique')
3 FROM
4 USER_CONSTRAINTS A, USER_CONS_COLUMNS B
5 WHERE A.CONSTRAINT_NAME = B.CONSTRAINT_NAME AND
6 A.TABLE_NAME = B.TABLE_NAME AND
7 A.CONSTRAINT_TYPE in ('U','P') and
8 A.TABLE_NAME LIKE upper('%&tn')
9 /
Enter value for tn: ROLE
old 8: A.TABLE_NAME LIKE upper('%&tn')
new 8: A.TABLE_NAME LIKE upper('%ROLE')
B.TABLE_NAME||'-'||B.COLUMN_NAME||'-'||B.CONSTRAINT_NAME||''||DECODE(A.CONSTRAIN
-------------- ------------------------------------------------------------------
ROLE_MAS$ - ROLE_ID – ROLL_MAS_PK Primary Key
ROLE_MAS$ - DESCRIPTION - ROLL_MAS_DESC_U Unique

find the object created date?
ora9iAS$maran@TIFA> select OBJECT_NAME||' - '||OBJECT_TYPE||' - '||CREATED from
2 user_objects where OBJECT_NAME like upper('%&objname%')
3 /
Enter value for objname: COUNTER_MAS$
old 2: user_objects where OBJECT_NAME like upper('%&objname%')
new 2: user_objects where OBJECT_NAME like upper('%COUNTER%')
OBJECT_NAME||'-'||OBJECT_TYPE||'-'||CREATED
--------------------------------------------------------------------------------
COUNTER_MAS$ - TABLE - 12-APR-07
COUNTER__MAS$_BCK - TABLE - 12-APR-07

find all schemas and its created date?
ora9iAS$maran@TIFA> select username,CREATED from all_users order by 2,1;
USERNAME CREATED
------------------------------ ---------
SYS 23-NOV-04
SYSTEM 23-NOV-04
TIFA 23-NOV-04
find reference tables of a given primary table?

ora9iAS$maran@TIFA> Select c.TABLE_NAME FTN
2 from
3 USER_CONS_COLUMNS C ,user_constraints T
4 where
5 t. CONSTRAINT_NAME= c.CONSTRAINT_NAME AND
6 t.TABLE_NAME = c.TABLE_NAME AND
7 T.CONSTRAINT_TYPE='R' AND
8 t.R_CONSTRAINT_NAME = (SELECT c.CONSTRAINT_NAME as PCNfrom
9 USER_CONS_COLUMNS C ,user_constraints T
10 where
11 t. CONSTRAINT_NAME= c.CONSTRAINT_NAME AND
12 t.TABLE_NAME =c.TABLE_NAME AND
13 T.CONSTRAINT_TYPE='P' AND
14 c.table_name = '&TNAM')
15 /
Enter value for tnam: COUNTER_MAS$'
old 14: c.table_name = '&TNAM')
new 14: c.table_name = 'COUNTER_MAS$')
FTN
------------------------------
DAILYTRANSACTION_DET$
LOGIN_LOG_DET$

find server ip address?
ora9iAS$maran@TIFA> SELECT UTL_INADDR.get_host_address from dual;
GET_HOST_ADDRESS
------------------------------------------------------------------------------ --
192.168.1.200

find last number of a given sequence?
ora9iAS$maran@TIFA> select SEQUENCE_NAME, LAST_NUMBER from user_sequences where upper(SEQUENCE_NAME) like upper('%&sn%');
Enter value for sn: BANK
old 2: where upper(SEQUENCE_NAME) like upper('%&sn%')
new 2: where upper(SEQUENCE_NAME) like upper('%BANK%')
SEQUENCE_NAME LAST_NUMBER
------------------------------ -----------
BANK_ID_SEQ 1

SQLLOADER:
SQL*Loader is a bulk loader utility used for moving data from external files into the Oracle database. SQL*Loader supports various load formats, selective loading, and multi-table loads.
Can I load more than one input file at the same time?
Yes.
LOAD DATA
INFILE 'C:empcsv1.csv'
INFILE 'C:empcsv2.csv'
INFILE 'C:empcsv3.csv'
TRUNCATE INTO TABLE EMP
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
TRAILING NULLCOLS
(
EMPNO,
ENAME,
SAL
)

You need to DBA privilege to run the following queries:

find out the objects created in SYSTEM tablespace other than SYSTEM, SYS users?
ora9i$maran> SELECT TABLE_NAME, OWNER from dba_tables
2 where TABLESPACE_NAME= 'SYSTEM' and
3 OWNER NOT IN ('SYSTEM','SYS');
TABLE_NAME OWNER
------------------------------------------------------------
COUNTER_MAS$ TIFA
RIGHTS_DET TIFA
2 rows selected.
ora9i$maran>

find size of the database?
ora9i$maran> select sum(bytes)/1024/1024 "Total DB size in Meg" from sys.v_$datafile;
Total DB size in Meg
--------------------
2543.4375

find segment size greater then 1 MB?
ora9i$maran> select OWNER||' - '||SEGMENT_NAME||' - '||(BYTES/1024)/1024||' MB'
2 from dba_segments where (BYTES/1024)/1024 >=1 AND
3 OWNER like UPPER('%&OWNER%')
4 /
Enter value for owner: UCB
OWNER||'-'||SEGMENT_NAME||'-'||(BYTES/1024)/1024||'MB'
---------------------------------------- ------------------------------------------
UCB - TERM1_DB - 6.515625 MB
UCB - TERM1_XL - 6.4609375 MB

find all schema size?
ora9i$maran> select owner , sum(bytes/1024/1024) MB
2 from dba_segments
3 group by owner order by 2
4 /
OWNER MB
----------------------------------------
KENT .0625
SYSTEM 3.34375
VIP 57.96875
CVB 263.25
ER_CVB 344.460938
SYS 391.492188

find users those who have DBA privilege?
ora9i$maran> select grantee "DBA Privilege"
2 from dba_role_privs
3 where granted_role='DBA';
DBA Privilege
------------------------------
SYS
SYSTEM

move objects from current tablespace to another
REM create a file name with movetsall.sql using this content
SET FEEDBACK OFF;
SET HEADING OFF;
SET ECHO OFF;
SET PAGESIZE 50000;
SET LINESIZE 100;
CLEAR SCREEN;
column movets new_value movets noprint
select 'c:'||'Move_Tablespace_Script_'||USER||'_'||to_char(sysdate,'DDMMYYYY')||'.SQL' movets from DUAL;
spool && movets
select decode( segment_type, 'TABLE',
segment_name, table_name ) order_col1,
decode( segment_type, 'TABLE', 1, 2 ) order_col2,
'alter ' || LOWER(segment_type) || ' ' || segment_name ||chr(10) ||
decode( segment_type, 'TABLE', ' move ', ' rebuild ' ) ||
' tablespace &Taget_Tablespace_Name ' ||chr(10) ||
' storage '||chr(10) ||
' ('||chr(10) ||
' initial ' || initial_extent || ' next ' ||next_extent ||chr(10) ||
' minextents ' || min_extents || ' maxextents ' ||max_extents ||chr(10) ||
' pctincrease ' || pct_increase || ' freelists ' ||
freelists ||chr(10) ||
' );'
from user_segments,
(select table_name, index_name from user_indexes )
where segment_type in ( 'TABLE', 'INDEX' )
and segment_name = index_name (+)
order by 1, 2
REM edit 'c:Move_Tablespace_Script__.SQL̢۪, modify as needed and run it.


DBA (Basic) Part 2


What is the use of Control File ?
When an instance of an ORACLE database is started, its control file is used to identify the database and redo log files that must be opened for database operation to proceed. It is also used in database recovery.

What does a Control file Contain ?
A Control file records the physical structure of the database. It contains the following information.

i. Database Name
ii. Names and locations of a database's files and redolog files.
iii. Time stamp of database creation.


What is the function of Redo Log ?
The Primary function of the redo log is to record all changes made to data.

What is the use of Redo Log Information ?
The Information in a redo log file is used only to recover the database from a system or media failure the prevents database data from being written to a database's data files.


What is a Data Dictionary ?

The data dictionary of an ORACLE database is a set of tables and views that are used a read-only reference about the database.

It stores information about both the logical and physical structure of the database, the valid users of an ORACLE database, integrity constraints defined for tables in the database and space allocated for a schema object and how much of it is being used.


What is Two-Phase Commit ?
Two-phase commit is mechanism that guarantees a distributed transaction either commits on all involved nodes or rolls back on all involved nodes to maintain data consistency across the global distributed database. It has two phase, a Prepare Phase and a Commit Phase.

Describe two phases of Two-phase commit ?
Prepare phase - The global coordinator (initiating node) ask a participants to prepare (to promise to commit or rollback the transaction, even if there is a failure)

Commit - Phase - If all participants respond to the coordinator that they are prepared, the coordinator asks all nodes to commit the transaction, if all participants cannot prepare, the coordinator asks all nodes to roll back the transaction.

What is the mechanism provided by ORACLE for table replication ?
Snapshots and SNAPSHOT LOGs

What is a SQL * NET?
SQL *NET is ORACLE's mechanism for interfacing with the communication protocols used by the networks that facilitate distributed processing and distributed databases. It is used in Clint-Server and Server-Server communications.

What is the use of ANALYZE command ?
To perform one of these function on an index,table, or cluster:

- to collect statisties about object used by the optimizer and store them in the data
dictionary.
- to delete statistics about the object used by object from the data dictionary.
- to validate the structure of the object.
- to identify migrated and chained rows of the table or cluster.

What are the benefits of distributed options in databases ?
Database on other servers can be updated and those transactions can be grouped together with others in a logical unit.
Database uses a two phase commit.

What is the use of COMPRESS option in EXP command ?
Flag to indicate whether export should compress fragmented segments into single extents.

What is the use of GRANT option in EXP command ?
A flag to indicate whether grants on databse objects will be exported or not. Value is 'Y' or
'N'.

What is the use of INDEXES option in EXP command ?
A flag to indicate whether indexes on tables will be exported.

What is the use of ROWS option in EXP command ?
Flag to indicate whether table rows should be exported. If 'N' only DDL statements for the
databse objects will be created.

What is the use of CONSTRAINTS option in EXP command ?
A flag to indicate whether constraints on table need to be exported.

What is the use of FULL option in EXP command ?
A flag to indicate whether full databse export should be performed.

What is the use of OWNER option in EXP command ?
List of table accounts should be exported.

What is the use of TABLES option in EXP command ?
List of tables should be exported.

What is the use of RECORD LENGTH option in EXP command ?
Record length in bytes.

What is the use of INCTYPE option in EXP command ?
Type export should be performed COMPLETE,CUMULATIVE,INCREMENTAL.

What is the use of RECORD option in EXP command ?
For Incremental exports, the flag indirects whether a record will be stores data dictionary
tables recording the export.

What is the use of PARFILE option in EXP command ?
Name of the parameter file to be passed for export.

What is the use of FILE option in IMP command ?
The name of the file from which import should be performed.

What is the use of IGNORE option in IMP command ?
A flag to indicate whether the import should ignore errors encounter when issuing CREATE
commands.

What is the use of GRANT option in IMP command ?
A flag to indicate whether grants on database objects will be imported.

What is the use of INDEXES option in IMP command ?
A flag to indicate whether import should import index on tables or not.

What is the use of ROWS option in IMP command ?
A flag to indicate whether rows should be imported. If this is set to 'N' then only DDL for database objects will be exectued.

What is the difference between a TEMPORARY tablespace and a PERMANENT tablespace?
A temporary tablespace is used for temporary objects such as sort structures while permanent tablespaces are used to store those objects meant to be used as the true objects of the database.

How can you rebuild an index?
ALTER INDEX REBUILD;

What is the difference between the SQL*Loader and IMPORT utilities?
These two Oracle utilities are used for loading data into the database. The difference is that the import utility relies on the data being produced by another Oracle utility EXPORT while the SQL*Loader utility allows data to be loaded that has been produced by other utilities from different data sources just so long as it conforms to ASCII formattsed or delimited files.


Name two files used for network connection to a database.

TNSNAMES.ORA and SQLNET.ORA


DBA (Basic) Part 1


Do you have your own Blog or Website? Try PuppyURL - Free and Automated Directory Submission.


Level: Intermediate

What are the components of Physical database structure of Oracle Database?.
ORACLE database is comprised of three types of files. One or more Data files, two are more Redo Log files, and one or more Control files.

What are the components of Logical database structure of ORACLE database?
Tablespaces and the Database's Schema Objects.

What is a Tablespace?

A database is divided into Logical Storage Unit called tablespaces. A tablespace is used to grouped related logical structures together.

What is Tablespace Quota ?
The collective amount of disk space available to the objects in a schema on a particular tablespace.


What is SYSTEM tablespace and When is it Created?
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.

Explain the relationship among Database, Tablespace and Data file.
Each databases logically divided into one or more tablespaces One or more data files are explicitly created for each tablespace.

What is schema?
A schema is collection of database objects of a User.

What are Schema Objects ?
Schema objects are the 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.

Can objects of the same Schema reside in different tablespaces.?
Yes.

Can a Tablespace hold objects from different Schemes ?
Yes.

What is a Synonym ?
A synonym is an alias for a table, view,sequence or program unit.

What are the type of Synonyms ?
There are two types of Synonyms Private and Public.

What is a Private Synonyms ?
A Private Synonyms can be accessed only by the owner.

What is a Public Synonyms ?
A Public synonyms can be accessed by any user on the database.

What are synonyms used for ?
Synonyms are used to : Mask the real name and owner of an object.
Provide public access to an object
Provide location transparency for tables,views or program units of a remote database.
Simplify the SQL statements for database users.

What is an Index ?
An Index is an optional structure associated with a table to have direct access to rows,which can be created to increase the performance of data retrieval. Index can be created on one or more columns of a table.

How are Indexes Update ?
Indexes are automatically maintained and used by ORACLE. Changes to table data are automatically incorporated into all relevant indexes.

What is Database Link ?
A database link is a named object that describes a "path" from one database to another.

What are the types of Database Links ?

Private Database Link, Public Database Link & Network Database Link.

What is Private Database Link ?
Private database link is created on behalf of a specific user. A private database link can be used only when the owner of the link specifies a global object name in a SQL statement or in the definition of the owner's views or procedures.

What is Public Database Link ?
Public database link is created for the special user group PUBLIC. A public database link can be used when any user in the associated database specifies a global object name in a SQL statement or object definition.

What is Row Chaining ?
In Circumstances, all of the data for a row in a table may not be able to fit in the same data block. When this occurs , the data for the row is stored in a chain of data block (one or more) reserved for that segment.

What is a Data File ?
Every ORACLE database has one or more physical data files. A database's data files contain all the database data. The data of logical database structures such as tables and indexes is physically stored in the data files allocated for a database.

What are the Characteristics of Data Files ?
A data file can be associated with only one database.
Once created a data file can't change size.
One or more data files form a logical unit of database storage called a tablespace.

What is a Redo Log ?
The set of Redo Log files for a database is collectively known as the database's redo log.


SQL*Plus and SQL - Part 2


What is difference between TRUNCATE & DELETE ?

TRUNCATE commits after deleting entire table i.e., can not be rolled back.
Database triggers do not fire on TRUNCATE

DELETE allows the filtered deletion. Deleted records can be rolled back or committed.
Database triggers fire on DELETE.

What is a join ? Explain the different types of joins ?

Join is a query which retrieves related columns or rows from multiple tables.

Self Join - Joining the table with itself.
Equi Join - Joining two tables by equating two common columns.
Non-Equi Join - Joining two tables by equating two common columns.
Outer Join - Joining two tables in such a way that query can also retrive rows that do not have corresponding join value in the other table.

Difference between SUBSTR and INSTR ?

INSTR (String1,String2(n,(m)),
INSTR returns the position of the mth occurrence of the string 2 in string1. The search begins from nth position of string1.

SUBSTR (String1 n,m)
SUBSTR returns a character string of size m in string1, starting from nth postion of string1.

Explain UNION,MINUS,UNION ALL, INTERSECT ?

INTERSECT returns all distinct rows selected by both queries.
MINUS - returns all distinct rows selected by the first query but not by the second.
UNION - returns all distinct rows selected by either query
UNION ALL - returns all rows selected by either query,including all duplicates.

What is ROWID ?

ROWID is a pseudo column attached to each row of a table. It is 18 character long, blockno, rownumber are the components of ROWID.

What is the fastest way of accessing a row in a table ?

Using ROWID.

What is difference between CHAR and VARCHAR2 ? What is the maximum SIZE allowed for each type ?

CHAR pads blank spaces to the maximum length. VARCHAR2 does not pad blank spaces. For CHAR it is 255 and 2000 for VARCHAR2.

How many LONG columns are allowed in a table ? Is it possible to use LONG columns in WHERE clause or ORDER BY ?

Only one LONG columns is allowed. It is not possible to use LONG column in WHERE or ORDER BY clause.

What are the pre requisites ?
i. to modify datatype of a column ?
ii. to add a column with NOT NULL constraint ?

To Modify the datatype of a column the column must be empty.
To add a column with NOT NULL constrain, the table must be empty.

Where the integrity constrints are stored in Data Dictionary ?

The integrity constraints are stored in USER_CONSTRAINTS.

How will you a activate/deactivate integrity constraints ?

The integrity constraints can be enabled or disabled by ALTER TABLE ENABLE constraint/DISABLE constraint.

If an unique key constraint on DATE column is created, will it validate the rows that are inserted with SYSDATE ?

It won't, Because SYSDATE format contains time attached with it.

How to access the current value and next value from a sequence ? Is it possible to access the current value in a session before accessing next value ?

Sequence name CURRVAL, Sequence name NEXTVAL.

It is not possible. Only if you access next value in the session, current value can be accessed.

What is CYCLE/NO CYCLE in a Sequence ?

CYCLE specifies that the sequence continues to generate values after reaching either maximum or minimum value. After pan ascending sequence reaches its maximum value, it generates its minimum value. After a descending sequence reaches its minimum, it generates its maximum.

NO CYCLE specifies that the sequence cannot generate more values after reaching its maximum or minimum value.


What is a database trigger ? Name some usages of database trigger ?

Database trigger is stored PL/SQL program unit associated with a specific database table.
Usages are Audit data modificateions, Log events transparently, Enforce complex business
rules Derive column values automatically, Implement complex security authorizations.
Maintain replicate tables.

How many types of database triggers can be specified on a table ? What are they ?

Insert Update Delete

Before Row Yes Yes Yes
After Row Yes Yes Yes
Before Statement Yes Yes Yes
After Statement Yes Yes Yes

If FOR EACH ROW clause is specified, then the trigger for each Row affected by the
statement.

If WHEN clause is specified, the trigger fires according to the retruned boolean value.


Is it possible to use Transaction control Statements such a ROLLBACK or
COMMIT in Database Trigger ? Why ?

It is not possible. As triggers are defined for each table, if you use COMMIT of
ROLLBACK in a trigger, it affects logical transaction processing.

What are two virtual tables available during database trigger execution ?

The table columns are referred as OLD.column_name and NEW.column_name.
For triggers related to INSERT only NEW.column_name values only available.
For triggers related to UPDATE only OLD.column_name NEW.column_name values only
available.
For triggers related to DELETE only OLD.column_name values only available.

What happens if a procedure that updates a column of table X is called in a database trigger of the same table ?

Mutation of table occurs.

You have just compiled a PL/SQL package but got errors, how would you view the errors?

SHOW ERRORS


How to generate query result in Text file through SQL Plus prompt?

Use SPOOL / ON / OFF

Example:
SQL>
SQL>spool c:\emp_output.txt
SQL>select * from emp;
...
...
SQL>spool off

A text file with the file name of emp_output.txt will be created in your C:\ drive.

Note: Don't forget to issue "spool off" statement. This "spool off" tells oracle to stop spooling. If you forget, all the statements will be recorded into this file until you close SQL Plus.


SQL*Plus and SQL - Part 1


Do you have your own Blog or Website? Try PuppyURL - Free and Automated Directory Submission.


what is Table ?

A table is the basic unit of data storage in an ORACLE database. The tables of a database hold all of the user accessible data. Table data is stored in rows and columns.


What is a View ?

A view is a virtual table. Every view has a Query attached to it. (The Query is a SELECT statement that identifies the columns and rows of the table(s) the view uses.)


Do View contain Data ?

Views do not contain or store data.


Can a View based on another View ?

Yes.

What are the advantages of Views ?

i. Provide an additional level of table security, by restricting access to a predetermined set of rows and columns of a table.
ii. Hide data complexity.
iii. Simplify commands for the user.
iv. Present the data in a different perpecetive from that of the base table.
v. Store complex queries.

Can a view be updated/inserted/deleted? If Yes under what conditions ?

A View can be updated/deleted/inserted if it has only one base table if the view is based on columns from one or more tables then insert, update and delete is not possible.

If a View on a single base table is manipulated will the changes be reflected on the base table ?

If changes are made to the tables which are base tables of a view will the changes be reference on the view.


What is a Sequence ?

A sequence generates a serial list of unique numbers for numerical columns of a database's tables.

How to see current user name
Sql> show user;

Change SQL prompt name

SQL> set sqlprompt ?Manimara > ?
Manimara >
Manimara >

Switch to DOS prompt
SQL> host

How do I eliminate the duplicate rows ?

SQL> delete from table_name where rowid not in (select max(rowid) from table group by duplicate_values_field_name);
Example:
SQL> delete duplicate_values_field_name dv from table_name ta where rowid <(select min(rowid) from table_name tb where ta.dv=tb.dv);
Example.
Table Emp
Empno Ename
101 Scott
102 Jiyo
103 Millor
104 Jiyo
105 Smith
delete ename from emp a where rowid < ( select min(rowid) from emp b where a.ename = b.ename);
The output like,
Empno Ename
101 Scott
102 Millor
103 Jiyo
104 Smith

How do I display row number with records?
To achive this use rownum pseudocolumn with query, like SQL> SQL> select rownum, ename from emp;
Output:
1 Scott
2 Millor
3 Jiyo
4 Smith


Display the records between two range
select rownum, empno, ename from emp where rowid in
(select rowid from emp where rownum <=&upto
minus
select rowid from emp where rownum<&Start);
Enter value for upto: 10
Enter value for Start: 7
ROWNUM EMPNO ENAME
--------- --------- ----------
1 7782 CLARK
2 7788 SCOTT
3 7839 KING
4 7844 TURNER


I know the nvl function only allows the same data type(ie. number or char or date Nvl(comm, 0)), if commission is null then the text ?Not Applicable? want to display, instead of blank space. How do I write the query?
SQL> select nvl(to_char(comm.),'NA') from emp;
Output :
NVL(TO_CHAR(COMM),'NA')
-----------------------
NA
300
500
NA
1400
NA
NA


Oracle cursor : Implicit & Explicit cursors
Oracle uses work areas called private SQL areas to create SQL statements.
PL/SQL construct to identify each and every work are used, is called as Cursor.
For SQL queries returning a single row, PL/SQL declares all implicit cursors.
For queries that returning more than one row, the cursor needs to be explicitly declared.


Explicit Cursor attributes
There are four cursor attributes used in Oracle
cursor_name%Found, cursor_name%NOTFOUND, cursor_name%ROWCOUNT, cursor_name%ISOPEN


Implicit Cursor attributes
Same as explicit cursor but prefixed by the word SQL
SQL%Found, SQL%NOTFOUND, SQL%ROWCOUNT, SQL%ISOPEN
Tips : 1. Here SQL%ISOPEN is false, because oracle automatically closed the implicit cursor after executing SQL statements.
: 2. All are Boolean attributes.


Find out nth highest salary from emp table
SELECT DISTINCT (a.sal) FROM EMP A WHERE &N = (SELECT COUNT (DISTINCT (b.sal)) FROM EMP B WHERE a.sal<=b.sal);
Enter value for n: 2
SAL
---------
3700


To view installed Oracle version information
SQL> select banner from v$version;


Friday, March 11, 2011

SQL*Plus and SQL - Part 3


Display the number value in Words
SQL> select sal, (to_char(to_date(sal,'j'), 'jsp'))
from emp;
the output like,
SAL (TO_CHAR(TO_DATE(SAL,'J'),'JSP'))
--------- -----------------------------------------------------
800 eight hundred
1600 one thousand six hundred
1250 one thousand two hundred fifty
If you want to add some text like,
Rs. Three Thousand only.
SQL> select sal "Salary ",
(' Rs. '|| (to_char(to_date(sal,'j'), 'Jsp'))|| ' only.'))
"Sal in Words" from emp
/
Salary Sal in Words
------- ------------------------------------------------------
800 Rs. Eight Hundred only.
1600 Rs. One Thousand Six Hundred only.
1250 Rs. One Thousand Two Hundred Fifty only.

Display Odd/ Even number of records
Odd number of records:
select * from emp where (rowid,1) in (select rowid, mod(rownum,2) from emp);
1
3
5
Even number of records:
select * from emp where (rowid,0) in (select rowid, mod(rownum,2) from emp)
2
4
6


Which date function returns number value?
months_between


Any three PL/SQL Exceptions?
Too_many_rows, No_Data_Found, Value_Error, Zero_Error, Others

What are PL/SQL Cursor Exceptions?
Cursor_Already_Open, Invalid_Cursor


Other way to replace query result null value with a text
SQL> Set NULL ?N/A?
to reset SQL> Set NULL ??


What are the more common pseudo-columns?
SYSDATE, USER , UID, CURVAL, NEXTVAL, ROWID, ROWNUM


What is the output of SIGN function?
1 for positive value,
0 for Zero,
-1 for Negative value.

What is Cursor ?

A Cursor is a handle ( a name or pointer) for the memory associated with a specific statement

What is the maximum number of triggers, can apply to a single table?
12 triggers

What is a Procedure ?

A Procedure consist of a set of SQL and PL/SQL statements that are grouped together as a unit to solve a specific problem or perform a set of related tasks.

What is difference between Procedures and Functions ?

A Function returns a value to the caller where as a Procedure does not.

What is a Package ?

A Package is a collection of related procedures, functions, variables and other package constructs together as a unit in the database.

What are the advantages of having a Package ?

Increased functionality (for example,global package variables can be declared and used by any proecdure in the package) and performance (for example all objects of the package are parsed compiled, and loaded into memory once)

What are the uses of Database Trigger ?

Database triggers can be used to automatic data generation, audit data modifications, enforce complex Integrity constraints, and customize complex security authorizations.

What are the differences between Database Trigger and Integrity constraints ?

A declarative integrity constraint is a statement about the database that is always true.
A constraint applies to existing data in the table and any statement that manipulates the table.

A trigger does not apply to data loaded before the definition of the trigger, therefore, it does not guarantee all data in a table conforms to the rules established by an associated trigger.

A trigger can be used to enforce transitional constraints where as a declarative integrity constraint cannot be used.


What is an Integrity Constrains ?

An integrity constraint is a declarative way to define a business rule for a column of a table.

Describe the different type of Integrity Constraints supported by ORACLE ?

NOT NULL Constraint - Disallows NULLs in a table's column.
UNIQUE Constraint - Disallows duplicate values in a column or set of columns.
PRIMARY KEY Constraint - Disallows duplicate values and NULLs in a column or set of columns.
FOREIGN KEY Constrain - Require each value in a column or set of columns match a value in a related table's UNIQUE or PRIMARY
KEY.
CHECK Constraint - Disallows values that do not satisfy the logical expression of the
constraint.

What is difference between UNIQUE constraint and PRIMARY KEY constraint ?

A column defined as UNIQUE can contain NULLs while a column defined as
PERIMETER KEY can't contain Nulls.

What is the maximum number of CHECK constraints that can be defined on a column ?

No Limit.


Tuesday, April 13, 2010

Forms 4.5/5.0/6.0/9i Techniques with Examples


List of Forms:


  • Generate INSERT Statements from existing Oracle tables Updated GenInster.zip V3.8


  • Dropping All Tables without drop/recreate user


  • Popup LOV after 3 attempts failed to enter valid value



  • Key Feature:
    Generates INSERT statements for entire table records
    Generates Individual SQL file for each table
    Generates Single SQL file for all table
    &
    With Source Code






    Click to download FMB File - Updated GenInster.zip V3.8





    Key Feature:
    No need to drop and recreate user
    It removes all tables
    Integrity Constraints will not affect this tool
    &
    With Source Code






    Click to download FMB File


    Warning: This Form created for Demo purpose only.
    Take a User Level Backup or export before using this tool.
    Create a Dummy User and Then Try.
    Key Feature:

    It gives 3 chances to enter correct value(clear invalid value and reset the cursor position)
    LOV shows the valid list after 3 wrong entries
    Conditionally Changing the Particular Field color
    &
    With Source Code



    Click to download FMB File
    Related Books: