Professional Documents
Culture Documents
Sub queries: A query embedded with in another query is called as sub query Types: 2 1. Single row sub query 2. Multi row sub query
SINGLE ROW SUB QUERY (OUTPUT THAT RETURNS ONLY ONE ROW) Q: Find out the persons those who got a salary more than Alexenders salary. Step 1 : First find out the Alexenders salary (By using sub query) Step 2 : Then find out the employees those who got a more salary than the Alexenders salary (Result of sub queries)
Step 2: SELECT FIRST_NAME,SALARY FROM EMPLOYEES WHERE SALARY > (SELECT SALARY FROM EMPLOYEES WHERE FIRST_NAME='Alexander' AND LAST_NAME='Hunold' );
(Result) >
MULTI ROW SUB QUERY (QUERY THAT RETURNS MORE THEN ONE ROW)
ALL - TAKE THE MAX VALUE FROM THE OUTPUT SELECT SALARY FROM EMPLOYEES WHERE FIRST_NAME='Alexander'
SELECT FIRST_NAME,SALARY FROM EMPLOYEES WHERE SALARY >ALL (SELECT SALARY FROM EMPLOYEES WHERE FIRST_NAME='Alexander');
>
ANY - TAKE THE MINIMUM VALUE FROM THE OUTPUT SELECT SALARY FROM EMPLOYEES WHERE FIRST_NAME='Alexander'
SELECT FIRST_NAME,SALARY FROM EMPLOYEES WHERE SALARY >ANY (SELECT SALARY FROM EMPLOYEES WHERE FIRST_NAME='Alexander');
. . .
. .
>
WE CAN USE SUB QUERY IN ALL THE CLAUSES EXCEPT ORDER BY AND GROUP BY.
SELECT FIRST_NAME,SALARY FROM EMPLOYEES WHERE SALARY >(SELECT SALARY FROM EMPLOYEES
WHERE FIRST_NAME='Neena');
USE OF SUB QUERY IN FROM CLAUSE INLINE VIEW -> NAMED SUBQUERY IN A FROM CLAUSE IS CALLED AS INLINE VIEW
SELECT * FROM (SELECT FIRST_NAME,SALARY FROM EMPLOYEES WHERE SALARY >ANY (SELECT SALARY FROM EMPLOYEES WHERE FIRST_NAME='Neena'))
EXCEPT ORDER BY AND GROUP BY WE CAN USE SUB QUERIES IN ALL THE CLAUSEES
Interview Questions
1. FIND OUT THE SECOND MAXIMUM SALERY FROM THE EMPLOYEES TABLE
STEP 1 : SELECT MAX(SALARY) FROM EMPLOYEES; THIS IS A QUERY TO FIND OUT THE MAXIMUM SALARY STEP 2 : Use the above query as a sub query and use the operator > or not in to find out the second maximum salary
SELECT MAX(SALARY) FROM EMPLOYEES WHERE SALARY NOT IN(SELECT MAX(SALARY) FROM EMPLOYEES);
Output :
2. Find out the nth maximum salary from the employees table.
Step 1 : First find out the distinct salary from the employees table by using the query select distinct salary from employees order by 1 desc; Step 2 : use the above query in the from CLAUSE (i.e. inline view) and use the rownum (with <=
SELECT MIN(SALARY) FROM (SELECT DISTINCT SALARY FROM EMPLOYEES ORDER BY SALARY DESC) WHERE ROWNUM <= 10; Result :