Sunteți pe pagina 1din 38

1>What are the Advantages of SQL

* High Speed:
SQL Queries can be used to retrieve large amounts of
records from a database quickly and efficiently.
* Well Defined Standards Exist:
SQL databases use long-established standard,
which is being adopted by ANSI & ISO. Non-SQL
databases do not adhere to any clear standard.
* No Coding Required:
Using standard SQL it is easier to manage database
systems without having to write substantial amount
of code.
* Emergence of ORDBMS:
Previously SQL databases were synonymous with
relational database. With the emergence of Object
Oriented DBMS, object storage capabilities are
extended to relational databases.
2>What is join and how many types of joins?

The purpose of a join is to combine the data across tables.
A join is actually performed by the where clause which combines the specified rows of
tables.
If a join involves in more than two tables then oracle joins first two tables based on the
joins condition and then compares the result with the next table and so on.
TYPES
Equi join
Non-equijoin
Self join
Natural join
Cross join
Outer join
Left outer
Right outer
Full outer
Inner join
Using clause
On clause



3. Differences between count(1) and count(*).
Count(*) will check for all rows and column and takes more time but count(1) will count
directly the rows alone


4. Differentiate between TRANSLATE and REPLACE.
TRANSLATE function:
Translate function does character by character substitution in a string
format- TRANSLATE(STRING,IF,THEN)
Translate looks at each character in 'STRING' and then check 'IF' to see if that character is there,
if it is there then it notes the position in 'IF' where it found the character and then looks the
same position in 'THEN'
for example-
SELECT TRANSLATE('NOW VOWELS ARE UNDER ATTACK','TAEIOU','Taeiou') FROM
dual;
Result- NoWVoWeLSaReuNDeRaTTaCK
this feature of TRANSLATE, ability to eliminate characters from a string, can prove very useful
in cleaning up data.
REPLACE
REPLACE function replaces a character or characters in a string with zero or more charcters
REPLACE('ADAH','A','BLAH')
this evaluate the string 'ADAH'.
Everywhere an 'A' is found, it will be replaced with a string 'BLAH'
so the result will be- BLAHDBLAHH
2.REPLACE('GEORGE','GE',NULL)
result- OR


5. What is composite data type?
A composite data type stores values that have internal components. You can pass entire
composite variables to subprograms as parameters, and you can access internal components
of composite variables individually. Internal components can be either scalar or composite. You
can use scalar components wherever you can use scalar variables. PL/SQL lets you define two
kinds of composite data types, collection and record. You can use composite components
wherever you can use composite variables of the same type.



6. Differences between CHAR and NCHAR in Oracle.
Both CHAR and NCHAR are fixed length character data types. But they have the following
differences:
CHAR's size is specified in bytes by default.
NCHAR's size is specified in characters by default. A character could be 1 byte to 4 bytes
long depending on the character set used.
NCHAR stores characters in Unicode.


7. Differences between CHAR and VARCHAR2 in Oracle.
The main differences between CHAR and VARCHAR2 are:
CHAR stores values in fixed lengths. Values are padded with space characters to match
the specified length.
VARCHAR2 stores values in variable lengths. Values are not padded with any
characters.


8. What is an External Table?
You can use external table feature to access external files as if they are tables inside the
database.
When you create an external table, you define its structure and location with in oracle.
When you query the table, oracle reads the external table and returns the results just as if
the data had been stored with in the database.

BENEFITS OF EXTERNAL TABLES
a) Queries of external tables complete very quickly even though a full table scan id
required with each access
b) You can join external tables to each other or to standard tables


9. Which one is faster delete/truncate? Why?
Truncante is performs better than delete because when you delete the records from the database
, database has to perform 2 actions.
1.delete from the database
2.write the deleted records into "rollback" segments.
But incase of "Truncate" the second activity is not required.



10. Explain how to DISABLE and ENABLE constraint.
OPERATIONS WITH CONSTRAINTS
Possible operations with constraints as follows.
Enable
Disable
Enforce
Drop

ENABLE
This will enable the constraint. Before enable, the constraint will check the existing data.
Ex:
SQL>alter table student enable constraint un;
DISABLE
This will disable the constraint.
Ex:
SQL>alter table student enable constraint un;
ENFORCE
This will enforce the constraint rather than enable for future inserts or updates.
This will not check for existing data while enforcing data.
Ex:
SQL>alter table student enforce constraint un;
DROP
This will remove the constraint.
Ex:
SQL>alter table student drop constraint un;
Once the table is dropped, constraints automatically will drop.



11. Difference between truncate and drop.
TRUNCATE
TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers
will be fired. As such, TRUCATE is faster and doesn't use as much undo space as a DELETE.
SQL> TRUNCATE TABLE emp;

Table truncated.

SQL> SELECT COUNT(*) FROM emp;

COUNT(*)
----------
0
DROP
The DROP command removes a table from the database. All the tables' rows, indexes and
privileges will also be removed. No DML triggers will be fired. The operation cannot be rolled
back.
SQL> DROP TABLE emp;

Table dropped.

SQL> SELECT * FROM emp;
SELECT * FROM emp
*
ERROR at line 1:
ORA-00942: table or view does not exist

DROP and TRUNCATE are DDL commands, whereas DELETE is a DML command. Therefore
DELETE operations can be rolled back (undone), while DROP and TRUNCATE operations
cannot be rolled back.
From Oracle 10g a table can be "undropped". Example:
SQL> FLASHBACK TABLE emp TO BEFORE DROP;

Flashback complete.
PS: DROP and TRUNCATE are DDL commands, whereas DELETE is a DML command. As
such, DELETE operations can be rolled back (undone), while DROP and TRUNCATE
operations cannot be rolled back.

12. Write a query to display all the odd numbers from a table in which year did most
employees joined in the company .display the year and the number of employees.


13. write a correlated sub query to list out the employees.

14. who earn more than the average salary of their department.

15. write a query to find nth maximum salary .
Select *from emp where sal in (select max(sal) from (select *from emp order by sal)
where rownum <= 5);
16. Which data type is used for storing graphics and images?
LONG RAW data type is used for storing BLOB's (binary large objects).
17. What are various privileges that a user can grant to another user?
There are two distinct categories of privileges:
system privileges
object privileges
System Privileges
A system privilege is the right to perform a particular action, or to perform a particular action on
a particular type of object. For example, the privileges to create tablespaces and to delete the
rows of any table in a database are system privileges. There are over 60 distinct system
privileges.
Object Privileges
An object privilege is a privilege or right to perform a particular action on a specific table, view,
sequence, procedure, function, or package. For example, the privilege to delete rows from the
table DEPT is an object privilege. Depending on the type of object, there are different types of
object privileges.

18. What is the difference between joins and set operators?
JOIN:
A Join is used for displaying columns with the same or different names from different tables.
The output displayed will have all the columns shown individually. i.e. The columns will be
aligned next to each other.
UNION:
The UNION set operator is used for combining data from two tables which have columns with
the same datatype. When a UNION is performed the data from both tables will be collected in a
single column having the same datatype.

19. What is the difference between UNION and UNION ALL?
Both UNION and UNION ALL concatenate the result of two different SQLs. They differ in the
way they handle duplicates.
-UNION performs a DISTINCT on the result set, eliminating any duplicate rows.
-UNION ALL does not remove duplicates, and it therefore faster than UNION.

20. What is the difference among UNION, MINUS and INTERSECT?

UNION
It returns a union of two select statements. It is returning unique (distinct) values of them.
UNION ALL
Similar to UNION just that UNION ALL returns also the duplicated values.
MINUS
MINUS (also known as EXCEPT) returns the difference between the first and second SELECT
statement. It is the one where we need to be careful which statement will be put first, cause we
will get only those results that are in the first SELECT statement and not in the second.
INTERSECT
INTERSECT is opposite from MINUS as it returns us the results that are both to be found in first
and second SELECT statement.
21. What is Self Join and why is it required?
A table can be joined to itself in a self-join. Use a self-join when you want to create a result set
that joins records in a table with other records in the same table. To list a table two times in the
same query, you must provide a table alias for at least one of instance of the table name.
Syntax:
The basic syntax of SELF JOIN is as follows:
SELECT a.column_name,b.column_name...
FROM table1 a, table1 b
WHERE a.common_field=b.common_field;
Here, WHERE clause could be any given expression based on your requirement.
Example:
Consider the following two tables, (a) CUSTOMERS table is as follows:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
|1|Ramesh|32|Ahmedabad|2000.00|
|2|Khilan|25|Delhi|1500.00|
|3|kaushik|23|Kota|2000.00|
|4|Chaitali|25|Mumbai|6500.00|
|5|Hardik|27|Bhopal|8500.00|
|6|Komal|22| MP |4500.00|
|7|Muffy|24|Indore|10000.00|
+----+----------+-----+-----------+----------+
Now, let us join this table using SELF JOIN as follows:
SQL>SELECT a.ID, b.NAME,a.SALARY
FROM CUSTOMERS a, CUSTOMERS b
WHERE a.SALARY<b.SALARY;
This would produce the following result:
+----+----------+---------+
| ID | NAME |SALARY |
+----+----------+---------+
|2|Ramesh|1500.00|
|2|kaushik|1500.00|
|1|Chaitali|2000.00|
|2|Chaitali|1500.00|
|3|Chaitali|2000.00|
|6|Chaitali|4500.00|
|1|Hardik|2000.00|
|2|Hardik|1500.00|
|3|Hardik|2000.00|
|4|Hardik|6500.00|
|6|Hardik|4500.00|
|1|Komal|2000.00|
|2|Komal|1500.00|
|3|Komal|2000.00|
|1|Muffy|2000.00|
|2|Muffy|1500.00|
|3|Muffy|2000.00|
|4|Muffy|6500.00|
|5|Muffy|8500.00|
|6|Muffy|4500.00|
+----+----------+---------+


22. How to generate row number in SQL Without ROWNUM?
Select Empname, EmpId,
(Select Count(*) from Emp emp1 where emp1.EmpId< emp2.EmpId ) AS Rownumber from
Emp emp2
where Empname is not null
order by Empname

23. How can we transpose a table using SQL (changing rows to column or vice-versa) ?


24. How to select first 5 records from a table?
SELECT *
FROM (your ordered query) alias_name
WHERE rownum<= Rows_to_return
ORDER BY rownum;
For example, if you wanted to retrieve the first 3 records from the suppliers table, sorted by
supplier_name in ascending order, you would run the following query:
SELECT *
FROM (select * from suppliers ORDER BY supplier_name) suppliers2
WHERE rownum<= 5
ORDER BY rownum;

25. How to display the 3rd highest salary in the employee table?
Select * from emp e where 2=(select count(*) from emp where sal>e.sal

26. How to display the employee who joined after 15 th of any month?
selectename from emp where to_char(hiredate,'DD')<15;

27. What is major difference between sql and plsql?
1.) SQL is a data oriented language for selecting and manipulating sets of data. PL/SQL is a
procedural language to create applications.

2.) PL/SQL can be the application language just like Java or PHP can. PL/SQL might be the
language we use to build, format and display those screens, web pages and reports.SQL may be
the source of data for our screens, web pages and reports.

3.) SQL is executed one statement at a time. PL/SQL is executed as a block of code.

4.) SQL tells the database what to do (declarative), not how to do it. In contrast, PL/SQL tell
the database how to do things (procedural).

5.) SQL is used to code queries, DML and DDL statements. PL/SQL is used to code program
blocks, triggers, functions, procedures and packages.

6.) We can embed SQL in a PL/SQL program, but we cannot embed PL/SQL within a SQL
statement.

7.) SQL is a language that is used by relational database technologies such as Oracle, Microsoft
Access, and Sybase etc., PL/SQL is commonly used to write data-centric programs to manipulate
data in an Oracle database. PL/SQL language includes object oriented programming techniques
such as encapsulation, function overloading, and information hiding (all but inheritance).

28. What is the use of the group by clause and having clause and with clause ?
The GROUP BY statement is used in conjunction with the aggregate functions to group the
result-set by one or more columns.
SQL GROUP BY Syntax
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;
The HAVING clause was added to SQL because the WHERE keyword could not be used with
aggregate functions.
SQL HAVING Syntax
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value;
WITH Clause:
The WITH clause, or subquery factoring clause, is part of the SQL-99 standard and was added
into the Oracle SQL syntax in Oracle 9.2. The WITH clause may be processed as an inline view
or resolved as a temporary table. The advantage of the latter is that repeated references to the
subquery may be more efficient as the data is easily retrieved from the temporary table, rather
than being requeried by each reference. You should access the performance implications of
the WITH clause on a case-by-case basis.
This article shows how the WITH clause can be used to reduce repetition and simplify complex
SQL statements. I'm not suggesting the following queries are the best way to retrieve the
required information. They merely demonstrate the use of the WITH clause.
Using the SCOTT schema, for each employee we want to know how many other people are in
their department. Using an inline view we might do the following.
SELECT e.ename AS employee_name,
dc.dept_count AS emp_dept_count
FROM emp e,
(SELECT deptno, COUNT(*) AS dept_count
FROM emp
GROUP BY deptno) dc
WHERE e.deptno = dc.deptno;
Using a WITH clause this would look like the following.
WITH dept_count AS (
SELECT deptno, COUNT(*) AS dept_count
FROM emp
GROUP BY deptno)
SELECT e.ename AS employee_name,
dc.dept_count AS emp_dept_count
FROM emp e,
dept_count dc
WHERE e.deptno = dc.deptno;
The difference seems rather insignificant here.
What if we also want to pull back each employees manager name and the number of people in
the managers department? Using the inline view it now looks like this.
SELECT e.ename AS employee_name,
dc1.dept_count AS emp_dept_count,
m.ename AS manager_name,
dc2.dept_count AS mgr_dept_count
FROM emp e,
(SELECT deptno, COUNT(*) AS dept_count
FROM emp
GROUP BY deptno) dc1,
emp m,
(SELECT deptno, COUNT(*) AS dept_count
FROM emp
GROUP BY deptno) dc2
WHERE e.deptno = dc1.deptno
AND e.mgr = m.empno
AND m.deptno = dc2.deptno;
Using the WITH clause this would look like the following.
WITH dept_count AS (
SELECT deptno, COUNT(*) AS dept_count
FROM emp
GROUP BY deptno)
SELECT e.ename AS employee_name,
dc1.dept_count AS emp_dept_count,
m.ename AS manager_name,
dc2.dept_count AS mgr_dept_count
FROM emp e,
dept_count dc1,
emp m,
dept_count dc2
WHERE e.deptno = dc1.deptno
AND e.mgr = m.empno
AND m.deptno = dc2.deptno;
So we don't need to redefine the same subquery multiple times. Instead we just use the query
name defined in the WITH clause, making the query much easier to read.
29. Diff between Rownumvsrowid?
Rownum is just the serial No of your output while Rowid is automatically generated unique id of
a row an it is generated at the time of insertion of row.
Rownum is numeric and rowid is 16 bit hexadecimal no.

30. What is the difference between ROWNUM pseudo column and ROW_NUMBER() function?

ROWNUM is a "pseudocolumn" that assigns a number to each row returned by a query:
SQL>selectrownum, ename, deptno
2fromemp;

ROWNUM ENAME DEPTNO
---------- ---------- ----------
1 SMITH 99
2 ALLEN 30
3 WARD 30
4 JONES 20
5 MARTIN 30
6 BLAKE 30
7 CLARK 10
8 SCOTT 20
9 KING 10
10 TURNER 30
11 FORD 20
12 MILLER 10
ROW_NUMBER is an analytic function that assigns a number to each row according to its
ordering within a group of rows:
SQL>selectename, deptno, row_number() over (partitionbydeptnoorderbyename) rn
2fromemp;

ENAME DEPTNO RN
---------- ---------- ----------
CLARK 101
KING 102
MILLER 103
FORD 201
JONES 202
SCOTT 203
ALLEN 301
BLAKE 302
MARTIN 303
TURNER 304
WARD 305
SMITH 991



31. What are the differences among ROWNUM, RANK and DENSE_RANK?
Row_number function returns a unique value, when confronted with the same data, ranked
according to the record in the order of the records in ascending order.
-----------
RANK gives you the ranking within your ordered partition. Ties are assigned the same rank,
with the next ranking(s) skipped. So, if you have 3 items at rank 2, the next rank listed would be
ranked 5.

DENSE_RANK again gives you the ranking within your ordered partition, but the ranks are
consecutive. No ranks are skipped if there are ranks with multiple items.

32. Pseudo columns?
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.

33. SQL Query to find Max Salary from each department.
SELECT DeptID, MAX(Salary) FROM EmpDetails GROUP BY DeptID

34. Lag vs lead functions?
LAG and LEAD provide a comparison between 2 rows in a table without requiring a self join.

LAG() provides access to a prior row
LEAD() provides access to a row after the current position


35. What are analytical functions?
Analytic functions compute an aggregate value based on a group of rows. They differ from
aggregate functions in that they return multiple rows for each group. The group of rows is called
a window and is defined by the analytic_clause.

36. How to delete duplicate values in table?
delete from <table_name> where rowid not in
( select min(rowid)
fromexp group by column1..,column2,...column3..);


37. What are the conversion functions?
The CONVERT() function is a general function that converts an expression of one data type to
another.
The CONVERT() function can be used to display date/time data in different formats.

Syntax
CONVERT(data_type(length),expression,style)

38. IN vs EXISTS operators..give me one scenario?
IN:
This will gives the output based on the column and its list of values specified.
(select * from nani where nno in (12,13);)
Syntax:
select * from <table_name> where <col> in ( value1, value2, value3 valuen);
Ex:
SQL>select * from student where no in (1, 2, 3);
NO NAME MARKS
--- ------- ---------
1 Sudha 100
2 Saketh 200
1 Jagan 300
2 Naren 400
3 Ramesh


EXISTS
Exists function is a test for existence. This is a logical test for the return of rows from a
query.
Ex:
Suppose we want to display the department numbers which has more than 4
employees.
SQL>select deptno,count(empno) from emp group by deptno having count(empno) > 4;
DEPTNO COUNT(*)
--------- ----------
20 5
30 6
From the above query can you want to display the names of employees?
SQL>select deptno,ename, count(*) from emp group by deptno,ename having count(*)
> 4;
no rows selected
The above query returns nothing because combination of deptno and ename never
return more than one count.
The solution is to use exists which follows.selectdeptno,ename from emp e1 where exists
(select * from emp e2
where e1.deptno=e2.deptno group by e2.deptno having count(e2.ename) > 4)
order by deptno,ename;
DEPTNO ENAME
20 ADAMS
20 FORD
20 JONES
20 SCOTT
20 SMITH
30 ALLEN
30 BLAKE
30 JAMES
30 MARTIN
30 TURNER
30 WARD

39. How to display the column count?
select count(*)
fromuser_tab_columns
wheretable_name='MYTABLE'


40. What is difference between CEIL and FLOOR?

CEIL
This will produce a whole number that is greater than or equal to the specified value.
Syntax: ceil (value)
Ex:
SQL>select ceil(5), ceil(5.1), ceil(-5), ceil( -5.1), ceil(0), ceil(null) from dual;
CEIL(5) CEIL(5.1) CEIL(-5) CEIL(-5.1) CEIL(0) CEIL(NULL)
--------- ----------- ---------- ------------ -------- --------------
5 6 -5 -5 0

FLOOR
This will produce a whole number that is less than or equal to the specified value.
Syntax: floor (value)
Ex:
SQL>select floor(5), floor(5.1), floor(-5), floor( -5.1), floor(0), floor(null) from
dual;

41. What is difference between BTREE INDEX and BINARY INDEX?
1. B-tree Index has low cardinality values,where as Bitmap Index has High Cardinality values.
2. B-tree Index is userful for OLTP,where as Bitmap Index is useful for Dataware Housing.
3. B-tree index updates on key values has relatively inexpensive , where as Bitmap index has
more expensive.

42. Difference between where clause and having clause?
Though the HAVING clause specifies a condition that is similar to the purpose of
a WHERE clause, the two clauses are not interchangeable. Listed below are some differences to
help distinguish between the two:
1. The WHERE clause specifies the criteria which individual records must meet to be
selcted by a query. It can be used without the GROUP BY clause. TheHAVING clause
cannot be used without the GROUP BY clause.
2. The WHERE clause selects rows before grouping. The HAVING clause selects
rows after grouping.
3. The WHERE clause cannot contain aggregate functions.
The HAVING clause can contain aggregate functions.
43. Difference between sub query and correlated subquery?
CORRELATED SUBQUERIES: Is evaluated for each row processed by the Main query.
Execute the Inner query based on the value fetched by the Outer query. Continues till all the
values returned by the main query are matched. The INNER Query is driven by the OUTER
Query
EX: SELECT empno,fname,sal,deptid FROM emp
e WHERE sal=(SELECT AVG(sal) FROM empWHERE deptid=e.deptid)
The Correlated subquery specifically computes the avg (sal) for each department.
SUBQUERY: Runs first,executedonce,returns values to be used by the MAIN Query. The
OUTER Query is driven by the INNER QUERY




44. What is the difference between CUBE and ROLLUP operators
CUBE generates a result set that represents aggregates for all combinations of values in the
selected columns.
ROLLUP generates a result set that represents aggregates for a hierarchy of values in the
selected columns.
Difference between CUBE and ROLLUP:
CUBE ROLLUP
Its an additional switch to GROUP BY
clause. It can be applied to all
aggregation functions to return cross
tabular result sets.
Its an extension to GROUP BY clause. Its used to
extract statistical and summarized information from
result sets. It creates groupings and then applies
aggregation functions on them.
Produces all possible combinations of
subtotals specified in GROUP BY
clause and a Grand Total.
Produces only some possible subtotal combinations.

45. What is MERG ? Give me syntax?
MERGE is a DML command that enables us to optionally update or insert data into a target
table, depending on whether matching records already exist.
The syntax of the MERGE statement is:
MERGE [hint] INTO [schema .]table [t_alias]
USING [[schema .]table | view | subquery] t_alias
ON ( condition ) [merge_update_clause | merge_insert_clause]

merge_update_clause:
WHEN MATCHED THEN UPDATE SET [<column> =
[<expr>|DEFAULT][,]]<where_clause>
DELETE <where_clause>

merge_insert_clause:
WHEN NOT MATCHED THEN INSERT ( <column> [,])
VALUES (<expr>|DEFAULT[,])
<where_clause>

46. Tell me something about synonyms?
synonyms--is the another name given to DB object.
used to hide the indentity of the object

47. What is the difference between primary key and forigen key?
Primary Key:
Primary key uniquely identify a record in the table.
Primary Key can't accept null values.
By default, Primary key is clustered index and data in the database table is physically organized
in the sequence of clustered index.
We can have only one Primary key in a table.
Foreign Key:
Foreign key is a field in the table that is primary key in another table.
Foreign key can accept multiple null value.
Foreign key do not automatically create an index, clustered or non-clustered. You can manually
create an index on foreign key.
We can have more than one foreign key in a table.


48. What is collesce and nullif, nvl and nvl2 function?
BASE TABLE:
SQL> SELECT * FROM null_test_tab ORDER BY id;

ID COL1 COL2 COL3 COL4
---------- ---------- ---------- ---------- ----------
1 ONE TWO THREE FOUR
2 TWO THREE FOUR
3 THREE FOUR
4 THREE THREE
NVL
The NVL function allows you to replace null values with a default value. If the value in the first
parameter is null, the function returns the value in the second parameter. If the first parameter is
any value other than null, it is returned unchanged.
We know that COL1 in the test table contains null in all rows except the first. Using
the NVL function we replace the null values with 'ZERO'.
SQL> SELECT id, NVL(col1, 'ZERO') AS output FROM null_test_tab ORDER BY id;

ID OUTPUT
---------- ----------
1 ONE
2 ZERO
3 ZERO
4 ZERO

4 rows selected.

SQL>
DECODE
The DECODE function is not specifically for handling null values, but it can be used in a similar
way to the NVL function, as shown by the following example.
SQL> SELECT id, DECODE(col1, NULL, 'ZERO', col1) AS output FROM null_test_tab
ORDER BY id;

ID OUTPUT
---------- ----------
1 ONE
2 ZERO
3 ZERO
4 ZERO

4 rows selected.

SQL>
NVL2
The NVL2 function accepts three parameters. If the first parameter value is not null it returns the
value in the second parameter. If the first parameter value is null, it returns the third parameter.
The following query shows NVL2 in action.
SQL> SELECT id, NVL2(col1, col2, col3) AS output FROM null_test_tab ORDER BY id;

ID OUTPUT
---------- ----------
1 TWO
2 THREE
3 THREE
4 THREE

4 rows selected.

SQL>
The first row in the test table has a not null value in COL1, so the value of COL2 is returned. All
other rows contains null in COL1, so the value of COL3 is returned.
COALESCE
The COALESCE function was introduced in Oracle 9i. It accepts two or more parameters and
returns the first non-null value in a list. If all parameters contain null values, it returns null.
SQL> SELECT id, COALESCE(col1, col2, col3) AS output FROM null_test_tab ORDER BY
id;

ID OUTPUT
---------- ----------
1 ONE
2 TWO
3 THREE
4 THREE

4 rows selected.

SQL>
NULLIF
The NULLIF function was introduced in Oracle 9i. It accepts two parameters and returns null if
both parameters are equal. If they are not equal, the first parameter value is returned.
In our test table the values of COL3 and COL4 are equal in row 4, so we would only expect null
returned for that row using the following query.
SQL> SELECT id, NULLIF(col3, col4) AS output FROM null_test_tab ORDER BY id;

ID OUTPUT
---------- ----------
1 THREE
2 THREE
3 THREE
4

4 rows selected.

SQL>


49. How to get last day of the month?
SELECT LAST_DAY(to_date('04/04/1924','MM/DD/YYYY')) from dual;

SELECT LAST_DAY(ADD_MONTHS(to_date('04/04/1924','MM/DD/YYYY'), -1)) from dual;

SELECT LAST_DAY(ADD_MONTHS(to_date('04/04/1924','MM/DD/YYYY'), -2)) from dual;

50. Primary key vs unique?
UNIQUE
This is used to avoid duplicates but it allow nulls.
We can add this constraint in all three levels.
Ex:
COLUMN LEVEL
SQL>create table student(no number(2) unique, name varchar(10), marks
number(3));
SQL>create table student(no number(2) constraint un unique, name varchar(10),
marks number(3));
TABLE LEVEL
SQL>create table student(no number(2) , name varchar(10), marks number(3),
unique(no));
SQL>create table student(no number(2) , name varchar(10), marks number(3),
constraint un unique(no));

PRIMARY KEY
This is used to avoid duplicates and nulls. This will work as combination of unique and
not null.
Primary key always attached to the parent table.
We can add this constraint in all three levels.

Ex:
COLUMN LEVEL
SQL>create table student(no number(2) primary key, name varchar(10), marks
number(3));
SQL>create table student(no number(2) constraint pk primary key, name varchar(10),
marks number(3));
TABLE LEVEL
SQL>create table student(no number(2) , name varchar(10), marks number(3),
primary key(no));
SQL>create table student(no number(2) , name varchar(10), marks number(3),
constraintpk primary key(no));


51. What is view? Tell me different views?
view is a logical representation of data from one or more than one table.
It is We can create obj in the table and can use of own reqd query for that view w/o disturb the
main table
They are different types
Simple views
Complex views
Read only views
With check option views
Materialized views

52. What is materialized view and difference between view and mview?
Materialized views will help improving the performance of select statement on view.To create
materialized view, the based table should have primary key.Changes to base table will not reflect
on materialized view.
difference
- A materialized view contains a separate copy of the data. A normal view is just a stored query
that is always executed at runtime.

- A materialized view, depending on the system, may be stale, that is, the data in the materialized
view may not match the latest changes in the base tables. A view is just a stored query that is
executed at runtime, so the results of querying the view will always match querying the table.

- A materialized view may be used by the optimizer as a way of pre-aggregating certain
interesting data sets in order to more efficiently answer business questions. A view is just a
stored query that is executed at runtime.

53. What is inline view ?have you ever used?
In the select statement instead of table name, replacing the select statement is known as
inline view.
Ex:
SQL>Select ename, sal, rownum rank from (select * from emp order by sal);

54. if a string is there like s1,s2,s3,s4.How to find count of commas in this.
Select length(s1,s2,s3,s4) length(replace(s1,s2,s3,s4,,) from dual

55. write sub query for eliminating duplicate rows using analytical function?
Delete from emp where rowed not in(select min(rowid) from emp group by sno)

56. How to retrieve a second highest salary from a table? Note:Suppose salaries are in duplicate
values
eg: Name Sal Malli 60000 Pandi 60000 Rudra 45000 Ravi 45000.

Select max(sal) from emp e where 2=(select distinct count(sal) from emp d where
d.sal>e.sal)

57. Differences between Oracle 9i and 10g (Probably in terms of SQL and PL/SQL)?


58. In a table have one column primary key..it will not allows null values and duplicate
values..instead of primary key why cant we use unique and not null.these two also doesnt accept
null values in not null and unique doesnt accept duplicate values? so what is the difeerence
between(unique,not null) and primary key?

A primary key is a unique field on a table but it is special in that the table considers that row its
key. That means that other tables can use this field to create foreign key relationships to
themselves.
A unique constraint simply means that a particular field must be unique.

59. What is save point and commit?
You can use the COMMIT, ROLLBACK, SAVEPOINT, and SET TRANSACTION command
to control the transaction.
1. COMMIT : COMMIT command to make changes permanent save to a database during
the current transaction.
2. ROLLBACK : ROLLBACK command execute at the end of current transaction and
undo/undone any changes made since the begin transaction.
3. SAVEPOINT : SAVEPOINT command save the current point with the unique name in
the processing of a transaction.
4. AUTOCOMMIT : Set AUTOCOMMIT ON to execute COMMIT Statement
automatically.
5. SET TRANSACTION : PL/SQL SET TRANSACTION command set the transaction
properties such as read-write/read only access.

60. What is the global temporary tables?
These tables do not reside in the system catalogs and are not persistent. Temporary tables exist
only during the connection that declared them and cannot be referenced outside of that
connection. When the connection closes, the rows of the table are deleted, and the in-memory
description of the temporary table is dropped.
Temporary tables are useful when:
The table structure is not known before using an application.
Other users do not need the same table structure.
Data in the temporary table is needed while using the application.
The table can be declared and dropped without holding the locks on the system catalog.
The data in a global temporary table is private, such that data inserted by a session can only be
accessed by that session. The session-specific rows in a global temporary table can be preserved
for the whole session, or just for the current transaction. The ON COMMIT DELETE ROWS
clause indicates that the data should be deleted at the end of the transaction.
Syntax
DECLARE GLOBAL TEMPORARY TABLE table-Name
{ column-definition [ , column-definition ] * }
[ ON COMMIT {DELETE | PRESERVE} ROWS ]
NOT LOGGED [ON ROLLBACK DELETE ROWS]


61. What is index organized table?
An index-organized table (IOT) is a type of table that stores data in a B*Tree index structure.
Normal relational tables, called heap-organized tables, store rows in any order (unsorted). In
contrast to this, index-organized tables store rows in a B-tree index structure that is logically
sorted in primary key order.

62. How many triggers can be applied to a table?
Insert/Update/Delete :- 3
Before/After:- 2
Row Level/Statement Level:-2

Hence 3*2*2

63. If a cursor is open, how can we find in a PL/SQL Block?
We can use %ISOPEN clause, a keyword provided by oracle to check whether the cursor is in
open state.
e.g
Declare
...
cursor c1 is select emp_name from emp;
Begin
if c1%ISOPEN then
...
End;


64. 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 differenttable or views and
variables. E.g. TYPE r_emp is RECORD (enoemp.empno% type,enameempename
%type); e_recemp% ROWTYPE cursor c1 is select empno,deptno from emp; e_rec c1
%ROWTYPE.


65. Differ between DECODE and CASE.
Decode: column wise execution.
Case: rowwise execution.
Difference between DECODE and CASE:
Everything DECODE can do, CASE can. There is a lot more that you can do with CASE, though
, which DECODE cannot. Following is the list of differences -
1. DECODE can work with only scaler values but CASE can work with logical oprators, predicat
es and searchable subqueries.
2. CASE can work as a PL/SQL construct but DECODE is used only in SQL statement.CASE ca
n be used as parameter of a function/procedure.
3. CASE expects datatype consistency, DECODE does not.
4. CASE complies with ANSI SQL. DECODE is proprietary to Oracle.
5. CASE executes faster in the optimizer than does DECODE.
6. CASE is a statement while DECODE is a function. Read more at: http://www.queryhome.com
/32211/what-the-difference-between-decode-and-case-statement-oracle

66. Explain polymorphism in PL/SQL.
Polymorphism is a feature of object-oriented programming, is the ability to create a variable, a
function, or an object that has more than one form.

67. What is pragma? types in pragma?
Pragma is a keyword in oracle pl/sql.That is used to provide an instruction to compiler.
Pragama is compiler directive .

Example of Autonomous transactions

Suppose you are updating value from table and you don't have update trigger on that table

but still you want to maintain a log entry for this update in separate table.

You can write a procedure and call that procedure to do this . But you can not use "COMMIT" in
this called procedure because it will save the entire transaction.

To avoid this you can declare this procedure as autonomous transaction procedure so that the
execution of this procedure will be treated as totally diff. transaction and you can issue commit
in called procedure without affecting the main transaction.

Different types of Pragama are

* EXCEPTION_INIT
* RESTRICT_REFERENCES
* SERIALLY_REUSABLE



68. What is difference between procedure and trigger ?
Both are database objects containing blocks lof code that can be used for implementing business
logic

The differences are:

1)Triggers fire automatically but they need events for that.
(Example: create,alter,drop,insert,delete,update)
Procedures have to be explicitly called and then executed.
They do not need create,alter,drop,insert,delete,update.
we can also execute procedures automatically using the sp_procoption.

2))we cannot pass parameters inside the triggers,
but we can pass parameters inside stored procedures
-------------------
example: if we want to display a message "error"

using a trigger: we need some DDL/DML Statement
using a procedure: NO DDL/DML is needed

69. What is mutating error ..how to avoid it.
Mutating error normally occurs when we are performing some DML operations and we are
trying to select the affected record from the same trigger. So basically we are trying to select
records in the trigger from the table that owns the trigger. This creates inconsistency and Oracle
throws a mutating error.

http://decipherinfosys.wordpress.com/2009/06/22/mutating-tabletrigger-error-and-how-to-
resolve-it/

70. What is dynamic sql?
Dynamic SQL is a SQL statement that is constructed and executed at program execution time.
In contrast to this, static SQL statements are hard-coded in the program and executed "as-is" at
run-time. Dynamic SQL provides more flexibility, nevertheless, static SQL is faster and more
secure than dynamic SQL.

71. Tell me everything about cursors?
Cursor is a pointer to memory location which is called as context area which contains the
information necessary for processing, including the number of rows processed by the
statement, a pointer to the parsed representation of the statement, and the active set which
is the set of rows returned by the query.
Cursor contains two parts
Header
Body

Header includes cursor name, any parameters and the type of data being loaded.
Body includes the select statement.
Ex:
Cursor c(dno in number) return dept%rowtype is select *from dept;
In the above
Header cursor c(dno in number) return dept%rowtype
Body select *from dept
CURSOR TYPES
Implicit (SQL)
Explicit
Parameterized cursors
REF cursors

CURSOR STAGES
Open
Fetch
Close

CURSOR ATTRIBUTES
%found
%notfound
%rowcount
%isopen
%bulk_rowcount
%bulk_exceptions

CURSOR DECLERATION
Syntax:
Cursor <cursor_name> is select statement;
Ex:
Cursor c is select *from dept;

72. Can you tell me about exceptions?
PL/SQL provides a feature to handle the Exceptions which occur in a PL/SQL Block known as
exception Handling. Using Exception Handling we can test the code and avoid it from exiting
abruptly.
When an exception occurs a messages which explains its cause is recieved.
PL/SQL Exception message consists of three parts.
1) Type of Exception
2) An Error Code
3) A message
There are 3 types of Exceptions.
a) Named System Exceptions
`b) Unnamed System Exceptions
c) User-defined Exceptions


73. What are advantages of packages?
Modularity,Easier Application Design,InformationHiding,AddedFunctionality,Better
Performance

74. What is difference between cursor and ref cursor?
REF cursor is typically used to return record set or a cursor from stored procedure. REF Cursor
is basically a data type. It is normally declared as type r_cursor is REF CURSOR; REF cursor
supports dynamic change of query.
Normal cursor is a static cursor in which the query is assigned at design time and cant be
changed at run time.
75. What is advantage of procedure and function?

76. What is difference between procedure v/s package?
Package-->It stores and compiles all the functions and procedures declared in SGA(System
Global Area).Whenever stored procedures or functions are called from this package,it will get
them from SGA.So it perfomance is definetly high.


Procedures-->They are subprograms which perform certain action.They cannot be called from
select statement.

Package is faster when you working on specific project and all your functions and procedure are
in that package.
because package load into memory and remain in memory till the place available so execution is
fast.
for calling realted procedure, function and global variable.

but if you have a small and misc work. then you should use single function or procedure
it will take a small memory and load fast

77. What are the collection types please brief?
A collection is an ordered group of elements, all of the same type. It is a general concept that
encompasses lists, arrays, and other datatypes used in classic programming algorithms. Each
element is addressed by a unique subscript.
PL/SQL offers these collection types:
Associative arrays, also known as index-by tables, let you look up elements using
arbitrary numbers and strings for subscript values. (They are similar to hash tables in
other programming languages.)
Nested tables hold an arbitrary number of elements. They use sequential numbers as
subscripts. You can define equivalent SQL types, allowing nested tables to be stored in
database tables and manipulated through SQL.
Varrays (short for variable-size arrays) hold a fixed number of elements (although you
can change the number of elements at runtime). They use sequential numbers as
subscripts. You can define equivalent SQL types, allowing varrays to be stored in
database tables. They can be stored and retrieved through SQL, but with less flexibility
than nested tables.
78. What is SQLCODE and SQLERRM?
SQL CODE Function:
The function SQLCODE returns the number code of the most recent exception.
SQL ERRM Function:
The function SQLERRM returns the error message associated with its error-number argument. If
the argument is omitted, it returns the error message associated with the current value
of SQLCODE. SQLERRM with no argument is useful only in an exception handler. Outside a
handler, SQLERRM with no argument always returns the normal, successful
completion message. For internal exceptions, SQLERRM returns the message associated with
the Oracle error that occurred. The message begins with the Oracle error code.
Example:
DECLARE
nameemployees.last_name%TYPE;
v_code NUMBER;
v_errmVARCHAR2(64);
BEGIN
SELECT last_name INTO name FROM employees WHERE employee_id = 1000;
EXCEPTION
WHEN OTHERS THEN
v_code := SQLCODE;
v_errm := SUBSTR(SQLERRM, 1 , 64);
DBMS_OUTPUT.PUT_LINE('The error code is ' || v_code || '- ' || v_errm);
END;

79. What is exception? Tell me some seeded exceptions?
An error condition during a program execution is called an exception in PL/SQL. PL/SQL
supports programmers to catch such conditions using EXCEPTION block in the program and an
appropriate action is taken against the error condition. There are two types of exceptions:
System-defined exceptions
User-defined exceptions
80. What are the conditional statements?
IF THEN ELSE STATEMENT

1)
IF condition
THEN
statement 1;
ELSE
statement 2;
END IF;

81. What is NOCOPY? And where we can use this?
NOCOPY will instruct Oracle to pass the argument as fast as possible. This can significantly
enhance performance when passing a large value.

82. What is difference between raise and raise application error
Raise command is used for raise an user defined exception.

Raise_application_error is a procedrue in dbms_standardpackage..It will raise the user defined
error message and error number.

Error number range will be from -20000 to -20999. Error msg length can be 2048 bytes..(new
versions may be more than this).

example
*******

create or replace trigger dummy before insert on emp for each row

begin

If :new.sal>5000 then
raise_application_error(-20115,' sorry invalid salary');
end if;
end;


example for Raise
***************
declare

sample exception;

begin

if a > b then

raise sample;

end if;

exception

when sample then

do something...

end;

83. What are formal and actual parameters?
Actual Parameters : Subprograms pass information using parameters. The variables or
expressions referenced in the parameter list of a subprogram call are actual parameters. For
example, the following procedure call lists two actual parameters named emp_num and amount:
Eg. raise_salary(emp_num, amount);
Formal Parameters : The variables declared in a subprogram specification and referenced in the
subprogram body are formal parameters. For example, the following procedure declares two
formal parameters named emp_id and increase: Eg. PROCEDURE raise_salary (emp_id
INTEGER, increase REAL) IS current_salary REAL;

84. Difference between nested tables and varrays?
Nested Table Collections:

Nested table collections are an extension of the index-by tables. The main difference between the
two is that nested tables can be stored in a database column but index-by tables cannot. In
addition some DML operations are possible on nested tables when they are stored in the
database. During creation the collection must be dense, having consecutive subscripts for the
elements. Once created elements can be deleted using the DELETE method to make the
collection sparse. The NEXT method overcomes the problems of traversing sparse collections.

Varray Collections:

A VARRAY is similar to a nested table except you must specifiy an upper bound in the
declaration. Like nested tables they can be stored in the database, but unlike nested tables
individual elements cannot be deleted so they remain dense.

85. What is bulk collect and give me syntax?
Bulk binds can improve the performance when loading collections from a queries. The BULK
COLLECT INTO construct binds the output of the query to the collection. To test this create the
following table.
Example:
PROCEDURE process_all_rows
IS
TYPE employees_aat
IS TABLE OF employees%ROWTYPE
INDEX BY PLS_INTEGER;
l_employeesemployees_aat;
BEGIN
SELECT *
BULK COLLECT INTO l_employees
FROM employees;

FOR indx IN 1 ..l_employees.COUNT
LOOP
analyze_compensation
(l_employees(indx));
END LOOP;
END process_all_rows;

86. What is weak and strong refcursor and give example?
Ref cursor is a cursor variable which acts as a pointer to
the sql memory area.
Ref cursor can be asssociated with multiple sql statements
where as a cursor can be associated with only one sql
statement.
Refcursor is dynamic where as cursor is static.
Ref cursors are of two types:
1)strong ref cursor:whichretuns value.
2)week ref cursor:which doesn't return value.

For the strong ref cursor the returning columns with
datatype and length need to be known at compile time.

For the weak ref cursor the structure does not need to be
known at compile time.

TYPE WEAK_REF_CURSOR IS REF CURSOR;

TYPE STRONG-_ REF_CURSOR IS REF CURSOR RETURN
TABLE_NAME%ROWTYPE;

87. What is authidclause ?
The AUTHID clause instructs Oracle as to whether the routine is to be run with the invoker's
rights (CURRENT_USER), or with the Owner rights (DEFINER). If the clause is not specified,
Oracle will default to using the AUTHID DEFINER.

88. Where current of clause?
If you plan on updating or deleting records that have been referenced by a SELECT FOR
UPDATE statement, you can use the WHERE CURRENT OF statement.
SYNTAX
The syntax for the WHERE CURRENT OF statement in Oracle/PLSQL is either:
UPDATE table_name
SET set_clause
WHERE CURRENT OF cursor_name;
89. What is difference betweenforall loop and for loop?
FOR is an actual loop which will go through records one by one and do some processing.

FORALL is NOT an actual loop, it's just a notation for a bulk DML operation. It will NOT go
through rows one by one. For example, you can do some row processing in a FOR loop, but you
won't be able to do it in FORALL.

90. What is forward declaration and where we can use this?
PL/SQL allows for a special subprogram declaration called a
forward declaration. It consists of the subprogram
specification in the package body terminated by a semicolon.
You can use forward declarations to do the following:
? Define subprograms in logical or alphabetical order.
? Define mutually recursive subprograms.(both calling each
other).
? Group subprograms in a package

Example of forward Declaration:

CREATE OR REPLACE PACKAGE BODY forward_pack
IS
PROCEDURE calc_rating(. . .); -- forward declaration
PROCEDURE award_bonus(. . .)
IS -- subprograms defined
BEGIN -- in alphabetical order
calc_rating(. . .);
. . .
END;

PROCEDURE calc_rating(. . .)
IS
BEGIN
. . .
END;

END forward_pack;

91. What are who columns? Why we can use in the tables?
WHO columns are used to track the information updated or inserted by the users against the
tables. FND_STANDARD package is used for this purpose. FND_STANDARD.SET_WHO
Procedure is used to update the WHO columns in aTable when a DML operation s (i.e. INSERT,
UPDATE) performed.1) Created by2) Creation date3) Last _updated_by4) last_update_date5)
last_update_login

Use fnd_profile.VALUE (USER_ID) for retrieving the user_id which will be used by
created_by column.
Creation date and last_update_date will be normally SYSDATE.
last_updated_by is same as created_by.
Use USERENV (SESSIONID) for getting the last_update_login id

92. What is Exception of propagation?
A PL/SQL program is an anonymous block, a procedure, or a function. This program, or
highest-level block, can call other procedures or functions, or nest an anonymous block within
that block. So at any given point in execution, there might be several layers of PL/SQL blocks
nested within other blocks. Each PL/SQL block can have its own exception section, or it can be
totally void of exception handlers.
To determine the appropriate exception-handling behavior, PL/SQL follows rules regarding:
Scope - The PL/SQL block or blocks in which an exception can be raised and handled.
Propagation - The way in which an exception is passed back through enclosing blocks until it is
handled or is resolved to be an unhandled exception
93. How to tune oracle sql queries give me step by step?
The three basic steps of SQL tuning is listed here.
Step1: At first we need to identified the high load SQLs or top SQLs that are responsible for
performance problem or in another word the sql that consume application workload and system
resources. We can easily identify them by reviewing past SQL execution history available in the
system.
Step 2: Now generate execution plan of those high load sql statements and verify that the
execution plans produced by the query optimizer for these statements perform reasonably.

Step 3: Implement corrective actions to generate better execution plans for poorly performing
SQL statements. While taking corrective actions there is many considerations. Hopefully I will
discuss these consideration in my blogs one by another.

94. we have a package and we have grants to execute that package inside of that we have table,
here we don't have privileges to this table? whether this package will execute or not?
Yes, this package will execute.
example:- suppose we have create a package inside any user
create or replace package sn_pck is
procedure sn_pr(c out number);
end;

create or replace package body scn_pck is
procedure sn_pr(c out number) is
begin
select b into c from sn where name='sony';
DBMS_OUTPUT.PUT_LINE(C);
END;
END;

after that you shd connect hr user
and execute that package it execute 100%

how u will execute on hr user:-

declare
e number;
begin
prativa.sn_pck(e);
end;

note:- here i hv created that package in a user named prativa
and in user i hv create a table sn

95. Explain the usage of WHERE CURRENT OF clause in cursors ?
If you plan on updating or deleting records that have been referenced by a SELECT FOR
UPDATE statement, you can use the WHERE CURRENT OF statement.
SYNTAX
The syntax for the WHERE CURRENT OF statement in Oracle/PLSQL is either:
UPDATE table_name
SET set_clause
WHERE CURRENT OF cursor_name;
96. What is difference between select statement and cursor?
Normal select Query fetches all rows in one go while cursor
fetches one row at a time.

97. what is the difference between pragma exception_init and raise_application_error?
PRAGMA EXCEPTION_INIT allows to associate an Oracle error
number with the name of a user-defined error. Here you need
to defined user-defined exception before it is used in
PRAGMA EXCEPTION_INIT. There are two parameters: exception
name and error code.

RAISE_APPLICATION_ERROR allows to create meaningful error
msg.it works with un-named user defined exceptions. It
associates the number of the error with the text of the
error. Therefore, the user-defined exception does nat have a
name associated with it. There are three parameter:
err_number, err_msg, keep-err

98. what is difference between pass by value and reference by value in oracle plsql?
In parameters by default call by reference where as out and in out call by value.
corresponding formal parameter.
parameter passed by value it copies the value of the actual parameter to the formal
parameter.



99. How can we Get the Updated Rows? ie, There is 100s of Rows i updated the Rows who have
salary 5000. then i want to select the Updated Rows. How can we achieve it?

create table t1 as select * from emp where 1=2;

create or replace trigger t1
after update on emp
for eachrow
begin
insert into t1
values(empno,'ename',job,'hiredate',sal,comm,deptno);

end;
after create trigger
then u updated.

S-ar putea să vă placă și