You are on page 1of 14

1.

Which is the subset of SQL commands used to manipulate Oracle Database structures, including tables?
Data Definition Language (DDL)

2.

What operator performs pattern matching?

LIKE operator
3.

What operator tests column for the absence of data?


IS NULL operator

4.

Which command executes the contents of a specified file?


START <filename> or @<filename>

5.

What is the parameter substitution symbol used with INSERT INTO command?
&

6.

Which command displays the SQL command in the SQL buffer, and then executes it?
RUN

7.

What are the wildcards used for pattern matching?


_ for single character substitution and % for multi-character substitution

8.

State true or false. EXISTS, SOME, ANY are operators in SQL.


True

9.

State true or false. !=, <>, ^= all denote the same operation.
True

10. What are the privileges that can be granted on a table by a user to others?
Insert, update, delete, select, references, index, execute, alter, all
11. What command is used to get back the privileges offered by the GRANT command?
REVOKE
12. Which system tables contain information on privileges granted and privileges obtained?
USER_TAB_PRIVS_MADE, USER_TAB_PRIVS_RECD
13. Which system table contains information on constraints on all the tables created?
USER_CONSTRAINTS
14.

TRUNCATE TABLE EMP;


DELETE FROM EMP;

Will the outputs of the above two commands differ?


Both will result in deleting all the rows in the table EMP.
15. What is the difference between TRUNCATE and DELETE commands?
TRUNCATE is a DDL command whereas DELETE is a DML command. Hence DELETE operation can be rolled
back, but TRUNCATE operation cannot be rolled back. WHERE clause can be used with DELETE and not with
TRUNCATE.
16. What command is used to create a table by copying the structure of another table?
Answer :
CREATE TABLE .. AS SELECT command

Explanation :
To copy only the structure, the WHERE clause of the SELECT command should contain a FALSE statement as
in the following.
CREATE TABLE NEWTABLE AS SELECT * FROM EXISTINGTABLE WHERE 1=2;
If the WHERE condition is true, then all the rows or rows satisfying the condition will be copied to the new table.
17. What will be the output of the following query?

SELECT REPLACE(TRANSLATE(LTRIM(RTRIM('!! ATHEN !!','!'), '!'), 'AN',


'**'),'*','TROUBLE') FROM DUAL;
TROUBLETHETROUBLE
18. What will be the output of the following query?
SELECT DECODE(TRANSLATE('A','1234567890','1111111111'), '1','YES', 'NO' );
Answer :
NO
Explanation :
The query checks whether a given string is a numerical digit.
19. What does the following query do?
SELECT SAL + NVL(COMM,0) FROM EMP;
This displays the total salary of all employees. The null values in the commission column will be replaced by 0
and added to salary.

20. Which date function is used to find the difference between two dates?
MONTHS_BETWEEN
21. Why does the following command give a compilation error?
DROP TABLE &TABLE_NAME;
Variable names should start with an alphabet. Here the table name starts with an '&' symbol.
22. What is the advantage of specifying WITH GRANT OPTION in the GRANT command?
The privilege receiver can further grant the privileges he/she has obtained from the owner to any other user.
23. What is the use of the DROP option in the ALTER TABLE command?
It is used to drop constraints specified on the table.
24. What is the value of comm and sal after executing the following query if the initial value of sal is 10000?
UPDATE EMP SET SAL = SAL + 1000, COMM = SAL*0.1;
sal = 11000, comm = 1000
25. What is the use of DESC in SQL?
Answer :
DESC has two purposes. It is used to describe a schema as well as to retrieve rows from table in descending
order.
Explanation :
The query SELECT * FROM EMP ORDER BY ENAME DESC will display the output sorted on ENAME in
descending order.
26. What is the use of CASCADE CONSTRAINTS?
When this clause is used with the DROP command, a parent table can be dropped even when a child table
exists.

27. Which function is used to find the largest integer less than or equal to a specific value?
FLOOR
28. What is the output of the following query?
SELECT TRUNC(1234.5678,-2) FROM DUAL;
1200

SQL QUERIES
I. SCHEMAS
Table 1 : STUDIES
PNAME (VARCHAR), SPLACE (VARCHAR), COURSE (VARCHAR), CCOST (NUMBER)
Table 2 : SOFTWARE
PNAME (VARCHAR), TITLE (VARCHAR), DEVIN (VARCHAR), SCOST (NUMBER), DCOST (NUMBER), SOLD
(NUMBER)
Table 3 : PROGRAMMER
PNAME (VARCHAR), DOB (DATE), DOJ (DATE), SEX (CHAR), PROF1 (VARCHAR), PROF2 (VARCHAR), SAL
(NUMBER)
LEGEND :
PNAME Programmer Name, SPLACE Study Place, CCOST Course Cost, DEVIN Developed in, SCOST
Software Cost, DCOST Development Cost, PROF1 Proficiency 1
QUERIES :

Find out the selling cost average for packages developed in Oracle.

Display the names, ages and experience of all programmers.

Display the names of those who have done the PGDCA course.

What is the highest number of copies sold by a package?

Display the names and date of birth of all programmers born in April.

Display the lowest course fee.

How many programmers have done the DCA course.

How much revenue has been earned through the sale of packages developed in C.

Display the details of software developed by Rakesh.

How many programmers studied at Pentafour.

Display the details of packages whose sales crossed the 5000 mark.

Find out the number of copies which should be sold in order to recover the development cost of each
package.

Display the details of packages for which the development cost has been recovered.

What is the price of costliest software developed in VB?

How many packages were developed in Oracle ?

How many programmers studied at PRAGATHI?

How many programmers paid 10000 to 15000 for the course?

What is the average course fee?

Display the details of programmers knowing C.

How many programmers know either C or Pascal?

How many programmers dont know C and C++?

How old is the oldest male programmer?

What is the average age of female programmers?

Calculate the experience in years for each programmer and display along with their names in
descending order.

Who are the programmers who celebrate their birthdays during the current month?

How many female programmers are there?

What are the languages known by the male programmers?

What is the average salary?

How many people draw 5000 to 7500?

Display the details of those who dont know C, C++ or Pascal.

Display the costliest package developed by each programmer.

Produce the following output for all the male programmers

Programmer
Mr. Arvind has 15 years of experience
KEYS:

SELECT AVG(SCOST) FROM SOFTWARE WHERE DEVIN = 'ORACLE';

SELECT

PNAME,TRUNC(MONTHS_BETWEEN(SYSDATE,DOB)/12)

"AGE",

TRUNC(MONTHS_BETWEEN(SYSDATE,DOJ)/12) "EXPERIENCE" FROM PROGRAMMER;

SELECT PNAME FROM STUDIES WHERE COURSE = 'PGDCA';

SELECT MAX(SOLD) FROM SOFTWARE;

SELECT PNAME, DOB FROM PROGRAMMER WHERE DOB LIKE '%APR%';

SELECT MIN(CCOST) FROM STUDIES;

SELECT COUNT(*) FROM STUDIES WHERE COURSE = 'DCA';

SELECT SUM(SCOST*SOLD-DCOST) FROM SOFTWARE GROUP BY DEVIN HAVING DEVIN = 'C';

SELECT * FROM SOFTWARE WHERE PNAME = 'RAKESH';

SELECT * FROM STUDIES WHERE SPLACE = 'PENTAFOUR';

SELECT * FROM SOFTWARE WHERE SCOST*SOLD-DCOST > 5000;

SELECT CEIL(DCOST/SCOST) FROM SOFTWARE;

SELECT * FROM SOFTWARE WHERE SCOST*SOLD >= DCOST;

SELECT MAX(SCOST) FROM SOFTWARE GROUP BY DEVIN HAVING DEVIN = 'VB';

SELECT COUNT(*) FROM SOFTWARE WHERE DEVIN = 'ORACLE';

SELECT COUNT(*) FROM STUDIES WHERE SPLACE = 'PRAGATHI';

SELECT COUNT(*) FROM STUDIES WHERE CCOST BETWEEN 10000 AND 15000;

SELECT AVG(CCOST) FROM STUDIES;

SELECT * FROM PROGRAMMER WHERE PROF1 = 'C' OR PROF2 = 'C';

SELECT * FROM PROGRAMMER WHERE PROF1 IN ('C','PASCAL') OR PROF2 IN ('C','PASCAL');

SELECT * FROM PROGRAMMER WHERE PROF1 NOT IN ('C','C++') AND PROF2 NOT IN ('C','C++');

SELECT TRUNC(MAX(MONTHS_BETWEEN(SYSDATE,DOB)/12)) FROM PROGRAMMER WHERE SEX =


'M';

SELECT TRUNC(AVG(MONTHS_BETWEEN(SYSDATE,DOB)/12)) FROM PROGRAMMER WHERE SEX = 'F';

SELECT PNAME, TRUNC(MONTHS_BETWEEN(SYSDATE,DOJ)/12) FROM PROGRAMMER ORDER BY


PNAME DESC;

SELECT PNAME FROM PROGRAMMER WHERE TO_CHAR(DOB,'MON') = TO_CHAR(SYSDATE,'MON');

SELECT COUNT(*) FROM PROGRAMMER WHERE SEX = 'F';

SELECT DISTINCT(PROF1) FROM PROGRAMMER WHERE SEX = 'M';

SELECT AVG(SAL) FROM PROGRAMMER;

SELECT COUNT(*) FROM PROGRAMMER WHERE SAL BETWEEN 5000 AND 7500;

SELECT * FROM PROGRAMMER WHERE PROF1 NOT IN ('C','C++','PASCAL') AND PROF2 NOT IN ('C','C+
+','PASCAL');

SELECT PNAME,TITLE,SCOST FROM SOFTWARE WHERE SCOST IN (SELECT MAX(SCOST) FROM


SOFTWARE GROUP BY PNAME);

32.SELECT 'Mr.' || PNAME || ' - has ' || TRUNC(MONTHS_BETWEEN(SYSDATE,DOJ)/12) || ' years of experience'
Programmer FROM PROGRAMMER WHERE SEX = 'M' UNION SELECT 'Ms.' || PNAME || ' - has ' || TRUNC
(MONTHS_BETWEEN (SYSDATE,DOJ)/12) || ' years of experience' Programmer FROM PROGRAMMER WHERE
SEX = 'F';

II . SCHEMA :
Table 1 : DEPT
DEPTNO (NOT NULL , NUMBER(2)), DNAME (VARCHAR2(14)),
LOC (VARCHAR2(13)
Table 2 : EMP
EMPNO (NOT NULL , NUMBER(4)), ENAME (VARCHAR2(10)),
JOB (VARCHAR2(9)), MGR (NUMBER(4)), HIREDATE (DATE),
SAL (NUMBER(7,2)), COMM (NUMBER(7,2)), DEPTNO (NUMBER(2))
MGR is the empno of the employee whom the employee reports to. DEPTNO is a foreign key.
QUERIES
1.

List all the employees who have at least one person reporting to them.

2.

List the employee details if and only if more than 10 employees are present in department no 10.

3.

List the name of the employees with their immediate higher authority.

4.

List all the employees who do not manage any one.

5.

List the employee details whose salary is greater than the lowest salary of an employee belonging to

deptno 20.
6.

List the details of the employee earning more than the highest paid manager.

7.

List the highest salary paid for each job.

8.

Find the most recently hired employee in each department.

9.

In which year did most people join the company? Display the year and the number of employees.

10. Which department has the highest annual remuneration bill?


11. Write a query to display a * against the row of the most recently hired employee.
12. Write a correlated sub-query to list out the employees who earn more than the average salary of their
department.
13. Find the nth maximum salary.
14. Select the duplicate records (Records, which are inserted, that already exist) in the EMP table.
15. Write a query to list the length of service of the employees (of the form n years and m months).
KEYS:

1.

SELECT DISTINCT(A.ENAME) FROM EMP A, EMP B WHERE A.EMPNO = B.MGR; or SELECT ENAME FROM

EMP WHERE EMPNO IN (SELECT MGR FROM EMP);


2.

SELECT * FROM EMP WHERE DEPTNO IN (SELECT DEPTNO FROM EMP GROUP BY DEPTNO HAVING

COUNT(EMPNO)>10 AND DEPTNO=10);


3.

SELECT A.ENAME "EMPLOYEE", B.ENAME "REPORTS TO" FROM EMP A, EMP B WHERE A.MGR=B.EMPNO;

4.

SELECT * FROM EMP WHERE EMPNO IN ( SELECT EMPNO FROM EMP MINUS SELECT MGR FROM EMP);

5.

SELECT * FROM EMP WHERE SAL > ( SELECT MIN(SAL) FROM EMP GROUP BY DEPTNO HAVING

DEPTNO=20);
6.

SELECT * FROM EMP WHERE SAL > ( SELECT MAX(SAL) FROM EMP GROUP BY JOB HAVING JOB =

'MANAGER' );
7.

SELECT JOB, MAX(SAL) FROM EMP GROUP BY JOB;

8.

SELECT * FROM EMP WHERE (DEPTNO, HIREDATE) IN (SELECT DEPTNO, MAX(HIREDATE) FROM EMP

GROUP BY DEPTNO);
9.

SELECT TO_CHAR(HIREDATE,'YYYY') "YEAR", COUNT(EMPNO) "NO. OF EMPLOYEES" FROM EMP GROUP

BY TO_CHAR(HIREDATE,'YYYY') HAVING COUNT(EMPNO) = (SELECT MAX(COUNT(EMPNO)) FROM EMP GROUP


BY TO_CHAR(HIREDATE,'YYYY'));
10. SELECT DEPTNO, LPAD(SUM(12*(SAL+NVL(COMM,0))),15) "COMPENSATION" FROM EMP GROUP BY
DEPTNO HAVING SUM( 12*(SAL+NVL(COMM,0))) = (SELECT MAX(SUM(12*(SAL+NVL(COMM,0)))) FROM EMP
GROUP BY DEPTNO);
11. SELECT ENAME, HIREDATE, LPAD('*',8) "RECENTLY HIRED" FROM EMP WHERE HIREDATE = (SELECT
MAX(HIREDATE) FROM EMP) UNION SELECT ENAME NAME, HIREDATE, LPAD(' ',15) "RECENTLY HIRED" FROM
EMP WHERE HIREDATE != (SELECT MAX(HIREDATE) FROM EMP);
12. SELECT ENAME,SAL FROM EMP E WHERE SAL > (SELECT AVG(SAL) FROM EMP F WHERE E.DEPTNO =
F.DEPTNO);
13. SELECT ENAME, SAL FROM EMP A WHERE &N = (SELECT COUNT (DISTINCT(SAL)) FROM EMP B WHERE
A.SAL<=B.SAL);
14. SELECT * FROM EMP A WHERE A.EMPNO IN (SELECT EMPNO FROM EMP GROUP BY EMPNO HAVING
COUNT(EMPNO)>1) AND A.ROWID!=MIN (ROWID));
15. SELECT ENAME "EMPLOYEE",TO_CHAR(TRUNC(MONTHS_BETWEEN(SYSDATE,HIREDATE)/12))||' YEARS '||
TO_CHAR(TRUNC(MOD(MONTHS_BETWEEN (SYSDATE, HIREDATE),12)))||' MONTHS ' "LENGTH OF SERVICE"
FROM EMP;
SQL is a language for accessing and manipulating database standardized by ANSI. To be successful with databasecentric applications (which includes most of the applications Data Warehousing domain), one must be strong enough in
SQL. In this article, we will learn more about SQL by breaking the subject in the form of several question-answer sessions
commonly asked in Interviewes.
SET UP OF SAMPLE DATA FOR PRACTICING SQL
For the purpose of our demonstration, we will primarily use two database tables with just a few records - EMPLOYEE

table and DEPT table. EMPLOYEE table will contain 10 records pertaining to 10 employees with funny sounding names of
an imaginary organization and DEPT or Department table will contain 5 departments of that organization. Click here to
download the DDL/INSERT statements for this data if you want to practice the below SQLs in your personal computer

Contents of these tables are not same with Oracle emp and dept tables!!

What is the difference between inner and outer join? Explain with
example.
Inner Join
Inner join is the most common type of Join which is used to combine the rows from two tables and create a result set
containing only such records that are present in both the tables based on the joining condition (predicate).

Inner join returns rows when there is at least one match in both tables
If none of the record matches between two tables, then INNER JOIN will return a NULL set. Below is an example of
INNER JOIN and the resulting set.

SELECT dept.name DEPARTMENT, emp.name EMPLOYEE


FROM DEPT dept, EMPLOYEE emp
WHERE emp.dept_id = dept.id

Department Employee
HR
Inno
HR
Privy
Engineering Robo
Engineering Hash
Engineering Anno
Engineering Darl
Marketing Pete
Marketing Meme
Sales
Tomiti
Sales
Bhuti
Outer Join

Outer Join can be full outer or single outer


Outer Join, on the other hand, will return matching rows from both tables as well as any unmatched rows from one or both
the tables (based on whether it is single outer or full outer join respectively).
Notice in our record set that there is no employee in the department 5 (Logistics). Because of this if we perform inner join,
then Department 5 does not appear in the above result. However in the below query we perform an outer join (dept left
outer join emp), and we can see this department.

SELECT dept.name DEPARTMENT, emp.name EMPLOYEE


FROM DEPT dept, EMPLOYEE emp
WHERE dept.id = emp.dept_id (+)

Department Employee
HR
Inno
HR
Privy
Engineering Robo
Engineering Hash
Engineering Anno
Engineering Darl

Marketing
Marketing
Sales
Sales
Logistics

Pete
Meme
Tomiti
Bhuti

The (+) sign on the emp side of the predicate indicates that emp is the outer table here. The above SQL can be
alternatively written as below (will yield the same result as above):

SELECT dept.name DEPARTMENT, emp.name EMPLOYEE


FROM DEPT dept LEFT OUTER JOIN EMPLOYEE emp
ON dept.id = emp.dept_id

What is the difference between JOIN and UNION?


SQL JOIN allows us to lookup records on other table based on the given conditions between two tables. For example, if
we have the department ID of each employee, then we can use this department ID of the employee table to join with the
department ID of department table to lookup department names.
UNION operation allows us to add 2 similar data sets to create resulting data set that contains all the data from the source
data sets. Union does not require any condition for joining. For example, if you have 2 employee tables with same
structure, you can UNION them to create one result set that will contain all the employees from both of the tables.

SELECT * FROM EMP1


UNION
SELECT * FROM EMP2;

What is the difference between UNION and UNION ALL?


UNION and UNION ALL both unify for add two structurally similar data sets, but UNION operation returns only the unique
records from the resulting data set whereas UNION ALL will return all the rows, even if one or more rows are duplicated to
each other.
In the following example, I am choosing exactly the same employee from the emp table and performing UNION and
UNION ALL. Check the difference in the result.

SELECT * FROM EMPLOYEE WHERE ID = 5


UNION ALL
SELECT * FROM EMPLOYEE WHERE ID = 5

ID MGR_ID DEPT_ID NAME SAL


DOJ
5.0 2.0
2.0
Anno 80.0 01-Feb-2012
5.0 2.0
2.0
Anno 80.0 01-Feb-2012
SELECT * FROM EMPLOYEE WHERE ID = 5
UNION
SELECT * FROM EMPLOYEE WHERE ID = 5

ID MGR_ID DEPT_ID NAME SAL


DOJ
5.0 2.0
2.0
Anno 80.0 01-Feb-2012

What is the difference between WHERE clause and HAVING


clause?
WHERE and HAVING both filters out records based on one or more conditions. The difference is, WHERE clause can
only be applied on a static non-aggregated column whereas we will need to use HAVING for aggregated columns.
To understand this, consider this example.
Suppose we want to see only those departments where department ID is greater than 3. There is no aggregation
operation and the condition needs to be applied on a static field. We will use WHERE clause here:

SELECT * FROM DEPT WHERE ID > 3

ID NAME
4 Sales

Logistics

Next, suppose we want to see only those Departments where Average salary is greater than 80. Here the condition is
associated with a non-static aggregated information which is average of salary. We will need to use HAVING clause
here:

SELECT dept.name DEPARTMENT, avg(emp.sal) AVG_SAL


FROM DEPT dept, EMPLOYEE emp
WHERE dept.id = emp.dept_id (+)
GROUP BY dept.name
HAVING AVG(emp.sal) > 80

DEPARTMENT AVG_SAL
Engineering
90

As you see above, there is only one department (Engineering) where average salary of employees is greater than 80.

What is the difference among UNION, MINUS and INTERSECT?


UNION combines the results from 2 tables and eliminates duplicate records from the result set.
MINUS operator when used between 2 tables, gives us all the rows from the first table except the rows which are present
in the second table.
INTERSECT operator returns us only the matching or common rows between 2 result sets.
To understand these operators, lets see some examples. We will use two different queries to extract data from our emp
table and then we will perform UNION, MINUS and INTERSECT operations on these two sets of data.

UNION

SELECT * FROM EMPLOYEE WHERE ID = 5


UNION
SELECT * FROM EMPLOYEE WHERE ID = 6

ID MGR_ID DEPT_ID NAME SAL


DOJ
5 2
2.0
Anno 80.0 01-Feb-2012
6 2
2.0
Darl
80.0 11-Feb-2012
MINUS

SELECT * FROM EMPLOYEE


MINUS
SELECT * FROM EMPLOYEE WHERE ID > 2

ID MGR_ID DEPT_ID NAME SAL


DOJ
1
2
Hash 100.0 01-Jan-2012
2 1
2
Robo 100.0 01-Jan-2012
INTERSECT

SELECT * FROM EMPLOYEE WHERE ID IN (2, 3, 5)


INTERSECT
SELECT * FROM EMPLOYEE WHERE ID IN (1, 2, 4, 5)

ID MGR_ID DEPT_ID NAME SAL


DOJ
5 2
2
Anno 80.0 01-Feb-2012
2 1
2
Robo 100.0 01-Jan-2012

What is Self Join and why is it required?


Self Join is the act of joining one table with itself.

Self Join is often very useful to convert a hierarchical structure into a flat
structure
In our employee table example above, we have kept the manager ID of each employee in the same row as that of the
employee. This is an example of how a hierarchy (in this case employee-manager hierarchy) is stored in the RDBMS
table. Now, suppose if we need to print out the names of the manager of each employee right beside the employee, we
can use self join. See the example below:

SELECT e.name EMPLOYEE, m.name MANAGER


FROM EMPLOYEE e, EMPLOYEE m
WHERE e.mgr_id = m.id (+)

EMPLOYEE MANAGER
Pete
Hash
Darl
Hash
Inno
Hash
Robo
Hash
Tomiti
Robo
Anno
Robo
Privy
Robo
Meme
Pete
Bhuti
Tomiti
Hash

The only reason we have performed a left outer join here (instead of INNER JOIN) is we have one employee in this table
without a manager (employee ID = 1). If we perform inner join, this employee will not show-up.

How can we transpose a table using SQL (changing rows to


column or vice-versa) ?
The usual way to do it in SQL is to use CASE statement or DECODE statement.

How to generate row number in SQL Without ROWNUM


Generating a row number that is a running sequence of numbers for each row is not easy using plain SQL. In fact, the
method I am going to show below is not very generic either. This method only works if there is at least one unique column
in the table. This method will also work if there is no single unique column, but collection of columns that is unique.
Anyway, here is the query:

SELECT name, sal, (SELECT COUNT(*)


i.name) row_num
FROM EMPLOYEE o
order by row_num

FROM EMPLOYEE i WHERE o.name >=

NAME SAL ROW_NUM


Anno 80 1
Bhuti 60 1
Darl
80 1
Hash 100 1
Inno
50 1
Meme 60 1
Pete
70 1
Privy 50 1
Robo 100 1
Tomiti 70 1

The column that is used in the row number generation logic is called sort key. Here sort key is name column. For this

technique to work, the sort key needs to be unique. We have chosen the column name because this column happened
to be unique in our Employee table. If it was not unique but some other collection of columns was, then we could have
used those columns as our sort key (by concatenating those columns to form a single sort key).
Also notice how the rows are sorted in the result set. We have done an explicit sorting on the row_num column, which
gives us all the row numbers in the sorted order. But notice that name column is also sorted (which is probably the reason
why this column is referred as sort-key). If you want to change the order of the sorting from ascending to descending, you
will need to change >= sign to <= in the query.
As I said before, this method is not very generic. This is why many databases already implement other methods to
achieve this. For example, in Oracle database, every SQL result set contains a hidden column called ROWNUM. We can
just explicitly select ROWNUM to get sequence numbers.

How to select first 5 records from a table?


This question, often asked in many interviews, does not make any sense to me. The problem here is how do you define
which record is first and which is second. Which record is retrieved first from the database is not deterministic. It depends
on many uncontrollable factors such as how database works at that moment of execution etc. So the question should
really be how to select any 5 records from the table? But whatever it is, here is the solution: In Oracle,

SELECT *
FROM EMP
WHERE ROWNUM <= 5;
In SQL Server,

SELECT TOP 5 * FROM EMP;


Generic solution,
I believe a generic solution can be devised for this problem if and only if there exists at least one distinct column in the
table. For example, in our EMP table ID is distinct. We can use that distinct column in the below way to come up with a
generic solution of this question that does not require database specific functions such as ROWNUM, TOP etc.

SELECT name
FROM EMPLOYEE o
WHERE (SELECT count(*) FROM EMPLOYEE i WHERE i.name < o.name) < 5

name
Inno
Anno
Darl
Meme
Bhuti

I have taken name column in the above example since name is happened to be unique in this table. I could very well
take ID column as well.
In this example, if the chosen column was not distinct, we would have got more than 5 records returned in our output.
Do you have a better solution to this problem? If yes, post your solution in the comment.

What is the difference between ROWNUM pseudo column and


ROW_NUMBER() function?
ROWNUM is a pseudo column present in Oracle database returned result set prior to ORDER BY being evaluated. So
ORDER BY ROWNUM does not work.
ROW_NUMBER() is an analytical function which is used in conjunction to OVER() clause wherein we can specify ORDER
BY and also PARTITION BY columns.
Suppose if you want to generate the row numbers in the order of ascending employee salaries for example, ROWNUM
will not work. But you may use ROW_NUMBER() OVER() like shown below:

SELECT name, sal, row_number() over(order by sal desc) rownum_by_sal


FROM EMPLOYEE o

name
Hash
Robo
Anno
Darl
Tomiti
Pete
Bhuti
Meme
Inno
Privy

Sal ROWNUM_BY_SAL
100 1
100 2
80 3
80 4
70 5
70 6
60 7
60 8
50 9
50 10

What are the differences among ROWNUM, RANK and


DENSE_RANK?
ROW_NUMBER assigns contiguous, unique numbers from 1.. N to a result set.
RANK does not assign unique numbersnor does it assign contiguous numbers. If two records tie for second place, no
record will be assigned the 3rd rank as no one came in third, according to RANK. See below:

SELECT name, sal, rank() over(order by sal desc) rank_by_sal


FROM EMPLOYEE o

name
Hash
Robo
Anno
Darl
Tomiti
Pete
Bhuti
Meme
Inno
Privy

Sal RANK_BY_SAL
100 1
100 1
80 3
80 3
70 5
70 5
60 7
60 7
50 9
50 9

DENSE_RANK, like RANK, does not assign unique numbers, but it does assign contiguous numbers. Even though two
records tied for second place, there is a third-place record. See below:

SELECT name, sal, dense_rank() over(order by sal desc) dense_rank_by_sal


FROM EMPLOYEE o

name
Hash
Robo
Anno
Darl
Tomiti
Pete
Bhuti
Meme
Inno
Privy

Sal DENSE_RANK_BY_SAL
100 1
100 1
80 2
80 2
70 3
70 3
60 4
60 4
50 5
50 5

The Scenarios of Enterprise Information Management with SAP (Integration)


Leave a reply
EIM is a buzz word in the IT industry right now. Everyone wants to make
better use of data (Information) available to make intelligent decisions. But
todays complex IT environment leaves data in different disparate systems;
the data should be integrated in proper manner to make it usable. Below are
some of major scenarios (needs) of data integration.

The data usage in any organization can be broadly divided as Operational and
Analytical.

Operational Usage: This is to support daily operations. Maintaining proper


Operational data is critical to viability of any business.

Analytics/Reporting Usage: Aggregation of data from multiple systems


collected over time to give insight into business.

1. Data Integration between Disparate systems in Same Company: - Say for


example your financial data is maintained by SAP FICO, sales data is in SAP
CRM and Inventory is in some 3rd party legacy inventory management
system. The sales orders you completed in the CRM should be reflected in
3rd party system to update the inventory. This is required for both
Operational and Analytics usage.

Real time: If this data integration need is Real time then SAP Net weaver
PI will be used for this purpose.

Batch load: For batch loading of this data in periodical time intervals we use
SAP Data Services.

2.
Reporting / Analytics: Data from multiple time periods and multiple
divisions will be summarized and loaded into a data warehouse like SAP
HANA. Then reports will be generated on top of this data to give insights to
companies operations for a period of time. Examples of the reports are
Monthly sales report by Zip code. SAP dataservices is default tool for this

purpose.

3.Data Integration between Different Companies / Migration to different


systems :- Suppose company A is acquiring Company B, or Company A is
changing its ERP from Oracle to SAP in these kind of scenarios the data
should be migrated for old location to new location. And data may need to be
transformed in-between to suit the structure of new location. This process will
be done using SAP Data Services.

You might also like