Sunday, August 24, 2008

Interview Questions IV

Differentiate between TRUNCATE and DELETE

RUNCATE

DELETE

It is a DDL statement

It is a DML statement

It is a one way trip, cannot ROLLBACK

We can Rollback

Doesn't have selective features (where clause)

Has

Doesn't fire database triggers

Does

It requires disabling of referential constraints.

Does not require

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.


How to get the 25th row of a table

select * from emp where rowid=(select max(rowid) from emp where rownum<26)

OR

elect * from Emp where rownum < 26

minus

select * from Emp where rownum<25

Why equality condition does'nt work with rownum, i'm giving my explanation here?

the query
select * from emp where rownum=25;

it fetches first record makes it rownum 1 as it does'nt match the where criteria, the record discarded

it fetches 2nd record makes it rownum 1 again
that is why rownum=x does'nt work

How do we display the column values of a table?


DECLARE

CURSOR cr_data

IS

SELECT ROWID, a.*

FROM fnd_user a where rownum < 10;

l_table_name VARCHAR2(2000) := 'FND_USER';

-- IMP--This table name should be same as your from table in the above cursor

l_value VARCHAR2 (2000);

l_str VARCHAR2 (2000);

CURSOR column_names (p_table_name VARCHAR2)

IS

SELECT *

FROM all_tab_columns

WHERE table_name = p_table_name;

-- You can use order by clause here if you want.

BEGIN

FOR cr_rec IN cr_data

LOOP

-- We should pass the same Table Name

FOR cr_columc_rec IN column_names (l_table_name)

LOOP

l_str :=

'Select '

|| cr_columc_rec.column_name

|| ' from '||l_table_name||' where rowid = '||chr(39)

|| cr_rec.ROWID||chr(39);

DBMS_OUTPUT.put_line ('Query is ' || l_str);

EXECUTE IMMEDIATE l_str

INTO l_value;

DBMS_OUTPUT.put_line ( 'Column is '

|| cr_columc_rec.column_name

|| ' and Value is '

|| l_value

);

END LOOP;

END LOOP;

END;


Tell me the difference between instead of trigger, database trigger, and schema trigger?

Instead of trigger : A view cannot be updated , so if the user tries to update a view, then this trigger can be used , where we can write the code so that the data will be updated in the table, from which the view was created. Database trigger : this trigger will be fired when a database event ( dml operation ) occurs in the database table, like insert , update or delete. System triggers : this trigger will fire for database events like dtartup / shutdown of the server, logon / logoff of the user, and server errors ... and also for the ddl events, like alter, drop, truncate etc.


What is the diff between %Rowtype and %type?


%Rowtype means associating a single variable to a entire row.(It is one way of Declaring a composite plsql datatype "RECORD")

%type means associating a single variable to a particular column in table.

both %Rowtype and %type declarations are known as Anchored Declarations in plsql .


Wat is difference between Cursor and Ref Cursor ?

· Cursor is static one and ref cursor is dynamic with return type

Example for cursor:

declare

cursor c1 is select * from emp;

begin

for r1 in c1 loop

dbms_output.put_line(r1.empno||' '||r1.ename);

end loop;

end;

/

Example for ref cursor

CREATE OR REPLACE package emp_data is

-- Author : RPSINGH

-- Created : 8/17/2006 12:54:03 AM

-- Purpose : displaying the data from different tables

-- Public type declarations

type my_cur is ref cursor;

-- Public constant declarations

-- Public variable declarations

-- Public function and procedure declarations

procedure tabledata(tname in varchar2, v_cur out my_cur);

end emp_data;

/

CREATE OR REPLACE PACKAGE BODY EMP_DATA IS

procedure tabledata(tname in varchar2,v_cur out my_cur) is

begin

OPEN V_CUR FOR

'SELECT * FROM '||TNAME;

end tabledata;

end emp_data;

/

Now to use this code:

declare

v_cur employees%rowtype;

C_CUR EMP_DATA.MY_CUR;

begin

emp_data.tabledata('EMPLOYEES', C_CUR);

LOOP

FETCH C_CUR INTO V_CUR;

EXIT WHEN C_CUR%NOTFOUND;

DBMS_OUTPUT.PUT_LINE(V_CUR.FIRST_NAME||' '||V_CUR.LAST_NAME);

END LOOP;

END;

/

Cursor is a structure which points to a memory locations

While Ref-cursor is a data structure which point to a object which intern points to Memory locations.

Advantage of having Ref-cursor is that we can pass dynamically the Ref-cursor as a parameter to a procedure.

Can we create a table using with Procedure or Function?

DECLARE

BEGIN

EXECUTE IMMEDIATE 'create table employee(empno number(3),ename varchar2(10))';
END;

What is the Mutating trigger error?

Mutating error:- occurs when row level trigger accesses same table on which it is based while executing or the table currently being modified by the DML statements.



Interview Questions III


Difference between decode and case.
In which case we are using case and in which case we are using decode?
With an example?

Ans:- decode is a function where case is expression .
decode gives result different when using null see below

SQL> select decode( null,null,1,0) from dual;

DECODE(NULL,NULL,1,0)
---------------------
1

SQL>select case null when null then 1 else 0 end from dual
SQL> /

CASENULLWHENNULLTHEN1ELSE0END
-----------------------------
0
but see here


SQL> select case when null is null then 1 else 0 end from dual;

CASEWHENNULLISNULLTHEN1ELSE0END
-------------------------------
1

The Main Difference is that


1) Decode cannot be used in Where clause but Case can.

2) In Decode Else can be specifed in the statement it self but in Case a seperate statement has to be written.


What are the advantages and disadvantages of View?...


advantages

1. hiding the data.

2. you can use two tables data in view.

3. security will be there.

disadvantages

1.when table is not there view will not work.

2. dml is not possible if that is more than one table.

3. it is also database object so it will occupy the space.


Explain what is mutation and what is mutating table and how this mutation problem is solved in a table?

Mutation happens in case of triggers. A 'Mutating table’ is a table which is being updated by Insert, update or delete triggers. It can also be a table which is being updated when delete cascade is run.

Mutation occurs when a trigger is trying to update a row which it is using currently. To solve this either we have to use intermediate table or a view so that it can choose from one while updating the other.


What is the difference between single quote (') and double quote(") in relates to using in SQL. When do you use 'xxx' and "xxx"? what is the difference both of them?


Single quote is used to write a character string or character in sql query.

but,double quotes are used to print the name in sql screen.

for eg:-

select sysdate "current date" from dual;

current date

-----------------

24-mar-06.


How to get first 5 Records then next 5 records till end of row count in SQL –Oracle ?

elect * from emp where rownum<6

Then we can get the next 5 records by the following sql:

select * from emp where rownum<6>

and so on..

Find the two minimum salaries among table

Ans: select sal from (select * from order by sal asc) where rownum <>

How to get the prime number rows from table ie like1,3,5,7,11

Ans :

I tried in sql but sql is not sufficient. U may create a function like this

create or replace function fn_chk_pm(v_num in number) return number
is
v_flag number:=0;
v_j number:=round(v_num/2);
begin
for v_cnt in 2..v_j
loop
if mod(v_num,v_cnt)=0 then
v_flag:=1;
exit when v_flag=1;
end if;
end loop;
if v_flag=0 then
return 1;
end if;
if v_flag=1 then
return 0;
end if;
end;

Assumuming the table as follows

SQL> select * from dummyag;

COL1 COL2
---------- -
2 b
3 c
4 d
1 a

I can call it from sql statement as follows:

SQL>


1 select a.rn,a.col1,a.col2 from (select rownum rn,col1,col2 from dummyag) a
2 where fn_chk_pm(a.rn)=1
3* and a.rn!=1

With the result,


RN COL1 C
---------- ---------- -
2 3 c
3 4 d


Ans 2 : ((select * from emp where (rowid,1) in (select rowid,mod(rownum,2) from emp)) Minus
(select * from emp where (rowid,0) in (select rowid,mod(rownum,3) from emp))) union
(select * from emp where (rowid,3) in (select rowid,rownum from emp));




Sunday, August 17, 2008

Oracle's Interview question's II

Bitmap index

An index that maintains a binary string of ones and zeros for each distinct value of a column within the index.

Materialized View

A materialized view can help speed queries by storing data in a previously joined
or summarized format. Unlike a traditional view, this stores only the query and runs that query every time the view is accessed; a materialized view stores the results of the query in addition to the SQL statements of the view itself. Because the materialized view already contains the results of the view’s underlying query,
Using a materialized view can be as fast as accessing a single table.

OR

What is materialized view?

A materialized view is a database object that contains the results of a query. They are local copies of data located remotely, or are used to create summary tables based on aggregations of a table's data. Materialized views, which store data based on remote tables are also, know as snapshots.A materialized view can query tables, views, and other materialized views. Collectively these are called master tables (a replication term) or detail tables (a data warehouse term)


Alias

An alternate name for a column, specified right after the column name in a SELECT statement, seen in the results
Of the query.


DML (Data Manipulation Language)

Includes INSERT, UPDATE, DELETE, and MERGE statements that operate specifically on database tables. Occasionally, SELECT statements are included in the SQL DML category.

DUAL
A special table, owned by the Oracle SYS user, that has one row and one column.
It is useful for ad hoc queries that don’t require rows from a specific table.

NULL

A NULL is usually used to represent a value that is unknown,
not applicable, or not available.

Why order by clause maintains column number values instead of column names?

Every Column have unique number in the table, when we write ORDER BY Clause with number then it refers to that unique number and display the result.

You can see the column Id as per below query

SELECT COLUMN_NAME, COLUMN_ID FROM USER_TAB_COLUMNS
WHERE TABLE_NAME = 'EMP';

What is difference between SQL and SQL*PLUS?

SQL*PLUS is a command line tool where as SQL and PL/SQL language interface and reporting tool. Its a command line tool that allows user to type SQL commands to be executed directly against an Oracle database. SQL is a language used to query the relational database(DML,DCL,DDL). SQL*PLUS commands are used to format query result, Set options, Edit SQL commands and PL/SQL.

There are 10 rows in Table A and 0 Rows in table B.
Select * from A,B
How many rows will be retrieved.

Ans : it will not select any row.coz according to this query it has to give cartesian product.that means it will select m into n rowsso 10*0=0

No Rows Selected.

What is the difference between Rename and Alias?

Rename is a permanent name given to a Table or Column Whereas Alias is a temporary name given to a table or a column, which do not exist once the SQL statement is executed.

What is the Difference between stored procedures and anonymous procedure?

An external procedure, also sometimes referred to as an external routine, is a procedure stored in a dynamic link library (DLL), or libunit in the case of a Java class method. You register the procedure with the base language, and then call it to perform special-purpose processing. A stored procedure is a group of SQL statements that form a logical unit and perform a particular task. This will be stored in oracle database.

We have EMP and dept table .how do you get the entire department and corresponding employee details and the department which are not allotted it?

We use joins to get details from both the tables that’s kind of joins r called outer joins to get the missed statements.


select e.eno, e.ename, e.deptno
from emp e, dept d
where (+)e.deptno=d.deptno;

What is Complex View?Where we can use?

Views containing any group functions or joining tables are known as complex views.

Write query for the following questions
________________________________________
select * from emp where (rowid,0) in (select rowid,mod(rownum,2) from emp)

select * from emp where (rowid,0) not in (select rowid,mod(rownum,2) from emp)

How to retrieving the data from 11th column to n th column in a table.

select * from emp where rowid in ( select rowid from emp where rownum <=&upto minus select rowid from emp where rownum <&startfrom)

Oracle Interview Questions

Oracle FAQ's

1)FOREIGN KEY constraint

A constraint that establishes a parent child relationship between two tables via one or more common columns.

The foreign key in the child table refers to a primary or unique key in the parent table.

2)Transaction

A logical unit of work consisting of one or more SQL statements that must all succeed or all fails to keep the database in a logically consistent state. A transfer of funds from one bank account is a logical

Transaction, in that both the withdrawal from one account and the deposit to another account must succeed for the transaction to succeed.

3)Schema

A named group of objects associated with a particular user account, such as tables, indexes, functions, and so forth.

4)Relational table

The most common form of a table in the Oracle database; the default type created with the

CREATE TABLE statement. A relational table is permanent and can be partitioned.

5)External table

A table whose definition is stored in the database but whose data is stored externally to the database.

6)Index

A database object designed to reduce the amount of time it takes to retrieve rows from a table. An index is created based on one or more columns in the table.

7)Composite index

If an index that is created on two or more columns in a table. This is called as Composite index.

8)Sequence

It is a database structure that automatically generates a series of numbers typically used to assign primary key values to database tables.

9)Synonyms

A synonym is an alias for another database object, such as a table, sequence, or view.

Synonyms provide easier access to database objects outside the user’s schema.

There are two kinds of synonyms: public and private. Public synonyms are Available to all database users. A private synonym is available only in the session of the schema owner who created it.

10)Username

An Oracle database account identifier that, along with a password, allows a user to connect to the database.

11)Privileges

The right to perform a specific action in the database granted by the DBA or other database users.

12)System privileges

Privileges that allow users to perform a specific action on one or more database objects or users in the database.

13)Object privileges

Privileges that allow users to manipulate the contents of database objects in other schemas.

14)ROWID

A unique identifier for a row in a table, maintained automatically in the table by the Oracle server.

ROWIDs are unique throughout the database.

15)Unique Index

In a Unique index, there are no duplicate values. An error is returned if you try to insert two rows into a table with the same index column values. By default, an index is nonunique.

Saturday, August 16, 2008

Changing SYSMAN password



Stop the DB console by using below command on the command prompt.

$>emctl stop dbconsole

This should stop dbconsole and the agent.

Have a check first.

$>emctl status dbconsole

$>emctl status agent

$>sqlplus / as sysdba

SQL>alter user sysman identified by [New Password];

Then check the new password by connecting with sysman user. This is to make sure sysman is not locked. Because when the password is changed and you try to reach the OEM, it will lock the sysman user.

SQL>conn sysman/newpassword
connected.

if you get
ora-28000: account is locked

Then unlock it first.

SQL> alter user sysman account unlock;

Modifying the emoms.properties file.

It’s located at ORACLE_HOME/[HOST]_[SID]/sysman/config. Replace HOST with your computer name and SID with your SID.

There are 2 parameters to modify:

oracle.sysman.eml.mntr.emdRepPwd= [Your encrypted password]
oracle.sysman.eml.mntr.emdRepPwdEncrypted=True

Change [Your encrypted password] with your new password in the first parameter (unencrypted current sysman password)
and change True to False in the second parameter.

As soon as you restart Dbconsole and Oracle agent, it will change false to true and will get encrypted.

Start the dbconsole

$>emctl start dbconsole
$>emctl start agent