Monday, 27 July 2015

USING clause in Oracle

The USING clause specifies which columns to test for equality when two tables are joined. It can be used instead of an ON clause in the JOIN operations that have an explicit join clause.

Syntax
USING ( Simple-column-Name [ , Simple-column-Name ]* )
The columns listed in the USING clause must be present in both of the two tables being joined. The USING clause will be transformed to an ON clause that checks for equality between the named columns in the two tables.

When a USING clause is specified, an asterisk (*) in the select list of the query will be expanded to the following list of columns (in this order):

All the columns in the USING clause
All the columns of the first (left) table that are not specified in the USING clause
All the columns of the second (right) table that are not specified in the USING clause
An asterisk qualified by a table name (for example, COUNTRIES.*) will be expanded to every column of that table that is not listed in the USING clause.

If a column in the USING clause is referenced without being qualified by a table name, the column reference points to the column in the first (left) table if the join is an INNER JOIN or a LEFT OUTER JOIN. If it is a RIGHT OUTER JOIN, unqualified references to a column in the USING clause point to the column in the second (right) table.

Examples
The following query performs an inner join between the COUNTRIES table and the CITIES table on the condition that COUNTRIES.COUNTRY is equal to CITIES.COUNTRY:

SELECT * FROM COUNTRIES JOIN CITIES
     USING (COUNTRY)
The next query is similar to the one above, but it has the additional join condition that COUNTRIES.COUNTRY_ISO_CODE is equal to CITIES.COUNTRY_ISO_CODE:

SELECT * FROM COUNTRIES JOIN CITIES
    USING (COUNTRY, COUNTRY_ISO_CODE)

Friday, 24 July 2015

Delete duplicate records in a Table

In Oracle there are many ways to delete duplicate records. Note that below example are described to just explain the different possibilities.

Consider the EMP table with below rows

create table emp(
EMPNNO  integer,
EMPNAME varchar2(20),
SALARY  number);

10    Bill    2000
11    Bill    2000
12    Mark    3000
12    Mark    3000
12    Mark    3000
13    Tom    4000
14    Tom    5000
15    Susan    5000

1. Using rowid

SQL > delete from emp
where rowid not in
(select max(rowid) from emp group by empno);

This technique can be applied to almost scenarios. Group by operation should be on the columns which identify the duplicates.

2. Using self-join

SQL > delete from emp e1
where rowid not in
(select max(rowid) from emp e2
where e1.empno = e2.empno );

3. Using row_number()

SQL > delete from emp where rowid in
(
select rid from
(
select rowid rid,
row_number() over(partition by empno order by empno) rn
from emp
)
where rn > 1
);

This is another efficient way to delete duplicates

4. Using dense_rank()

SQL > delete from emp where rowid in
(
select rid from
(
select rowid rid,
dense_rank() over(partition by empno order by rowid) rn
from emp
)
where rn > 1
);

Here you can use both rank() and dens_rank() since both will give unique records when order by rowid.

5. Using group by

Consider the EMP table with below rows

10    Bill    2000
11    Bill    2000
12    Mark    3000
13    Mark    3000

SQL > delete from emp where
(empno,empname,salary) in
(
select max(empno),empname,salary from emp
group by empname,salary
);

This technique is only applicable in few scenarios.

Always take extra caution while deleting records.

1. First identify the duplicates using select.

2. Double verify those are actual  ‘duplicates’ or not

3. Take backup if necessary

4. Apply commit only if you are sure.

Did you find above post useful ? Your comments are highly valuable.

WM_CONCAT and LISTAGG Analytic Function

LISTAGG Analytic Function in 11g Release 2

The LISTAGG analytic function was introduced in Oracle 11g Release 2, making it very easy to aggregate strings. The nice thing about this function is it also allows us to order the elements in the concatenated list. If you are using 11g Release 2 you should use this function for string aggregation.

COLUMN employees FORMAT A50

SELECT deptno, LISTAGG(ename, ',') WITHIN GROUP (ORDER BY ename) AS employees
FROM   emp
GROUP BY deptno;

    DEPTNO EMPLOYEES
---------- --------------------------------------------------
        10 CLARK,KING,MILLER
        20 ADAMS,FORD,JONES,SCOTT,SMITH
        30 ALLEN,BLAKE,JAMES,MARTIN,TURNER,WARD

3 rows selected.
WM_CONCAT Built-in Function (Not Supported)

If you are not running 11g Release 2 or above, but are running a version of the database where the WM_CONCAT function is present, then it is a zero effort solution as it performs the aggregation for you. It is actually an example of a user defined aggregate function described below, but Oracle have done all the work for you.

COLUMN employees FORMAT A50

SELECT deptno, wm_concat(ename) AS employees
FROM   emp
GROUP BY deptno;

    DEPTNO EMPLOYEES
---------- --------------------------------------------------
        10 CLARK,KING,MILLER
        20 SMITH,FORD,ADAMS,SCOTT,JONES
        30 ALLEN,BLAKE,MARTIN,TURNER,JAMES,WARD

3 rows selected.
 WM_CONCAT is an undocumented function and as such is not supported by Oracle for user applications (MOS Note ID 1336219.1). If this concerns you, use a User-Defined Aggregate Function described below.

Also, WM_CONCAT has been removed from 12c onward, so you can't pick this option.

FIRST_VALUE and LAST_VALUE Analytic Functions

This article gives an overview of the FIRST_VALUE and LAST_VALUE analytic functions.

FIRST_VALUE
LAST_VALUE
Related articles.

Analytic Functions
RANK, DENSE_RANK, FIRST and LAST Analytic Functions
LAG and LEAD Analytic Functions
LISTAGG Analystic Function in 11g Release 2
Top-N Queries
FIRST_VALUE

The FIRST_VALUE analytic function is similar to the FIRST analytic function, allowing you to return the first result from an ordered set.

SELECT empno,
       deptno,
       sal,
       FIRST_VALUE(sal) IGNORE NULLS
         OVER (PARTITION BY deptno ORDER BY sal) AS lowest_in_dept
FROM   emp;

     EMPNO     DEPTNO        SAL LOWEST_IN_DEPT
---------- ---------- ---------- --------------
      7934         10       1300           1300
      7782         10       2450           1300
      7839         10       5000           1300
      7369         20        800            800
      7876         20       1100            800
      7566         20       2975            800
      7788         20       3000            800
      7902         20       3000            800
      7900         30        950            950
      7654         30       1250            950
      7521         30       1250            950
      7844         30       1500            950
      7499         30       1600            950
      7698         30       2850            950

SQL>
The "{RESPECT | IGNORE} NULLS" clause indicates if NULLs are considered when determining results.

The windowing clause can be used to alter the window of operation. The following example uses "ROWS 1 PRECEDING" to give a result similar, but not quite the same, to a LAG of 1 row.

SELECT empno,
       deptno,
       sal,
       FIRST_VALUE(sal) IGNORE NULLS
         OVER (PARTITION BY deptno ORDER BY sal ROWS 1 PRECEDING) AS preceding_in_dept
FROM   emp;

     EMPNO     DEPTNO        SAL PRECEDING_IN_DEPT
---------- ---------- ---------- -----------------
      7934         10       1300              1300
      7782         10       2450              1300
      7839         10       5000              2450
      7369         20        800               800
      7876         20       1100               800
      7566         20       2975              1100
      7788         20       3000              2975
      7902         20       3000              3000
      7900         30        950               950
      7654         30       1250               950
      7521         30       1250              1250
      7844         30       1500              1250
      7499         30       1600              1500
      7698         30       2850              1600

SQL>
LAST_VALUE

The LAST_VALUE analytic function is similar to the LAST analytic function, allowing you to return the last result from an ordered set. Using the default windowing clause the result can be a little unexpected.

SELECT empno,
       deptno,
       sal,
       LAST_VALUE(sal) IGNORE NULLS
         OVER (PARTITION BY deptno ORDER BY sal) AS highest_in_dept
FROM   emp;

     EMPNO     DEPTNO        SAL HIGHEST_IN_DEPT
---------- ---------- ---------- ---------------
      7934         10       1300            1300
      7782         10       2450            2450
      7839         10       5000            5000
      7369         20        800             800
      7876         20       1100            1100
      7566         20       2975            2975
      7788         20       3000            3000
      7902         20       3000            3000
      7900         30        950             950
      7654         30       1250            1250
      7521         30       1250            1250
      7844         30       1500            1500
      7499         30       1600            1600
      7698         30       2850            2850

SQL>
This is because the default windowing clause is "RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW", which in this example means the first row with the same value as that of the current row will always be the last row considered. Altering the windowing clause to "RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING" gives us the result we probably expected.

SELECT empno,
       deptno,
       sal,
       LAST_VALUE(sal) IGNORE NULLS
         OVER (PARTITION BY deptno ORDER BY sal RANGE BETWEEN
           UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS highest_in_dept
FROM   emp;

     EMPNO     DEPTNO        SAL HIGHEST_IN_DEPT
---------- ---------- ---------- ---------------
      7934         10       1300            5000
      7782         10       2450            5000
      7839         10       5000            5000
      7369         20        800            3000
      7876         20       1100            3000
      7566         20       2975            3000
      7788         20       3000            3000
      7902         20       3000            3000
      7900         30        950            2850
      7654         30       1250            2850
      7521         30       1250            2850
      7844         30       1500            2850
      7499         30       1600            2850
      7698         30       2850            2850

SQL>
As with the previous function, the "{RESPECT | IGNORE} NULLS" clause indicates if NULLs are considered when determining results. The default action is RESPECT NULLS.

For more information see:

Analytic Functions
RANK, DENSE_RANK, FIRST and LAST Analytic Functions
LAG and LEAD Analytic Functions
LISTAGG Analystic Function in 11g Release 2
Top-N Queries
Analytic Functions (Docs)
FIRST_VALUE
LAST_VALUE

Find Nth Highest Salary in Employee Table

Suppose that you are given the following simple database table called Employee that has 2 columns named Employee ID and Salary:

Employee
Employee ID Salary
3 200
4 800
7 450
Write a SQL query to get the second highest salary from the table above. Also write a query to find the nth highest salary in SQL, where n can be any number.

The easiest way to start with a problem like this is to ask yourself a simpler question first. So, let’s ask ourselves how can we find the highest salary in a table? Well, you probably know that is actually really easy – we can just use the MAX aggregate function:

select MAX(Salary) from Employee;
Remember that SQL is based on set theory

You should remember that SQL uses sets as the foundation for most of its queries. So, the question is how can we use set theory to find the 2nd highest salary in the table above? Think about it on your own for a bit – even if you do not remember much about sets, the answer is very easy to understand and something that you might be able to come up with on your own.

Figuring out the answer to find the 2nd highest salary



What if we try to exclude the highest salary value from the result set returned by the SQL that we run? If we remove the highest salary from a group of salary values, then we will have a new group of values whose highest salary is actually the 2nd highest in the original Employee table.

So, if we can somehow select the highest value from a result set that excludes the highest value, then we would actually be selecting the 2nd highest salary value. Think about that carefully and see if you can come up with the actual SQL yourself before you read the answer that we provide below. Here is a small hint to help you get started: you will have to use the “NOT IN” SQL operator.


Solution to finding the 2nd highest salary in SQL

Now, here is what the SQL will look like:

SELECT MAX(Salary) FROM Employee
WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee )
Running the SQL above would return us “450”, which is of course the 2nd highest salary in the Employee table.

Subscribe to our newsletter for more free interview questions.

An explanation of the solution

The SQL above first finds the highest salary value in the Employee table using “(select MAX(Salary) from Employee)”. Then, adding the “WHERE Salary NOT IN” in front basically creates a new set of Salary values that does not include the highest Salary value. For instance, if the highest salary in the Employee table is 200,000 then that value will be excluded from the results using the “NOT IN” operator, and all values except for 200,000 will be retained in the results.

This now means that the highest value in this new result set will actually be the 2nd highest value in the Employee table. So, we then select the max Salary from the new result set, and that gives us 2nd highest Salary in the Employee table. And that is how the query above works.

An alternative solution using the not equals SQL operator

We can actually use the not equals operator – the “<>” – instead of the NOT IN operator as an alternative solution to this problem. This is what the SQL would look like:

select MAX(Salary) from Employee
WHERE Salary <> (select MAX(Salary) from Employee )
How would you write a SQL query to find the Nth highest salary?

What we did above was write a query to find the 2nd highest Salary value in the Employee table. But, another commonly asked interview question is how can we use SQL to find the Nth highest salary, where N can be any number whether it’s the 3rd highest, 4th highest, 5th highest, 10th highest, etc? This is also an interesting question – try to come up with an answer yourself before reading the one below to see what you come up with.

The answer and explanation to finding the nth highest salary in SQL


Here we will present one possible answer to finding the nth highest salary first, and the explanation of that answer after since it’s actually easier to understand that way. Note that the first answer we present is actually not optimal from a performance standpoint since it uses a subquery, but we think that it will be interesting for you to learn about because you might just learn something new about SQL. If you want to see the more optimal solutions first, you can skip down to the sections that says “Find the nth highest salary without a subquery” instead.

The SQL below will give you the correct answer – but you will have to plug in an actual value for N of course. This SQL to find the Nth highest salary should work in SQL Server, MySQL, DB2, Oracle, Teradata, and almost any other RDBMS:

SELECT * /*This is the outer query part */
FROM Employee Emp1
WHERE (N-1) = ( /* Subquery starts here */
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > Emp1.Salary)

How does the query above work?

The query above can be quite confusing if you have not seen anything like it before – pay special attention to the fact that “Emp1? appears in both the subquery (also known as an inner query) and the “outer” query. The outer query is just the part of the query that is not the subquery/inner query – both parts of the query are clearly labeled in the comments.

The subquery is a correlated subquery

The subquery in the SQL above is actually a specific type of subquery known as a correlated subquery. The reason it is called a correlated subquery is because the the subquery uses a value from the outer query in it’s WHERE clause. In this case that value is the Emp1 table alias as we pointed out earlier. A normal subquery can be run independently of the outer query, but a correlated subquery can NOT be run independently of the outer query. If you want to read more about the differences between correlated and uncorrelated subqueries you can go here: Correlated vs Uncorrelated Subqueries.


The most important thing to understand in the query above is that the subquery is evaluated each and every time a row is processed by the outer query. In other words, the inner query can not be processed independently of the outer query since the inner query uses the Emp1 value as well.

Finding nth highest salary example and explanation

Let’s step through an actual example to see how the query above will actually execute step by step. Suppose we are looking for the 2nd highest Salary value in our table above, so our N is 2. This means that the query will look like this:

SELECT *
FROM Employee Emp1
WHERE (1) = (
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > Emp1.Salary)
You can probably see that Emp1 and Emp2 are just aliases for the same Employee table – it’s like we just created 2 separate clones of the Employee table and gave them different names.

Understanding and visualizing how the query above works

Let’s assume that we are using this data:

Employee
Employee ID Salary
3 200
4 800
7 450
For the sake of our explanation, let’s assume that N is 2 – so the query is trying to find the 2nd highest salary in the Employee table. The first thing that the query above does is process the very first row of the Employee table, which has an alias of Emp1.

The salary in the first row of the Employee table is 200. Because the subquery is correlated to the outer query through the alias Emp1, it means that when the first row is processed, the query will essentially look like this – note that all we did is replace Emp1.Salary with the value of 200:

SELECT *
FROM Employee Emp1
WHERE (1) = (
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > 200)
So, what exactly is happening when that first row is processed? Well, if you pay special attention to the subquery you will notice that it’s basically searching for the count of salary entries in the Employee table that are greater than 200. Basically, the subquery is trying to find how many salary entries are greater than 200. Then, that count of salary entries is checked to see if it equals 1 in the outer query, and if so then everything from that particular row in Emp1 will be returned.


Note that Emp1 and Emp2 are both aliases for the same table – Employee. Emp2 is only being used in the subquery to compare all the salary values to the current salary value chosen in Emp1. This allows us to find the number of salary entries (the count) that are greater than 200. And if this number is equal to N-1 (which is 1 in our case) then we know that we have a winner – and that we have found our answer.

But, it’s clear that the subquery will return a 2 when Emp1.Salary is 200, because there are clearly 2 salaries greater than 200 in the Employee table. And since 2 is not equal to 1, the salary of 200 will clearly not be returned.

So, what happens next? Well, the SQL processor will move on to the next row which is 800, and the resulting query looks like this:

SELECT *
FROM Employee Emp1
WHERE (1) = (
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > 800)
Since there are no salaries greater than 800, the query will move on to the last row and will of course find the answer as 450. This is because 800 is greater than 450, and the count will be 1. More precisely, the entire row with the desired salary would be returned, and this is what it would look like:

EmployeeID Salary
7 450

It’s also worth pointing out that the reason DISTINCT is used in the query above is because there may be duplicate salary values in the table. In that scenario, we only want to count repeated salaries just once, which is exactly why we use the DISTINCT operator.

A high level summary of how the query works

Let’s go through a high level summary of how someone would have come up with the SQL in the first place – since we showed you the answer first without really going through the thought process one would use to arrive at that answer.

Think of it this way – we are looking for a pattern that will lead us to the answer. One way to look at it is that the 2nd highest salary would have just one salary that is greater than it. The 4th highest salary would have 3 salaries that are greater than it. In more general terms, in order to find the Nth highest salary, we just find the salary that has exactly N-1 salaries greater than itself. And that is exactly what the query above accomplishes – it simply finds the salary that has N-1 salaries greater than itself and returns that value as the answer.

Find the nth highest salary using the TOP keyword in SQL Server

We can also use the TOP keyword (for databases that support the TOP keyword, like SQL Server) to find the nth highest salary. Here is some fairly simply SQL that would help us do that:

SELECT TOP 1 Salary
FROM (
      SELECT DISTINCT TOP N Salary
      FROM Employee
      ORDER BY Salary DESC
      ) AS Emp
ORDER BY Salary
To understand the query above, first look at the subquery, which simply finds the N highest salaries in the Employee table and arranges them in descending order. Then, the outer query will actually rearrange those values in ascending order, which is what the very last line “ORDER BY Salary” does, because of the fact that the ORDER BY Default is to sort values in ASCENDING order. Finally, that means the Nth highest salary will be at the top of the list of salaries, which means we just want the first row, which is exactly what “SELECT TOP 1 Salary” will do for us!


Find the nth highest salary without using the TOP keyword

There are many other solutions to finding the nth highest salary that do not need to use the TOP keyword, one of which we already went over. Keep reading for more solutions.

Find the nth highest salary in SQL without a subquery

The solution we gave above actually does not do well from a performance standpoint. This is because the use of the subquery can really slow down the query. With that in mind, let’s go through some different solutions to this problem for different database vendors. Because each database vendor (whether it’s MySQL, Oracle, or SQL Server) has a different SQL syntax and functions, we will go through solutions for specific vendors. But keep in mind that the solution presented above using a subquery should work across different database vendors.

Find the nth highest salary in MySQL

In MySQL, we can just use the LIMIT clause along with an offset to find the nth highest salary. If that doesn’t make sense take a look at the MySQL-specific SQL to see how we can do this:

SELECT Salary FROM Employee
ORDER BY Salary DESC LIMIT n-1,1
Note that the DESC used in the query above simply arranges the salaries in descending order – so from highest salary to lowest. Then, the key part of the query to pay attention to is the “LIMIT N-1, 1?. The LIMIT clause takes two arguments in that query – the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. So, it’s saying that the offset of the first row to return should be N-1, and the max number of rows to return is 1. What exactly is the offset? Well, the offset is just a numerical value that represents the number of rows from the very first row, and since the rows are arranged in descending order we know that the row at an offset of N-1 will contain the (N-1)th highest salary.

Find the nth highest salary in SQL Server

In SQL Server, there is no such thing as a LIMIT clause. But, we can still use the offset to find the nth highest salary without using a subquery – just like the solution we gave above in MySQL syntax. But, the SQL Server syntax will be a bit different. Here is what it would look like:

SELECT Salary FROM Employee
ORDER BY Salary DESC OFFSET N-1 ROW(S)
FETCH FIRST ROW ONLY
Note that I haven’t personally tested the SQL above, and I believe that it will only work in SQL Server 2012 and up. Let me know in the comments if you notice anything else about the query.

Find the nth highest salary in Oracle using rownum

Oracle syntax doesn’t support using an offset like MySQL and SQL Server, but we can actually use the row_number analytic function in Oracle to solve this problem. Here is what the Oracle-specific SQL would look like to find the nth highest salary:

select * from (
  select Emp.*,
row_number() over (order by Salary DESC) rownumb
from Employee Emp
)
where rownumb = n;  /*n is nth highest salary*/
The first thing you should notice in the query above is that inside the subquery the salaries are arranged in descending order. Then, the row_number analytic function is applied against the list of descending salaries. Applying the row_number function against the list of descending salaries means that each row will be assigned a row number starting from 1. And since the rows are arranged in descending order the row with the highest salary will have a 1 for the row number. Note that the row number is given the alias rownumb in the SQL above.

This means that in order to find the 3rd or 4th highest salary we simply look for the 3rd or 4th row. The query above will then compare the rownumb to n, and if they are equal will return everything in that row. And that will be our answer!


Find the nth highest salary in Oracle using RANK

Oracle also provides a RANK function that just assigns a ranking numeric value (with 1 being the highest) for some sorted values. So, we can use this SQL in Oracle to find the nth highest salary using the RANK function:

select * FROM (
select EmployeeID, Salary
,rank() over (order by Salary DESC) ranking
from Employee
)
WHERE ranking = N;
The rank function will assign a ranking to each row starting from 1. This query is actually quite similar to the one where we used the row_number() analytic function, and works in the same way as well.

We’ve now gone through many different solutions in different database vendors like Oracle, MySQL, and SQL Server. Hopefully now you understand how to solve a problem like this, and you have improved your SQL skills in the process! Be sure to leave a comment if you have any questions or observations.

Date Functions in Oracle

Alter session set NLS_DATE_FORMAT='DD-MON-YY HH:MI:SS';

Date Functions and Operators.
To see the system date and time use the following functions :

CURRENT_DATE :returns the current date in the session time zone, in a value in the Gregorian calendar of datatype DATE

SYSDATE :Returns the current date and time.

SYSTIMESTAMP :The SYSTIMESTAMP function returns the system date, including fractional seconds and time zone of the database. The return type is TIMESTAMP WITH TIME ZONE.


SYSDATE Example

To see the current system date and time give the following query.

select sysdate from dual;

SYSDATE
-------
8-AUG-03

The format in which the date is displayed depends on NLS_DATE_FORMAT parameter.

For example set the NLS_DATE_FORMAT to the following format

Alter session set NLS_DATE_FORMAT=’DD-MON-YYYY HH:MIpm’;

Then give the give the following statement

select sysdate from dual;

SYSDATE
------------------
8-AUG-2003 03:05pm

The default setting of NLS_DATE_FORMAT is DD-MON-YY



CURRENT_DATE Example

To see the current system date and time with  time zone use CURRENT_DATE function

ALTER SESSION SET TIME_ZONE = '-4:0';
ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS';
SELECT SESSIONTIMEZONE, CURRENT_DATE FROM DUAL;

SESSIONTIMEZONE CURRENT_DATE
--------------- --------------------
-04:00          22-APR-2003 14:15:03

ALTER SESSION SET TIME_ZONE = '-7:0';
SELECT SESSIONTIMEZONE, CURRENT_DATE FROM DUAL;

SESSIONTIMEZONE CURRENT_DATE
--------------- --------------------
-07:00          22-APR-2003 09:15:33


SYSTIMESTAMP Example

To see the current system date and time with fractional seconds with time zone give the following statement

Select systimestamp from dual;

SYSTIMESTAMP
-------------------------------
22-APR-03 08.38.55.538741 AM -07:00


DATE FORMAT MODELS

To translate the date into a different format string  you can use TO_CHAR function with date format. For example to see the current day you can give the following query

To translate a character value, which is in format other than the default date format, into a date value you can use TO_DATE function with date format to date


Select to_char(sysdate,’DAY’)”Today” FROM DUAL;

TODAY
-------
THURSDAY

Like this “DAY” format model there are many other date format models available in Oracle. The following table list date format models.

FORMAT
MEANING
D
Day of the week
DD
Day of the month
DDD
Day of the year
DAY
Full day for ex. ‘Monday’, ’Tuesday’, ’Wednesday’
DY
Day in three letters for ex. ‘MON’, ‘TUE’,’FRI’
W
Week of the month
WW
Week of the year
MM
Month in two digits  (1-Jan, 2-Feb,…12-Dec)
MON
Month in three characters like “Jan”, ”Feb”, ”Apr”
MONTH
Full Month like “January”, ”February”, ”April”
RM
Month in Roman Characters (I-XII, I-Jan, II-Feb,…XII-Dec)
Q
Quarter of the Month
YY
Last two digits of the year.
YYYY
Full year
YEAR
Year in words like “Nineteen Ninety Nine”
HH
Hours in 12 hour format
HH12
Hours in 12 hour format
HH24
Hours in 24 hour format
MI
Minutes
SS
Seconds
FF
Fractional Seconds
SSSSS
Milliseconds
J
Julian Day i.e Days since 1st-Jan-4712BC to till-date
RR
If the year is less than 50 Assumes the year as 21ST Century. If the year is greater than 50 then assumes the year in 20th Century.


SUFFIXES
TH
Returns th, st, rd or nd according to the leading number like 1st , 2nd 3rd 4th
SP
Spells out the leading number
AM or PM
Returns AM or PM according to the time
SPTH
Returns Spelled Ordinal number. For. Example First, Fourth

For example to see the today’s date in the following format

Friday, 7th March, 2014

Give the following statement
select to_char(sysdate,’Day, ddth Month, yyyy’)”Today” from dual;

TODAY
------------------------
Friday, 7th March, 2014



For example you want to see hire dates of all employee in the following format

Friday, 8th August, 2003

Then give the following query.

select to_char(hire_date,’Day, ddth Month, yyyy’) from emp;

TO_DATE Example

To_Date function is used to convert strings into date values. For example you want to see what was the day on 15-aug-1947. The use the to_date function to first convert the string into date value and then pass on this value to to_char function to extract day.

select to_char(to_date(’15-aug-1947’,’dd-mon-yyyy’),’Day’)
                                         from dual;

TO_CHAR(
--------
Friday


To see how many days have passed since 15-aug-1947 then give the following query

Select sysdate-to_date(’15-aug-1947’,’dd-mon-yyyy’)
from dual;


Now we want to see which date will occur after 45 days from now

Select sysdate+45 from dual;

SYSDATE
-------
06-JUN-2003



ADD_MONTHS

To see which date will occur after 6 months from now, we can use ADD_MONTHS function

Select ADD_MONTHS(SYSDATE,6) from dual;

ADD_MONTHS
----------
22-OCT-2003


MONTHS_BETWEEN

To see how many months have passed since 15-aug-1947, use the MONTHS_BETWEEN function.

Select months_between(sysdate,to_date(’15-aug-1947’))
                             from dual;

Months
------
616.553

To eliminate the decimal value use truncate function

LAST_DAY

To see the last date of the month of a given date, Use LAST_DAY function.

select LAST_DAY(sysdate) from dual;

LAST_DAY
--------
31-AUG-2003

NEXT_DAY

To see when the next Saturday is coming, use the NEXT_DAY function.

select next_day(sysdate) from dual;

NEXT_DAY
-----------
09-AUG-2003

EXTRACT

An EXTRACT datetime function extracts and returns the value of a specified datetime field from a datetime or interval value expression. When you extract a TIMEZONE_REGION or TIMEZONE_ABBR (abbreviation), the value returned is a string containing the appropriate time zone name or abbreviation

The syntax of EXTRACT function is

EXTRACT ( YEAR / MONTH / WEEK / DAY / HOUR / MINUTE / TIMEZONE  FROM DATE)

Example

The following demonstrate the usage of EXTRACT function to extract year from current date.
Select extract(year from sysdate) from dual;

EXTRACT
-------
2003

select to_char(to_date(:number,'j'),'jsp') from dual;

Oracle Interview Questions Part1

1. What is the difference between a view and a materialized view ?

Ans:

i)A View is stored in database as SQL statement. It is created as and when needed.


Materialized view is created as a table and stored physically in the database.

ii) Views created from multiple tables cannot be modified Materialized view can be modified

iii) Views are used to hide the complexity of SQL statement. For Eg: if you have a SQL statement with 3 tables joined by UNION with different WHERE clauses, it will be faster to have a view and just select from the view instead of complex SQL stmt.


Materialized views are the tables with pre-calculated joins and aggregated data from multiple tables. They improve performance as the it precalcutes the joins and aggregations and stores the results into the database even before the execution. When the query is executed, the query optimizer rewrites the query to use the materialized view instead of the underlying detail tables.

2. What are outer joins ? Name its types ?

Ans : Outer joins are used to join 2 tables so that the unmatched rows from one table are also retrived along with the matching rows. There are 3 types of outer joins: Left outer join, right outer join and Full outer join.


Left Outer Join :unmatched rows from left table, (+) should to attached to the right table.

Right outer join :unmatched rows from right table, (+) should to attached to the left table.

To avoid the confusion with (+) symbol, from oracle 9i, we use the word ' left outer join' Eg: select....from emp e LEFT OUTER JOIN dept d where emp.deptno = d.deptno;


Full Outer join is a combination of left and right outer join. For eg: you want to see a list of all projects and the tasks associated with all projects.


Eg: select t.task_name, p.project_name

from all_tasks FULL OUTER JOIN all_projects

where t.project_id = p.project_id;

3. How does the use of a package improves the performance ?


Ans: i) When you call a packaged function or subrpogram, the whole package is called and stored into the the memory. So the next time when we call any packaged function/subprogram, there is no need of disk I/O

ii) Packages stop cascading dependencies and unnessasary recompiling. When a packaged function is compiled, Oracle does not recompile the calling subprogram. That program will be recompiled only if we made any changes in the specs of the calling program.

4.Can we have a procedure declared in package body but not declared in package specifications?

Ans: Yes.But that procedure will be local and can not be called by other procedures in the package.When we declare a proc in package spec, it becomes global for the package.

5. Can we have a package spec without a body?

Ans:Yes

6. Can we have a procedure spec without body ?

Ans: No. It should atleast have NULL; inside begin and end.

7. Can we have a commit in trigger?

Ans: Yes. You can commit inside the trigger but you have to declare it as AUTONOMOUS_TRANSACTION.

8. How do u use variable in code of a trigger ?

Ans: by using':old' and ':new' clauses. Eg :old.salary, :new.salary

9. You wrote a PL/SQL stored procedure. How do u make it hidden so that NOBODY,not even the DBA or the owner can read the procedure ?

Ans: Use Wrap feature of Oracle 9i. Once wrapped, NO one, can read the code. Eg : Wrap iname=c:\programs\my_file.sql. OR wrap iname=c:\programs\my_file.plb. .plb extension is PL/SQL Binary file, output file of the wrap function.


10. What do you know about STANDARD package in Oracle ?

Ans: A package named STANDARD defines the PL/SQL environment. The package spec includes All the types, functions, procedures, etc which are automaticaly available to PL/SQLprograms. For eg: ABS(),SUM(),COUNT()

11. Name some Oracle's built-in packages?

Ans:


DBMS_OUTPUT - used to display a messgae, especially while debugging

DBMS_PIPE - This allows 2 different sessions of the database to communicate over the named pipe.

DBMS_DDL - Contains procedures to wrap single PL/SQL units like package specs, package body, function, procedure, type specs, type body, etc. Eg : DBMS_DDL.CREATE_WRAPPED();

DBMS_ALERT - lets you use database triggers to alert an application when some database values change

UTL_FILE - it allows the PL/SQL program to read from and write into text files.

UTL_SMTP - allows the PL/SQL program to send emails over Simple Mail Transfer Protocol

UTL_HTP, HTF - allows PL/SQL to generate HTML tags.

UTL_HTTP - allows PL/SQL programs to make HTTP calls. It gets the data from Internet. The inputs ar the URL and the contacts of the website. The return data is usually in HTML format.

DBMS_SQL - Helps you to write stored procedures and anonymous PL/SQL blocks that use dynamic SQL. For ex: it allows us to create a procedure based on a table, whose name is given at run-time.

12. What are database trigger? Types of database trigger?

Ans: These are the stored subprograms associated with tables, views , schemas or database

Table level triggers - 3 ways to catagorize these triggers : Before/After , Insert/Update/Delete, and Row-level (for each row) vs statement-level

View level - We cannot use the Before/After triggers on views, so we use " Instead of " triggers. Eg: Create or replace trigger trg_cal_sal INSTEAD OF INSERT on v_emp....

System triggers on database or Schema level - event triggers : Eg: LOGON, LOGOFF

13. What are implicit and explicit Cursors? Which one is recommended ?

Ans: A cursor is a handle or a pointer for the memory associated with a specific SQL statement. A cursor is basically an area allocated by Oracle for executing the Sql Statement. An implicit cursor statement are managed by Oracle itself and generally used for Single row query. When u need precise control on the cursor and its processing, use Explcit cursors used for multi row query.

Implicit cursor is always faster than explicit cursor.Bcoz, expilit cursor will have more no of lines, and the rule is "Less the no of lines less is the processing time." Also, implicit cursor does exception handling for NO_DATA_FOUND and TOO_MANY_ROWS by itself . We need not to write these exceptions. In explicit cursors, we have to write these exceptions.

14. What is mutating error? How do u resolve it?

Ans : When you perform a DML query (like Insert, Update, Delete) on a table,and another query is accessing the same table at the same time,none of the queries get completed and the table is called as mutuating table.It will then throw a mutating error. You can perform only 'Select' on such a table. You can resolve this error by using a PL/SQL table.

15.What is the difference between cursor & ref cursor?

Ans: Cursor is a handle or pointer to the memory location associated with a SQL statement. With a REF cursor, you can define a cursor variable, which will point to that memory space. With Ref cursor, we can dynamically retrive data in form of recordset from a PL/SQL stored procedure.

It works very similar to explicit cursor except that we define the query for this cursor at run-time.

The syntax of explicit cursor :

Cursor emp_cur IS

SELECT * from emp;

.......

OPEN emp_cur;

Syntax of REF cursor :

TYPE emp_curtype IS REF CURSOR RETURN emp%ROWTYPE; --cursor type

emp_curvar emp_curtype; --cursor variable

.........

v_state := 'NY'

OPEN emp_curvar FOR select * from emp where state = v_state;

..........

v_state := 'NJ'

OPEN emp_curvar FOR select * from emp where state = v_state;

As you can see, REF cursors can be reused for different SQL queries at runtime.

There are 2 types of REF cursors : Strong and weak.

TYPE emp_curtype IS REF CURSOR RETURN emp%ROWTYPE; --Strong REF cursor

TYPE emp_curtype IS REF CURSOR; --weak REF cursor

Which one is better ? depends on your requirement. In strong cursor, we attach the return ROWTYPE at the declaration time itself. So, the compiler knows what the cursor variable should return.So, its less error prone. Weak cursors , on the other hand , are more flexible because they can be used with any query, any return ROWTYPE , even different ROWTYPES at different calls to it.




16. What are different options in function declaration ?

Ans:

AUTHID : Specifies how to execute the function. Ex: DEFINER/CURRENT USER

PARALLEL_ENABLE: Specifies if we can run the function parallelly

DETERMINISTIC:

AUTONOMOUS_TRANSACTION: Specifies if this function is an Autonous Transaction
17. What is PRAGMA ? What are the different types of PRAGMA ?

Ans: Pragmas are specially formatted comments. Pragma tells Oracle to use specific rules other than the default rules for a particular object. They are processed at compile time, not at run time.

1. RESTRICTED_REFERENCES : This pragma checks if the function meets the rules.

create package cal_loans as

function credit_ok return boolean;

PRAGMA RESTRICTED_REFERENCES(credit_ok, RNPS,WNDS );
WNDS - Write No Database State

RNPS - Read No Package State
2. EXCEPTION_INIT : This pragma is used to bind a user-defined exception to a particular number.

Declare MyExcep exception;

PRAGMA EXCEPTION_INIT(MyExcep,10001);

begin

..…

exception

when I then

dbms_output.put_line( 'Duplicate value');

end;

3. AUTONOMOUS_TRANSACTION: Its a kind of PRAGMA which changes the way a subprogram works within a transaction. A child program marked with this pragma can be committed and rolled back without committing or rolling back the parent transaction.

Eg : When you declare a trigger as AUTONOMOUS_TRANSACTION, then you can commit inside the trigger, irrespective of the calling procedure.

CREATE OR REPLACE TRIGGER audit_sal
AFTER UPDATE OF salary ON employees FOR EACH ROW
DECLARE
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
-- bind variables are used here for values
INSERT INTO emp_audit VALUES( :old.employee_id, SYSDATE,
:new.salary, :old.salary );
COMMIT;
END;

4. SERIALLY_REUSABLE: This pragma tells the PL/SQL engine to reuse the package data. By default, the package level data is available throughout the session, by specifing this pragma, the data will not persist after the package is executed. You should specify the PRAGMA in both, package specification and body.

18.How to avoid errors with Autonomous transactions?

Ans:

1. If the autonomous transactions uses the resources used by main transac, a deadlock will occur.

2. The auto transac should be commited or rolled back beforeexiting, or oracle will give error.

3. The maximum no of concurrent transac is set by Oracle. That number might be exceeded as autonomous transac and main transac run concurrently.

19.What is the difference between Autonomous Transaction and Nested Transaction ?

Ans: As in case of Nested Transaction, Autonomous Transaction :

1. Do not share trasaction resources like variables with main transaction.

2.Have to be commited or rolled back separately.

3. It does not depend on main transaction. When main transaction rolls back, nested transaction also rolls back but autonomous transaction does not.

4.Exceptions raised in autonomous transaction are transaction-level and not statement-level.

20.What is the difference between ANY and ALL conditions?

Ans:ANY will check for the rows in the right side matching the condition and returns the rows for which the condition is true. It will not wait and search for all rows.

ALL will check if the condition is true for ALL rows and then only it will return the value.

21.What is the difference between UNION and UNION ALL?

Ans: Both do the same job but UNION ALL will give all rows,whereas UNION will skip the duplicate rows and give only distinct rows. Hence, UNION is faster than UNION ALL.

22.What is the difference between CHAR and VARCHAR2?

Ans:Char is used for fixed length strings, varchar2 is used for variable length string. Char is faster than varchar2,so if the length is fixed and not very long, it is recommanded to use Char.

23.What is the difference between EXISTS and IN operator?

Ans:IN works same as OR operator. The IN statement is internally converted into no of OR statements.It returns all the values for which the condition matches. EXISTS first analyzes the subquery to check if it returns any rows. If yes, then it returns True, else it returns False.

Exists - always has a subquery, IN- may have a subquery of list of values.

Example:

SELECT e.* from employees e

where exists(select deptno from dept d where e.deptno = d.deptno);

24.What are Global Temporary tables?

Ans: The temporary tables are the database tables or PL/SQL tables. The maintainance and management of these tables is handled by Global Temporary Tables. They are temporary because the data is available only to the current session. They are called as Global because the table definition is available to all sessions.

Example: Create global temporary table my_g_temp_tab(

name varchar2(20), city varchar2(10) )

on commit delete rows /*OR on commit reserve rows*/;

25.
================================================================================


51 Oracle Interview Questions and Answers -


1. Reference Cursor ?

A reference cursor is a pointer to a memory location that can be passed
between different PL/SQL clients, thus allowing query result sets to be
passed back and forth between clients.

A reference cursor is a variable type defined using the PL/SQL TYPE
statement within an Oracle package, much like a PL/SQL table:

TYPE ref_type_name IS REF CURSOR RETURN return_type;

Here, ref_type_name is the name given to the type and return_type represents
a record in the database. You do not have to specify the return type as this
could be used as a general catch-all reference cursor. Such non-restrictive
types are known as weak, whereas specifying the return type is restrictive,
or strong. The following example uses %ROWTYPE to define a strong return
type that represents the record structure of the emp table:

DECLARE TYPE EmpCurType IS REF CURSOR RETURN emp%ROWTYPE;



================================================================================
2. Anonymous Block ?
An unnamed PL/SQL block is called an anonymous block.

A PL/SQL block contains three parts or sections. They are:
• The optional Declaration section.
• The mandatory Execution section.
• The optional Exception (or Error) Handling
section.

================================================================================
3. Explain how cursor is implemented in PL/SQL



A cursor is a variable that runs through the rows of some table or answer to
some query.

CURSOR employee_cur IS SELECT * FROM employee;

Once I have declared the cursor, I can open it:
OPEN employee_cur;

And then I can fetch rows from it:
FETCH employee_cur INTO employee_rec;

and, finally, I can close the cursor:
CLOSE employee_cur;

***********
DECLARE
   CURSOR joke_feedback_cur
   IS
      SELECT J.name, R.laugh_volume, C.name
        FROM joke J, response R, comedian C
       WHERE J.joke_id = R.joke_id
         AND J.joker_id = C.joker_id;
BEGIN
   ...
END;

================================================================================
4. Constraints ?


Integrity constraints are used to enforce Business logic.
Enforcing rules with integrity constraints is less costly than enforcing the
equivalent rules by issuing SQL statements in the application.

Only define NOT NULL constraints for columns of a table that absolutely
require values at all times.

Use the combination of NOT NULL and UNIQUE key integrity constraints to
force the input of values in the UNIQUE key; this combination of data
integrity rules eliminates the possibility that any new row's data will ever
attempt to conflict with an existing row's data.

Choosing a Table's Primary Key :
Each table can have one primary key. A primary key allows each row in a
table to be uniquely identified and ensures that no duplicate rows exist.
Use the following guidelines when selecting a primary key:

Choose a column whose data values are unique.
The purpose of a table's primary key is to uniquely identify each row of the
table. Therefore, the column or set of columns in the primary key must
contain unique values for each row.

Choose a column whose data values are never changed.
A primary key value is only used to identify a row in the table; primary key
values should never contain any data that is used for any other purpose.
Therefore, primary key values should rarely need to be changed.

Choose a column that does not contain any nulls.
A PRIMARY KEY constraint, by definition, does not allow the input of any row
with a null in any column that is part of the primary key.

Choose a column that is short and numeric.
Short primary keys are easy to type. You can use sequence numbers to easily
generate numeric primary keys.

Avoid choosing composite primary keys.
Although composite primary keys are allowed, they do not satisfy the
previous recommendations. For example, composite primary key values are long
and cannot be assigned by sequence numbers.

Foreign Key(Referential Integrity): Whenever two tables are related by a
common column (or set of columns), define a PRIMARY or UNIQUE key constraint
on the column in the parent table, and define a FOREIGN KEY constraint on
the column in the child table, to maintain the relationship between the two
tables.

Using CHECK Integrity Constraints
Use CHECK constraints when you need to enforce integrity rules that can be
evaluated based on logical expressions. Never use CHECK constraints when any
of the other types of integrity constraints can provide the necessary
checking.

*The condition must be a Boolean expression that can be evaluated using the
values in the row being inserted or updated.
*The condition cannot contain subqueries or sequences.
*The condition cannot include the SYSDATE, UID, USER, or USERENV SQL
functions.
*The condition cannot contain the pseudocolumns LEVEL, PRIOR, or ROWNUM;
*The condition cannot contain a user-defined SQL function.

Eg.
CREATE TABLE dept (

deptno  NUMBER(3) PRIMARY KEY,
dname   VARCHAR2(15),
loc     VARCHAR2(15),
        CONSTRAINT dname_ukey UNIQUE (dname, loc),
        CONSTRAINT loc_check1
                CHECK (loc IN ('NEW YORK', 'BOSTON', 'CHICAGO')));

================================================================================
5. Difference between Primary Key and Unique key ?

*  Primary keys are used to identify each row of the table uniquely. Unique
keys should not have the purpose of identifying rows in the table.
* A primary key field cannot be Null, whereas a Unique column can have a
Null value.
* There could be only 1 Primary Key per table, but there could be any number
of Unique Key columns.
* A primary key should be a Unique column, but all Unique Key column need
not be a PRimary Key
================================================================================
6. what are diffenent Joins explain . outer ? how would you write outer
join(=+)
   if specify + to the right of equal to sign, which table data will be in
full.

A join is a query that combines rows from two or more tables.
An equijoin is a join with a join condition containing an equality operator.
( where A.b = C.d)
A self join is a join of a table to itself.
Cartesian Products
If two tables in a join query have no join condition, then Oracle returns
their Cartesian product. Oracle combines each row of one table with each row
of the other. A Cartesian product always generates many rows and is rarely
useful. For example, the Cartesian product of two tables, each with 100
rows, has 10,000 rows. Always include a join condition unless you
specifically need a Cartesian product. If a query joins three or more tables
and you do not specify a join condition for a specific pair, then the
optimizer may choose a join order that avoids producing an intermediate
Cartesian product.

An inner join (sometimes called a "simple join") is a join of two or more
tables that returns only those rows that satisfy the join condition.

An outer join returns all rows that satisfy the join condition and also
returns some or all of those rows from one table for which no rows from the
other satisfy the join condition.

To write a query that performs an outer join of tables A and B and returns
all rows from A( left outer join), apply the outer join operator (+) to all
columns of B in the join condition.
For example,
SELECT ename, job, dept.deptno, dname
    FROM emp, dept
    WHERE emp.deptno (+) = dept.deptno;

will select all departments even if there is no employee for a particular
dept.

Similarly to get all rows from B form a join of A & B , apply the outer join
operator(+) to A.
Example,
    SELECT ename, job, dept.deptno, dname
    FROM emp, dept
    WHERE emp.deptno = dept.deptno (+)

================================================================================
7. Is a function in SELECT possible ?
Yes. FOr example, Select ltrim(price) from Item.
User defined functions work only from Oracle 8i onwards.
================================================================================
8. EXCEPTION handling in PL/SQL

An exception is a runtime error or warning condition, which can be
predefined or user-defined. Predefined exceptions are raised implicitly
(automatically) by the runtime system. User-defined exceptions must be
raised explicitly by RAISE statements. To handle raised exceptions, you
write separate routines called exception handlers.

Example of an exception handler:
DECLARE
   pe_ratio NUMBER(3,1);
BEGIN
   SELECT price / earnings INTO pe_ratio FROM stocks
      WHERE symbol = 'XYZ';  -- might cause division-by-zero error
   INSERT INTO stats (symbol, ratio) VALUES ('XYZ', pe_ratio);
   COMMIT;
EXCEPTION  -- exception handlers begin
   WHEN ZERO_DIVIDE THEN  -- handles 'division by zero' error
      INSERT INTO stats (symbol, ratio) VALUES ('XYZ', NULL);
      COMMIT;
   ...
   WHEN OTHERS THEN  -- handles all other errors
      ROLLBACK;
END;  -- exception handlers and block end here


Unlike predefined exceptions, user-defined exceptions must be declared and
must be raised explicitly by RAISE statements.
Example:
DECLARE
   past_due EXCEPTION;
   acct_num NUMBER;
BEGIN
     ...
     ...
     IF ... THEN
         RAISE past_due;  -- this is not handled
      END IF;

EXCEPTION
   WHEN past_due THEN  -- does not handle RAISEd exception
   WHEN OTHERS THEN    -- handle all other errors

END;


The procedure RAISE_APPLICATION_ERROR lets you issue user-defined ORA- error
messages from stored subprograms. That way, you can report errors to your
application and avoid returning unhandled exceptions.

To call RAISE_APPLICATION_ERROR, use the syntax

raise_application_error(error_number, message[, {TRUE | FALSE}]);


where error_number is a negative integer in the range -20000 .. -20999 and
message is a character string up to 2048 bytes long. If the optional third
parameter is TRUE, the error is placed on the stack of previous errors. If
the parameter is FALSE (the default), the error replaces all previous
errors. RAISE_APPLICATION_ERROR is part of package DBMS_STANDARD, and as
with package STANDARD, you do not need to qualify references to it.

An application can call raise_application_error only from an executing
stored subprogram (or method). When called, raise_application_error ends the
subprogram and returns a user-defined error number and message to the
application. The error number and message can be trapped like any Oracle
error.

Another way to handle exception is to use DECODE statements. For example:
INSERT INTO stats (symbol, ratio)
   SELECT symbol, DECODE(earnings, 0, NULL, price / earnings)
   FROM stocks WHERE symbol = 'XYZ';

Here the DECODE function checks whether the earnings is 0 and if it is zero,
then returns earnings, else price/earnings.
================================================================================
9. When an exception is triggered in a loop, how you
continue to next itereration ?
By having an exception andling block within the loop.

================================================================================
10. Decode ? Using Decode map this logic,

If A>B Display 'A is Big', If A=B Display 'A equals B'
Else 'B is Big'

DECODE(Greatest(A,B), A, 'A is big',
                      B, 'B is Big',
                         'A equals B')

================================================================================
11. What is an index? what are diff type of indices? what is Clustered and
Non Clustered Indeces ?

Indexing is typically listing of keywords alongwith its location and is done
to speed up the Data base.

Create index WORKERSKILL_NAME_SKILL on WORKERSKILL(Name,Skill);

A clustered index is a special type of index that reorders the way records
in the table are physically stored. Therefore table can have only one
clustered index. The leaf nodes of a clustered index contain the data pages.
A nonclustered index is a special type of index in which the logical order
of the index does not match the physical stored order of the rows on disk.
The leaf node of a nonclustered index does not consist of the data pages.
Instead, the leaf nodes contain index rows.
================================================================================
12. Mutating Error ?
When we use a row level triger on a table, and at the same time if we
query/insert/delete/update on the same table, it will give the mutating
error.

================================================================================
13. How to avoid mutating error?
Two possible solutions.
1. Change the design of the table so as to avoid querying or any update on
the table on which the row level trigger is holding on.
2. Create a package which holds a PL/SQL table with the RowID of the rows
need to insert/update and a counter of the rows
a. In BEFORE STATEMENT trigger set the counter to zero.
b. In every ROW trigger call a procedure from the package which will
register the RowId and modify the counter
c. In AFTER STATEMENT trigger call a procedure which will make the needed
checks and update the particular rows of the table.
If you are not familiar with PL/SQL tables alternatively you can use
temporary Oracle tables. It is also a good idea.

================================================================================
14. Difference between Delete and Truncate.
Truncate will permenantly delete the record and no rollback capability will
exist.
The delete command remove records from a table. Delete moves records to the
rollback segment enabling rollback capability.
Excessive use of triggers can result in complex interdependencies, which can
be difficult to maintain in a large application.


================================================================================
15. How many types of triggers are there and what are ? (Before Insert,
after Insert, update,
delete etc..)

Triggers are similar to stored procedures. A trigger stored in the database
can include SQL and PL/SQL or Java statements to run as a unit and can
invoke stored procedures. However, procedures and triggers differ in the way
that they are invoked. A procedure is explicitly run by a user, application,
or trigger. Triggers are implicitly fired by Oracle when a triggering event
occurs, no matter which user is connected or which application is being
used.
Different Types
---------------
Row Triggers and Statement Triggers
BEFORE and AFTER Triggers
INSTEAD OF Triggers ( ON views,for INSERT etc, instaed of Inserting, it will
carry out the trigger statements)
Triggers on System Events(shut down) and User Events ( log on)
================================================================================
16. What all composite datatypes in oracle
Composite Data types:

Table

1. Is similar but not the same as a database table
2. Must contain only one column of any scalar datatype
3. Is like a one-dimensional array of any size
4. Has its elements indexed with a binary integer column called the primary
key of the table

Record

1. Contains uniquely defined columns of different data types,
2. Enables us to treat dissimilar columns that are logically related as a
single unit.

================================================================================
17. what is PL/SQL tables?


================================================================================
18. What are the default packages provided by oracle
The ones with "DBMS_" prefix. Eg. DBMS_Output, DBMS_ALERT

================================================================================
19. What is the diff between Where and Having

Having clause is used where group by clasue is used to restrict the groups
of returned rows to those groups for which the specified condition is TRUE.
The HAVING condition cannot contain a scalar subquery expression
eg:
SELECT department_id, MIN(salary), MAX (salary)
   FROM employees
   GROUP BY department_id
   HAVING MIN(salary) < 5000;

================================================================================
20. How is error Handling done?


================================================================================
21. I have table that contains state codes,
I might have more than 1 rows with the same state code, how can I find out?
select count(*), state_code from table. IF this is > 1 , then we can assure
that there are duplicates.


================================================================================
22. How do you copy rows from Schema a , table p to
table p in schema b ?
To copy between tables on a remote database, include the same username,
password, and service name in the FROM and TO clauses:

COPY FROM HR/your_password@SchemaA -
TO HR/your_password@SchemaB -
INSERT tableP-
USING SELECT * FROM tableP


================================================================================
23. What is %Rowtype and %Type

PROCEDURE Get_emp_names(Dept_num IN Emp_tab.Deptno%TYPE)
..Means the INput Parameter Dept_num should have the same Data Type as
Emp_tab.DeptNo.

Use the %ROWTYPE attribute to create a record that contains all the columns
of the specified table. The following example defines the Get_emp_rec
procedure, which returns all the columns of the Emp_tab table in a PL/SQL
record for the given empno:

PROCEDURE Get_emp_rec (Emp_number  IN  Emp_tab.Empno%TYPE,
                       Emp_ret     OUT Emp_tab%ROWTYPE) IS
BEGIN
   SELECT Empno, Ename, Job, Mgr, Hiredate, Sal, Comm, Deptno
      INTO Emp_ret
      FROM Emp_tab
      WHERE Empno = Emp_number;
END;

You could call this procedure from a PL/SQL block as follows:

DECLARE
   Emp_row      Emp_tab%ROWTYPE;     -- declare a record matching a
                                     -- row in the Emp_tab table
BEGIN
   Get_emp_rec(7499, Emp_row);   -- call for Emp_tab# 7499
   DBMS_OUTPUT.PUT(Emp_row.Ename || ' '                || Emp_row.Empno);
   DBMS_OUTPUT.PUT(' '           || Emp_row.Job || ' ' || Emp_row.Mgr);
   DBMS_OUTPUT.PUT(' '           || Emp_row.Hiredate   || ' ' ||
Emp_row.Sal);
   DBMS_OUTPUT.PUT(' '           || Emp_row.Comm || ' '|| Emp_row.Deptno);
   DBMS_OUTPUT.NEW_LINE;
END;



================================================================================
24. How to use the cursor with using open, fetch and close.?

================================================================================
25. using select Statement how you will retrieve the user who is logged in?

SELECT SYS_CONTEXT ('USERENV', 'SESSION_USER')
FROM DUAL;

================================================================================
26. When Exception occurs, i want to see the error generated by Oracle. How
to see it?
SQLERRM
================================================================================
27. how to generate the out of the select statement in a file?
SPOOL

================================================================================
28. how to find the duplicate records?

select count(*), job from emp group by job having count(*) > 1

then there are duplicates.
================================================================================
29. What is Procedure, function, package and anonymous block?

Procedures are named groups of SQl statements.
Functions are like Procedures, but can return a value.
Packages are groups of procedures, functions, variables and SQL statements.
An unnamed PL/SQL block is called an anonymous block.
================================================================================
30. What is group by funcion and where it is used.?
Specify the GROUP BY clause if you want Oracle to group the selected rows
based on the value of expr(s) for each row and return a single row of
summary information for each group.
Expressions in the GROUP BY clause can contain any columns of the tables,
views, or materialized views in the FROM clause, regardless of whether the
columns appear in the select list.


It is used for aggraegate functions.

================================================================================
31. What is the difference between RDBMS and DBMS? Sol: Chords 12 rules.



================================================================================
32. What is normalised and denormalised data?
process of removing redundancy in data by separating the data into multiple
tables.


================================================================================
33. What is a VIEW?
A view is a custom-tailored presentation of the data in one or more tables.
A view can also be thought of as a "stored query." Views do not actually
contain or store data; they derive their data from the tables on which they
are based.

================================================================================
34. Can a view update a table?

Can, but with restrictions.
Like tables, views can be queried, updated, inserted into, and deleted from,
with some restrictions.
All operations performed on a view affect the base tables of the view.
================================================================================
35. What happens if there is an exception in the cursor?
How do we ensure that the execution for other records in the cursor does not
stop.



================================================================================
36. What are cursors ? After retrieving the records into the cursor can we
update
the record in the table for the retrieved record. What effect will it
have on the cursor?

Cursors
Oracle uses work areas to execute SQL statements and store processing
information. A PL/SQL construct called a cursor lets you name a work area
and access its stored information. There are two kinds of cursors: implicit
and explicit. PL/SQL implicitly declares a cursor for all SQL data
manipulation statements, including queries that return only one row. For
queries that return more than one row, you can explicitly declare a cursor
to process the rows individually. An example follows:

DECLARE
   CURSOR c1 IS
      SELECT empno, ename, job FROM emp WHERE deptno = 20;


The set of rows returned by a multi-row query is called the result set. Its
size is the number of rows that meet your search criteria
Multi-row query processing is somewhat like file processing. For example, a
COBOL program opens a file, processes records, then closes the file.
Likewise, a PL/SQL program opens a cursor, processes rows returned by a
query, then closes the cursor. Just as a file pointer marks the current
position in an open file, a cursor marks the current position in a result
set.

You use the OPEN, FETCH, and CLOSE statements to control a cursor. The OPEN
statement executes the query associated with the cursor, identifies the
result set, and positions the cursor before the first row. The FETCH
statement retrieves the current row and advances the cursor to the next row.
When the last row has been processed, the CLOSE statement disables the
cursor.


================================================================================
37. What are user defined data types ?

SUBTYPE subtype_name IS base_type;
Eg. SUBTYPE EmpDate IS DATE;           -- based on DATE type
SUBTYPE ID_Num IS emp.empno%TYPE;  -- based on column type

   CURSOR c1 IS SELECT * FROM dept;
   SUBTYPE DeptFile IS c1%ROWTYPE;    -- based on cursor rowtype


To specify base_type, you can use %TYPE, which provides the datatype of a
variable or database column. Also, you can use %ROWTYPE, which provides the
rowtype of a cursor, cursor variable, or database table.

A subtype does not introduce a new type; it merely places an optional
constraint on its base type.

================================================================================
38. How to copy the Structure and data from one table to another in one SQL
stmt?
COPY {FROM database | TO database | FROM database TO database}
{APPEND|CREATE|INSERT|REPLACE} destination_table [(column, column, column,
...)]
USING query

where database has the following syntax:

username[/password]@connect_identifier
================================================================================

39. Describe UNION and UNION ALL.  UNION returns distinct rows selected by
both queries while UNION ALL returns all the rows. Therefore, if the table
has duplicates, UNION will remove them. If the table has no duplicates,
UNION will force a sort and cause performance degradation as compared to
UNION ALL.
================================================================================
40. What is 1st normal form?  Each cell must be one and only one value, and
that value must be atomic: there can be no repeating groups in a table that
satisfies first normal form.
================================================================================
41. What is 2nd normal form?  Every nonkey column must depend on the entire
primary key.
================================================================================
42. What is 3rd normal form? (another explanation than #1)  No nonkey column
depends on another nonkey column.
================================================================================

43. What is 4th normal form?  Fourth normal form forbids independent
one-to-many relationships between primary key columns and nonkey columns.
================================================================================
44. What is 5th normal form?  Fifth normal form breaks tables into the
smallest possible pieces in order to eliminate all redundancy within a
table. Tables normalized to this extent consist of little more than the
primary key.

45. How to find out top n salary from a employee table?
================================================================================

46.If we will modify a function , which is defined in package even though stored package will be valid ?

================================================================================

47.How do you define public and private procedure in oracle?

================================================================================

48.If same kind of logic we put in function as well as procedure then which one will be faster?

================================================================================

49.If we deleted any rows in table and commited then is it possible to retrieve the deleted data?

================================================================================

50. While handiling excecption if we have written “When others then” first before other exception handler then what will happen?

================================================================================
51. What is sql injection attack???
<form method="post" action="http://testasp.vulnweb.com/login.asp">
<input name="tfUName" type="text" id="tfUName">
<input name="tfUPass" type="password" id="tfUPass">
</form>
The easiest way for the login.asp to work is by building a database query that looks like this:
SELECT id
FROM logins
WHERE username = '$username'
AND password = '$password’
If the variables $username and $password are requested directly from the user's input, this can easily be compromised. Suppose that we gave "Joe" as a username and that the following string was provided as a password: anything' OR 'x'='x
SELECT id
FROM logins
WHERE username = 'Joe'
AND password = 'anything' OR 'x'='x'
As the inputs of the web application are not properly sanitised, the use of the single quotes has turned the WHERE SQL command into a two-component clause.
The 'x'='x' part guarantees to be true regardless of what the first part contains.
This will allow the attacker to bypass the login form without actually knowing a valid username / password combination!

LAG and LEAD Analytical Functions

The LAG and LEAD analytic functions were introduced in 8.1.6 to give access to multiple rows within a table, without the need for a self-join.

Introduction
LAG
LEAD
Related articles.

Analytic Functions
RANK, DENSE_RANK, FIRST and LAST Analytic Functions
FIRST_VALUE and LAST_VALUE Analytic Functions
LISTAGG Analystic Function in 11g Release 2
Top-N Queries

Introduction

Both LAG and LEAD functions have the same usage, as shown below.

LAG  (value_expression [,offset] [,default]) OVER ([query_partition_clause] order_by_clause)
LEAD (value_expression [,offset] [,default]) OVER ([query_partition_clause] order_by_clause)
value_expression - Can be a column or a built-in function, except for other analytic functions.
offset - The number of rows preceeding/following the current row, from which the data is to be retrieved. The default value is 1.
default - The value returned if the offset is outside the scope of the window. The default value is NULL.
Looking at the EMP table, we query the data in salary (SAL) order.

SELECT empno,
       ename,
       job,
       sal
FROM   emp
ORDER BY sal;

     EMPNO ENAME      JOB              SAL
---------- ---------- --------- ----------
      7369 SMITH      CLERK            800
      7900 JAMES      CLERK            950
      7876 ADAMS      CLERK           1100
      7521 WARD       SALESMAN        1250
      7654 MARTIN     SALESMAN        1250
      7934 MILLER     CLERK           1300
      7844 TURNER     SALESMAN        1500
      7499 ALLEN      SALESMAN        1600
      7782 CLARK      MANAGER         2450
      7698 BLAKE      MANAGER         2850
      7566 JONES      MANAGER         2975
      7788 SCOTT      ANALYST         3000
      7902 FORD       ANALYST         3000
      7839 KING       PRESIDENT       5000


LAG

The LAG function is used to access data from a previous row. The following query returns the salary from the previous row to calculate the difference between the salary of the current row and that of the previous row. Notice that the ORDER BY of the LAG function is used to order the data by salary.

SELECT empno,
       ename,
       job,
       sal,
       LAG(sal, 1, 0) OVER (ORDER BY sal) AS sal_prev,
       sal - LAG(sal, 1, 0) OVER (ORDER BY sal) AS sal_diff
FROM   emp;

     EMPNO ENAME      JOB              SAL   SAL_PREV   SAL_DIFF
---------- ---------- --------- ---------- ---------- ----------
      7369 SMITH      CLERK            800          0        800
      7900 JAMES      CLERK            950        800        150
      7876 ADAMS      CLERK           1100        950        150
      7521 WARD       SALESMAN        1250       1100        150
      7654 MARTIN     SALESMAN        1250       1250          0
      7934 MILLER     CLERK           1300       1250         50
      7844 TURNER     SALESMAN        1500       1300        200
      7499 ALLEN      SALESMAN        1600       1500        100
      7782 CLARK      MANAGER         2450       1600        850
      7698 BLAKE      MANAGER         2850       2450        400
      7566 JONES      MANAGER         2975       2850        125
      7788 SCOTT      ANALYST         3000       2975         25
      7902 FORD       ANALYST         3000       3000          0
      7839 KING       PRESIDENT       5000       3000       2000


LEAD

The LEAD function is used to return data from the next row. The following query returns the salary from the next row to calulate the difference between the salary of the current row and the following row.

SELECT empno,
       ename,
       job,
       sal,
       LEAD(sal, 1, 0) OVER (ORDER BY sal) AS sal_next,
       LEAD(sal, 1, 0) OVER (ORDER BY sal) - sal AS sal_diff
FROM   emp;

     EMPNO ENAME      JOB              SAL   SAL_NEXT   SAL_DIFF
---------- ---------- --------- ---------- ---------- ----------
      7369 SMITH      CLERK            800        950        150
      7900 JAMES      CLERK            950       1100        150
      7876 ADAMS      CLERK           1100       1250        150
      7521 WARD       SALESMAN        1250       1250          0
      7654 MARTIN     SALESMAN        1250       1300         50
      7934 MILLER     CLERK           1300       1500        200
      7844 TURNER     SALESMAN        1500       1600        100
      7499 ALLEN      SALESMAN        1600       2450        850
      7782 CLARK      MANAGER         2450       2850        400
      7698 BLAKE      MANAGER         2850       2975        125
      7566 JONES      MANAGER         2975       3000         25
      7788 SCOTT      ANALYST         3000       3000          0
      7902 FORD       ANALYST         3000       5000       2000
      7839 KING       PRESIDENT       5000          0      -5000