A subquery is a SELECT statement which is used in another SELECT statement. Subqueries are very useful when you need to select rows from a table with a condition that depends on the data of the table itself. You can use the subquery in the SQL clauses including WHERE clause, HAVING clause, FROM clause etc.
The subquery can also be referred as nested SELECT, sub SELECT or inner SELECT. In general, the subquery executes first and its output is used in the main query or outer query.
Types of Sub queries:
There are two types of subqueries in oracle:
The subquery can also be referred as nested SELECT, sub SELECT or inner SELECT. In general, the subquery executes first and its output is used in the main query or outer query.
Types of Sub queries:
There are two types of subqueries in oracle:
- Single Row Subqueries: The subquery returns only one row. Use single row comparison operators like =, > etc while doing comparisions.
- Multiple Row Subqueries: The subquery returns more than one row. Use multiple row comparison operators like IN, ANY, ALL in the comparisons.
Single Row Subquery Examples
1. Write a query to find the salary of employees whose salary is greater than the salary of employee whose id is 100?
SELECT EMPLOYEE_ID, SALARYFROM EMPLOYEESWHERE SALARY > ( SELECT SALARY FROM EMPLOYEES WHERE EMPLOYEED_ID = 100 )2. Write a query to find the employees who all are earningthe highest salary?
SELECT EMPLOYEE_ID, SALARYFROM EMPLOYEESWHERE SALARY = ( SELECT MAX(SALARY) FROM EMPLOYEES )3. Write a query to find the departments in which the least salary is greater than the highest salary in the department of id 200?
SELECT DEPARTMENT_ID, MIN(SALARY)FROM EMPLOYEESGROUP BY DEPARTMENT_IDHAVING MIN(SALARY) > ( SELECT MAX(SALARY) FROM EMPLOYEES WHERE DEPARTMENT_ID = 200 )Multiple Row Subquery Examples
1. Write a query to find the employees whose salary is equal to the salary of at least one employee in department of id 300?
SELECT EMPLOYEE_ID, SALARYFROM EMPLOYEESWHERE SALARY IN ( SELECT SALARY FROM EMPLOYEES WHERE DEPARTMENT_ID = 300 )2. Write a query to find the employees whose salary is greater than at least on employee in department of id 500?
SELECT EMPLOYEE_ID, SALARYFROM EMPLOYEESWHERE SALARY > ANY ( SELECT SALARY FROM EMPLOYEES WHERE DEPARTMENT_ID = 500 )3. Write a query to find the employees whose salary is less than the salary of all employees in department of id 100?
SELECT EMPLOYEE_ID, SALARYFROM EMPLOYEESWHERE SALARY < ALL ( SELECT SALARY FROM EMPLOYEES WHERE DEPARTMENT_ID = 100 )4. Write a query to find the employees whose manager and department should match with the employee of id 20 or 30?
SELECT EMPLOYEE_ID, MANAGER_ID, DEPARTMENT_IDFROM EMPLOYEESWHERE (MANAGER_ID,DEPARTMENT_ID) IN ( SELECT MANAGER_ID, DEPARTMENT_ID FROM EMPLOYEES WHERE EMPLOYEE_ID IN (20,30) )5. Write a query to get the department name of an employee?
SELECT EMPLOYEE_ID, DEPARTMENT_ID, (SELECT DEPARTMENT_NAME FROM DEPARTMENTS D WHERE D.DEPARTMENT_ID = E.DEPARTMENT_ID )FROM EMPLOYEES ECorrelated SubQueries Examples
Correlated sub query is used for row by row processing. The sub query is executed for each row of the main query.
1. Write a query to find the highest earning employee in each department?
SELECT DEPARTMENT_ID, EMPLOYEE_ID, SALARYFROM EMPLOYEES E_0WHERE 1 = ( SELECT COUNT(DISTINCT SALARY) FROM EMPLOYEES E_I WHERE E_O.DEPARTMENT_ID = E_I.DEPARTMENT_ID AND E_O.SALARY <= E_I.SALARY )2. Write a query to list the department names which have at lease one employee?
SELECT DEPARTMENT_ID, DEPARTMENT_NAMEFROM DEPARTMENTS DWHERE EXISTS ( SELECT 1 FROM EMPLOYEES E WHERE E.DEPARTMENT_ID = D.DEPARTMENT_ID)3. Write a query to find the departments which do not have employees at all?
SELECT DEPARTMENT_ID, DEPARTMENT_NAMEFROM DEPARTMENTS DWHERE NOT EXISTS ( SELECT 1 FROM EMPLOYEES E WHERE E.DEPARTMENT_ID = D.DEPARTMENT_ID) SQL Queries Interview Questions - Oracle Analytical Functions Part 1
Analytic functions compute aggregate values based on a group of rows. They differ from aggregate functions in that they return multiple rows for each group. Most of the SQL developers won't use analytical functions because of its cryptic syntax or uncertainty about its logic of operation. Analytical functions saves lot of time in writing queries and gives better performance when compared to native SQL.
Before starting with the interview questions, we will see the difference between the aggregate functions and analytic functions with an example. I have used SALES TABLE as an example to solve the interview questions. Please create the below sales table in your oracle database.
Before starting with the interview questions, we will see the difference between the aggregate functions and analytic functions with an example. I have used SALES TABLE as an example to solve the interview questions. Please create the below sales table in your oracle database.
CREATE TABLE SALES( SALE_ID INTEGER, PRODUCT_ID INTEGER, YEAR INTEGER, Quantity INTEGER, PRICE INTEGER); INSERT INTO SALES VALUES ( 1, 100, 2008, 10, 5000);INSERT INTO SALES VALUES ( 2, 100, 2009, 12, 5000);INSERT INTO SALES VALUES ( 3, 100, 2010, 25, 5000);INSERT INTO SALES VALUES ( 4, 100, 2011, 16, 5000);INSERT INTO SALES VALUES ( 5, 100, 2012, 8, 5000); INSERT INTO SALES VALUES ( 6, 200, 2010, 10, 9000);INSERT INTO SALES VALUES ( 7, 200, 2011, 15, 9000);INSERT INTO SALES VALUES ( 8, 200, 2012, 20, 9000);INSERT INTO SALES VALUES ( 9, 200, 2008, 13, 9000);INSERT INTO SALES VALUES ( 10,200, 2009, 14, 9000); INSERT INTO SALES VALUES ( 11, 300, 2010, 20, 7000);INSERT INTO SALES VALUES ( 12, 300, 2011, 18, 7000);INSERT INTO SALES VALUES ( 13, 300, 2012, 20, 7000);INSERT INTO SALES VALUES ( 14, 300, 2008, 17, 7000);INSERT INTO SALES VALUES ( 15, 300, 2009, 19, 7000);COMMIT; SELECT * FROM SALES; SALE_ID PRODUCT_ID YEAR QUANTITY PRICE--------------------------------------1 100 2008 10 50002 100 2009 12 50003 100 2010 25 50004 100 2011 16 50005 100 2012 8 50006 200 2010 10 90007 200 2011 15 90008 200 2012 20 90009 200 2008 13 900010 200 2009 14 900011 300 2010 20 700012 300 2011 18 700013 300 2012 20 700014 300 2008 17 700015 300 2009 19 7000 Difference Between Aggregate and Analytic Functions:
Q. Write a query to find the number of products sold in each year?
The SQL query Using Aggregate functions is
SELECT Year, COUNT(1) CNTFROM SALESGROUP BY YEAR; YEAR CNT---------2009 32010 32011 32008 32012 3The SQL query Using Aanalytic functions is
SELECT SALE_ID, PRODUCT_ID, Year, QUANTITY, PRICE, COUNT(1) OVER (PARTITION BY YEAR) CNTFROM SALES; SALE_ID PRODUCT_ID YEAR QUANTITY PRICE CNT------------------------------------------9 200 2008 13 9000 31 100 2008 10 5000 314 300 2008 17 7000 315 300 2009 19 7000 32 100 2009 12 5000 310 200 2009 14 9000 311 300 2010 20 7000 36 200 2010 10 9000 33 100 2010 25 5000 312 300 2011 18 7000 34 100 2011 16 5000 37 200 2011 15 9000 313 300 2012 20 7000 35 100 2012 8 5000 38 200 2012 20 9000 3From the outputs, you can observe that the aggregate functions return only one row per group whereas analytic functions keeps all the rows in the gorup. Using the aggregate functions, the select clause contains only the columns specified in group by clause and aggregate functions whereas in analytic functions you can specify all the columns in the table.
The PARTITION BY clause is similar to GROUP By clause, it specifies the window of rows that the analytic funciton should operate on.
I hope you got some basic idea about aggregate and analytic functions. Now lets start with solving the Interview Questions on Oracle Analytic Functions.
1. Write a SQL query using the analytic function to find the total sales(QUANTITY) of each product?
Solution:
SUM analytic function can be used to find the total sales. The SQL query is
SELECT PRODUCT_ID, QUANTITY, SUM(QUANTITY) OVER( PARTITION BY PRODUCT_ID ) TOT_SALESFROM SALES; PRODUCT_ID QUANTITY TOT_SALES-----------------------------100 12 71100 10 71100 25 71100 16 71100 8 71200 15 72200 10 72200 20 72200 14 72200 13 72300 20 94300 18 94300 17 94300 20 94300 19 942. Write a SQL query to find the cumulative sum of sales(QUANTITY) of each product? Here first sort the QUANTITY in ascendaing order for each product and then accumulate the QUANTITY.
Cumulative sum of QUANTITY for a product = QUANTITY of current row + sum of QUANTITIES all previous rows in that product.
Solution:
We have to use the option "ROWS UNBOUNDED PRECEDING" in the SUM analytic function to get the cumulative sum. The SQL query to get the ouput is
SELECT PRODUCT_ID, QUANTITY, SUM(QUANTITY) OVER( PARTITION BY PRODUCT_ID ORDER BY QUANTITY ASC ROWS UNBOUNDED PRECEDING) CUM_SALESFROM SALES; PRODUCT_ID QUANTITY CUM_SALES-----------------------------100 8 8100 10 18100 12 30100 16 46100 25 71200 10 10200 13 23200 14 37200 15 52200 20 72300 17 17300 18 35300 19 54300 20 74300 20 94The ORDER BY clause is used to sort the data. Here theROWS UNBOUNDED PRECEDING option specifies that the SUM analytic function should operate on the current row and the pervious rows processed.
3. Write a SQL query to find the sum of sales of current row and previous 2 rows in a product group? Sort the data on sales and then find the sum.
Solution:
The sql query for the required ouput is
SELECT PRODUCT_ID, QUANTITY, SUM(QUANTITY) OVER( PARTITION BY PRODUCT_ID ORDER BY QUANTITY DESC ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) CALC_SALESFROM SALES; PRODUCT_ID QUANTITY CALC_SALES------------------------------100 25 25100 16 41100 12 53100 10 38100 8 30200 20 20200 15 35200 14 49200 13 42200 10 37300 20 20300 20 40300 19 59300 18 57300 17 54The ROWS BETWEEN clause specifies the range of rows to consider for calculating the SUM.
4. Write a SQL query to find the Median of sales of a product?
Solution:
The SQL query for calculating the median is
SELECT PRODUCT_ID, QUANTITY, PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY QUANTITY ASC) OVER (PARTITION BY PRODUCT_ID) MEDIANFROM SALES; PRODUCT_ID QUANTITY MEDIAN--------------------------100 8 12100 10 12100 12 12100 16 12100 25 12200 10 14200 13 14200 14 14200 15 14200 20 14300 17 19300 18 19300 19 19300 20 19300 20 195. Write a SQL query to find the minimum sales of a product without using the group by clause.
Solution:
The SQL query is
SELECT PRODUCT_ID, YEAR, QUANTITYFROM (SELECT PRODUCT_ID, YEAR, QUANTITY, ROW_NUMBER() OVER(PARTITION BY PRODUCT_ID ORDER BY QUANTITY ASC) MIN_SALE_RANKFROM SALES) WHERE MIN_SALE_RANK = 1; PRODUCT_ID YEAR QUANTITY------------------------100 2012 8200 2010 10300 2008 17 SQL Queries Interview Questions - Oracle Part 1
As a database developer, writing SQL queries, PLSQL code is part of daily life. Having a good knowledge on SQL is really important. Here i am posting some practical exampleson SQL queries.
To solve these interview questions on SQL queries you have to create the products, sales tables in your oracle database. The "Create Table", "Insert" statements are provided below.
To solve these interview questions on SQL queries you have to create the products, sales tables in your oracle database. The "Create Table", "Insert" statements are provided below.
CREATE TABLE PRODUCTS( PRODUCT_ID INTEGER, PRODUCT_NAME VARCHAR2(30));CREATE TABLE SALES( SALE_ID INTEGER, PRODUCT_ID INTEGER, YEAR INTEGER, Quantity INTEGER, PRICE INTEGER); INSERT INTO PRODUCTS VALUES ( 100, 'Nokia');INSERT INTO PRODUCTS VALUES ( 200, 'IPhone');INSERT INTO PRODUCTS VALUES ( 300, 'Samsung');INSERT INTO PRODUCTS VALUES ( 400, 'LG'); INSERT INTO SALES VALUES ( 1, 100, 2010, 25, 5000);INSERT INTO SALES VALUES ( 2, 100, 2011, 16, 5000);INSERT INTO SALES VALUES ( 3, 100, 2012, 8, 5000);INSERT INTO SALES VALUES ( 4, 200, 2010, 10, 9000);INSERT INTO SALES VALUES ( 5, 200, 2011, 15, 9000);INSERT INTO SALES VALUES ( 6, 200, 2012, 20, 9000);INSERT INTO SALES VALUES ( 7, 300, 2010, 20, 7000);INSERT INTO SALES VALUES ( 8, 300, 2011, 18, 7000);INSERT INTO SALES VALUES ( 9, 300, 2012, 20, 7000);COMMIT;The products table contains the below data.
SELECT * FROM PRODUCTS; PRODUCT_ID PRODUCT_NAME-----------------------100 Nokia200 IPhone300 SamsungThe sales table contains the following data.
SELECT * FROM SALES; SALE_ID PRODUCT_ID YEAR QUANTITY PRICE--------------------------------------1 100 2010 25 50002 100 2011 16 50003 100 2012 8 50004 200 2010 10 90005 200 2011 15 90006 200 2012 20 90007 300 2010 20 70008 300 2011 18 70009 300 2012 20 7000Here Quantity is the number of products sold in each year. Price is the sale price of each product.
I hope you have created the tables in your oracle database. Now try to solve the below SQL queries.
1. Write a SQL query to find the products which have continuous increase in sales every year?
Solution:
Here “Iphone” is the only product whose sales are increasingevery year.
STEP1: First we will get the previous year sales for each product. The SQL query to do this is
SELECT P.PRODUCT_NAME, S.YEAR, S.QUANTITY, LEAD(S.QUANTITY,1,0) OVER ( PARTITION BY P.PRODUCT_ID ORDER BY S.YEAR DESC ) QUAN_PREV_YEARFROM PRODUCTS P, SALES SWHERE P.PRODUCT_ID = S.PRODUCT_ID; PRODUCT_NAME YEAR QUANTITY QUAN_PREV_YEAR-----------------------------------------Nokia 2012 8 16Nokia 2011 16 25Nokia 2010 25 0IPhone 2012 20 15IPhone 2011 15 10IPhone 2010 10 0Samsung 2012 20 18Samsung 2011 18 20Samsung 2010 20 0Here the lead analytic function will get the quantity of a product in its previous year.
STEP2: We will find the difference between the quantities of a product with its previous year’s quantity. If this difference is greater than or equal to zero for all the rows, then the product is a constantly increasing in sales. The final query to get the required result is
SELECT PRODUCT_NAMEFROM(SELECT P.PRODUCT_NAME, S.QUANTITY - LEAD(S.QUANTITY,1,0) OVER ( PARTITION BY P.PRODUCT_ID ORDER BY S.YEAR DESC ) QUAN_DIFFFROM PRODUCTS P, SALES SWHERE P.PRODUCT_ID = S.PRODUCT_ID)AGROUP BY PRODUCT_NAMEHAVING MIN(QUAN_DIFF) >= 0; PRODUCT_NAME------------IPhone2. Write a SQL query to find the products which does not have sales at all?
Solution:
“LG” is the only product which does not have sales at all. This can be achieved in three ways.
Method1: Using left outer join.
SELECT P.PRODUCT_NAMEFROM PRODUCTS P LEFT OUTER JOIN SALES SON (P.PRODUCT_ID = S.PRODUCT_ID);WHERE S.QUANTITY IS NULL PRODUCT_NAME------------LGMethod2: Using the NOT IN operator.
SELECT P.PRODUCT_NAMEFROM PRODUCTS PWHERE P.PRODUCT_ID NOT IN (SELECT DISTINCT PRODUCT_ID FROM SALES); PRODUCT_NAME------------LGMethod3: Using the NOT EXISTS operator.
SELECT P.PRODUCT_NAMEFROM PRODUCTS PWHERE NOT EXISTS (SELECT 1 FROM SALES S WHERE S.PRODUCT_ID = P.PRODUCT_ID); PRODUCT_NAME------------LG3. Write a SQL query to find the products whose sales decreased in 2012 compared to 2011?
Solution:
Here Nokia is the only product whose sales decreased in year 2012 when compared with the sales in the year 2011. The SQL query to get the required output is
SELECT P.PRODUCT_NAMEFROM PRODUCTS P, SALES S_2012, SALES S_2011WHERE P.PRODUCT_ID = S_2012.PRODUCT_IDAND S_2012.YEAR = 2012AND S_2011.YEAR = 2011AND S_2012.PRODUCT_ID = S_2011.PRODUCT_IDAND S_2012.QUANTITY < S_2011.QUANTITY; PRODUCT_NAME------------Nokia4. Write a query to select the top product sold in each year?
Solution:
Nokia is the top product sold in the year 2010. Similarly, Samsung in 2011 and IPhone, Samsung in 2012. The query for this is
SELECT PRODUCT_NAME, YEARFROM(SELECT P.PRODUCT_NAME, S.YEAR, RANK() OVER ( PARTITION BY S.YEAR ORDER BY S.QUANTITY DESC ) RNKFROM PRODUCTS P, SALES SWHERE P.PRODUCT_ID = S.PRODUCT_ID) AWHERE RNK = 1; PRODUCT_NAME YEAR--------------------Nokia 2010Samsung 2011IPhone 2012Samsung 20125. Write a query to find the total sales of each product.?
Solution:
This is a simple query. You just need to group by the data on PRODUCT_NAME and then find the sum of sales.
SELECT P.PRODUCT_NAME, NVL( SUM( S.QUANTITY*S.PRICE ), 0) TOTAL_SALESFROM PRODUCTS P LEFT OUTER JOIN SALES SON (P.PRODUCT_ID = S.PRODUCT_ID)GROUP BY P.PRODUCT_NAME; PRODUCT_NAME TOTAL_SALES---------------------------LG 0IPhone 405000Samsung 406000Nokia 245000SQL Queries Interview Questions - Oracle Part 2
This is continuation to my previous post, SQL Queries Interview Questions - Oracle Part 1 , Where i have used PRODUCTSand SALES tables as an example. Here also i am using the same tables. So, just take a look at the tables by going through that link and it will be easy for you to understand the questionsmentioned here.
Solve the below examples by writing SQL queries.
1. Write a query to find the products whose quantity sold in a year should be greater than the average quantity sold across all the years?
Solution:
This can be solved with the help of correlated query. The SQL query for this is
Solve the below examples by writing SQL queries.
1. Write a query to find the products whose quantity sold in a year should be greater than the average quantity sold across all the years?
Solution:
This can be solved with the help of correlated query. The SQL query for this is
SELECT P.PRODUCT_NAME, S.YEAR, S.QUANTITYFROM PRODUCTS P, SALES SWHERE P.PRODUCT_ID = S.PRODUCT_IDAND S.QUANTITY > (SELECT AVG(QUANTITY) FROM SALES S1 WHERE S1.PRODUCT_ID = S.PRODUCT_ID ); PRODUCT_NAME YEAR QUANTITY--------------------------Nokia 2010 25IPhone 2012 20Samsung 2012 20Samsung 2010 202. Write a query to compare the products sales of "IPhone" and "Samsung" in each year? The output should look like as
YEAR IPHONE_QUANT SAM_QUANT IPHONE_PRICE SAM_PRICE---------------------------------------------------2010 10 20 9000 70002011 15 18 9000 70002012 20 20 9000 7000Solution:
By using self-join SQL query we can get the required result. The required SQL query is
SELECT S_I.YEAR, S_I.QUANTITY IPHONE_QUANT, S_S.QUANTITY SAM_QUANT, S_I.PRICE IPHONE_PRICE, S_S.PRICE SAM_PRICEFROM PRODUCTS P_I, SALES S_I, PRODUCTS P_S, SALES S_SWHERE P_I.PRODUCT_ID = S_I.PRODUCT_IDAND P_S.PRODUCT_ID = S_S.PRODUCT_IDAND P_I.PRODUCT_NAME = 'IPhone'AND P_S.PRODUCT_NAME = 'Samsung'AND S_I.YEAR = S_S.YEAR3. Write a query to find the ratios of the sales of a product?
Solution:
The ratio of a product is calculated as the total sales pricein a particular year divide by the total sales price across all years. Oracle provides RATIO_TO_REPORT analytical function for finding the ratios. The SQL query is
SELECT P.PRODUCT_NAME, S.YEAR, RATIO_TO_REPORT(S.QUANTITY*S.PRICE) OVER(PARTITION BY P.PRODUCT_NAME ) SALES_RATIOFROM PRODUCTS P, SALES SWHERE (P.PRODUCT_ID = S.PRODUCT_ID); PRODUCT_NAME YEAR RATIO-----------------------------IPhone 2011 0.333333333IPhone 2012 0.444444444IPhone 2010 0.222222222Nokia 2012 0.163265306Nokia 2011 0.326530612Nokia 2010 0.510204082Samsung 2010 0.344827586Samsung 2012 0.344827586Samsung 2011 0.3103448284. In the SALES table quantity of each product is stored in rows for every year. Now write a query to transpose the quantity for each product and display it in columns? The output should look like as
PRODUCT_NAME QUAN_2010 QUAN_2011 QUAN_2012------------------------------------------IPhone 10 15 20Samsung 20 18 20Nokia 25 16 8Solution:
Oracle 11g provides a pivot function to transpose the row data into column data. The SQL query for this is
SELECT * FROM(SELECT P.PRODUCT_NAME, S.QUANTITY, S.YEARFROM PRODUCTS P, SALES SWHERE (P.PRODUCT_ID = S.PRODUCT_ID))APIVOT ( MAX(QUANTITY) AS QUAN FOR (YEAR) IN (2010,2011,2012));If you are not running oracle 11g database, then use the below query for transposing the row data into column data.
SELECT P.PRODUCT_NAME, MAX(DECODE(S.YEAR,2010, S.QUANTITY)) QUAN_2010, MAX(DECODE(S.YEAR,2011, S.QUANTITY)) QUAN_2011, MAX(DECODE(S.YEAR,2012, S.QUANTITY)) QUAN_2012FROM PRODUCTS P, SALES SWHERE (P.PRODUCT_ID = S.PRODUCT_ID)GROUP BY P.PRODUCT_NAME;5. Write a query to find the number of products sold in each year?
Solution:
To get this result we have to group by on year and the find the count. The SQL query for this question is
SELECT YEAR, COUNT(1) NUM_PRODUCTSFROM SALESGROUP BY YEAR; YEAR NUM_PRODUCTS------------------2010 32011 32012 3SQL Queries Interview Questions - Oracle Part 3
Here I am providing Oracle SQL Query Interview Questions. If you find any bugs in the queries, Please do comment. So, that i will rectify them.
1. Write a query to generate sequence numbersfrom 1 to the specified number N?
Solution:
1. Write a query to generate sequence numbersfrom 1 to the specified number N?
Solution:
SELECT LEVEL FROM DUAL CONNECT BY LEVEL<=&N;2.Write a query to display only friday dates from Jan, 2000 to till now?
Solution:
SELECT C_DATE, TO_CHAR(C_DATE,'DY') FROM ( SELECT TO_DATE('01-JAN-2000','DD-MON-YYYY')+LEVEL-1 C_DATE FROM DUAL CONNECT BY LEVEL <= (SYSDATE - TO_DATE('01-JAN-2000','DD-MON-YYYY')+1) )WHERE TO_CHAR(C_DATE,'DY') = 'FRI'; 3.Write a query to duplicate each row based on the value in the repeat column? The input table data looks like as below
Products, Repeat
----------------A, 3B, 5C, 2Now in the output data, the product A should be repeated 3 times, B should be repeated 5 times and C should be repeated 2 times. The output will look like as below
Products, Repeat----------------A, 3A, 3A, 3B, 5B, 5B, 5B, 5B, 5C, 2C, 2Solution:
SELECT PRODUCTS, REPEAT FROM T, ( SELECT LEVEL L FROM DUAL CONNECT BY LEVEL <= (SELECT MAX(REPEAT) FROM T) ) A WHERE T.REPEAT >= A.L ORDER BY T.PRODUCTS;4.Write a query to display each letter of the word "SMILE" in a separate row?
SMILESolution:
SELECT SUBSTR('SMILE',LEVEL,1) A FROM DUAL CONNECT BY LEVEL <=LENGTH('SMILE');5. Convert the string "SMILE" to Ascii values? The output should look like as 83,77,73,76,69. Where 83 is the ascii value of S and so on.
The ASCII function will give ascii value for only one character. If you pass a string to the ascii function, it will give the ascii value of first letter in the string. Here i am providing two solutions to get the ascii values of string.
Solution1:
SELECT SUBSTR(DUMP('SMILE'),15) FROM DUAL;Solution2:
SELECT WM_CONCAT(A) FROM (SELECT ASCII(SUBSTR('SMILE',LEVEL,1)) A FROM DUAL CONNECT BY LEVEL <=LENGTH('SMILE') );SQL Queries Interview Questions - Oracle Part 4
1. Consider the following friends table as the source
Name, Friend_Name-----------------sam, ramsam, vamsivamsi, ramvamsi, jhonram, vijayram, anandHere ram and vamsi are friends of sam; ram and jhon are friends of vamsi and so on. Now write a query to find friends of friends of sam. For sam; ram,jhon,vijay and anand are friends of friends. The output should look as
Name, Friend_of_Firend----------------------sam, ramsam, jhonsam, vijaysam, anandSolution:
SELECT f1.name, f2.friend_name as friend_of_friendFROM friends f1, friends f2WHERE f1.name = 'sam'AND f1.friend_name = f2.name;2.This is an extension to the problem 1. In the output, you can see ram is displayed as friends of friends. This is because, ram is mutual friend of sam and vamsi. Now extend the above query to exclude mutual friends. The outuput should look as
Name, Friend_of_Friend----------------------sam, jhonsam, vijaysam, anandSolution:
SELECT f1.name, f2.friend_name as friend_of_friendFROM friends f1, friends f2WHERE f1.name = 'sam'AND f1.friend_name = f2.nameAND NOT EXISTS (SELECT 1 FROM friends f3 WHERE f3.name = f1.name AND f3.friend_name = f2.friend_name);3.Write a query to get the top 5 productsbased on the quantity sold without using the row_number analyticalfunction? The source data looks as
Products, quantity_sold, year-----------------------------A, 200, 2009B, 155, 2009C, 455, 2009D, 620, 2009E, 135, 2009F, 390, 2009G, 999, 2010H, 810, 2010I, 910, 2010J, 109, 2010L, 260, 2010M, 580, 2010Solution:
SELECT products, quantity_sold, yearFROM( SELECT products, quantity_sold, year, rownum r from t ORDER BY quantity_sold DESC)AWHERE r <= 5;4. This is an extension to the problem 3. Write a query to producethe same output using row_number analytical function?
Solution:
SELECT products, quantity_sold, yearFROM( SELECT products, quantity_sold, year, row_number() OVER( ORDER BY quantity_sold DESC) r from t)AWHERE r <= 5;5. This is an extension to the problem 3. write a query to get the top 5 products in each year based on the quantity sold?
Solution:
SELECT products, quantity_sold, yearFROM( SELECT products, quantity_sold, year, row_number() OVER( PARTITION BY year ORDER BY quantity_sold DESC) r from t)AWHERE r <= 5;SQL Query Interview Questions - Part 5
Write SQL queries for the below interviewquestions:
1. Load the below productstable into the target table.
CREATE TABLE PRODUCTS( PRODUCT_ID INTEGER, PRODUCT_NAME VARCHAR2(30)); INSERT INTO PRODUCTS VALUES ( 100, 'Nokia');INSERT INTO PRODUCTS VALUES ( 200, 'IPhone');INSERT INTO PRODUCTS VALUES ( 300, 'Samsung');INSERT INTO PRODUCTS VALUES ( 400, 'LG');INSERT INTO PRODUCTS VALUES ( 500, 'BlackBerry');INSERT INTO PRODUCTS VALUES ( 600, 'Motorola');COMMIT; SELECT * FROM PRODUCTS; PRODUCT_ID PRODUCT_NAME-----------------------100 Nokia200 IPhone300 Samsung400 LG500 BlackBerry600 MotorolaThe requirements for loading the target table are:
- Select only 2 products randomly.
- Do not select the products which are already loaded in the target table with in the last 30 days.
- Target table should always contain the products loaded in 30 days. It should not contain the products which are loaded prior to 30 days.
Solution:
First we will create a target table. The target table will have an additional column INSERT_DATE to know when a product is loaded into the target table. The target
table structure is
table structure is
CREATE TABLE TGT_PRODUCTS( PRODUCT_ID INTEGER, PRODUCT_NAME VARCHAR2(30), INSERT_DATE DATE);The next step is to pick 5 products randomly and then load into target table. While selecting check whether the products are there in the
INSERT INTO TGT_PRODUCTSSELECT PRODUCT_ID, PRODUCT_NAME, SYSDATE INSERT_DATEFROM(SELECT PRODUCT_ID, PRODUCT_NAMEFROM PRODUCTS SWHERE NOT EXISTS ( SELECT 1 FROM TGT_PRODUCTS T WHERE T.PRODUCT_ID = S.PRODUCT_ID )ORDER BY DBMS_RANDOM.VALUE --Random number generator in oracle.)AWHERE ROWNUM <= 2;The last step is to delete the products from the table which are loaded 30 days back.
DELETE FROM TGT_PRODUCTSWHERE INSERT_DATE < SYSDATE - 30;2. Load the below CONTENTS table into the target table.
CREATE TABLE CONTENTS( CONTENT_ID INTEGER, CONTENT_TYPE VARCHAR2(30)); INSERT INTO CONTENTS VALUES (1,'MOVIE');INSERT INTO CONTENTS VALUES (2,'MOVIE');INSERT INTO CONTENTS VALUES (3,'AUDIO');INSERT INTO CONTENTS VALUES (4,'AUDIO');INSERT INTO CONTENTS VALUES (5,'MAGAZINE');INSERT INTO CONTENTS VALUES (6,'MAGAZINE');COMMIT; SELECT * FROM CONTENTS; CONTENT_ID CONTENT_TYPE-----------------------1 MOVIE2 MOVIE3 AUDIO4 AUDIO5 MAGAZINE6 MAGAZINEThe requirements to load the target table are:
- Load only one content type at a time into the target table.
- The target table should always contain only one contain type.
- The loading of content types should follow round-robin style. First MOVIE, second AUDIO, Third MAGAZINE and again fourth Movie.
Solution:
First we will create a lookup table where we mention the priorities for the content types. The lookup table “Create Statement” and data is shown below.
CREATE TABLE CONTENTS_LKP( CONTENT_TYPE VARCHAR2(30), PRIORITY INTEGER, LOAD_FLAG INTEGER); INSERT INTO CONTENTS_LKP VALUES('MOVIE',1,1);INSERT INTO CONTENTS_LKP VALUES('AUDIO',2,0);INSERT INTO CONTENTS_LKP VALUES('MAGAZINE',3,0);COMMIT; SELECT * FROM CONTENTS_LKP; CONTENT_TYPE PRIORITY LOAD_FLAG---------------------------------MOVIE 1 1AUDIO 2 0MAGAZINE 3 0Here if LOAD_FLAG is 1, then it indicates which content type needs to be loaded into the target table. Only one content type will have LOAD_FLAG as 1. The other content types will have LOAD_FLAG as 0. The target table structure is same as the source table structure.
The second step is to truncate the target table before loading the data
TRUNCATE TABLE TGT_CONTENTS;The third step is to choose the appropriate content type from the lookup table to load the source data into the target table.
INSERT INTO TGT_CONTENTS
SELECT CONTENT_ID,
CONTENT_TYPE
FROM CONTENTS
WHERE CONTENT_TYPE = (SELECT CONTENT_TYPE FROM CONTENTS_LKP WHERE LOAD_FLAG=1);
The last step is to update the LOAD_FLAG of the Lookup table.
UPDATE CONTENTS_LKP
SET LOAD_FLAG = 0
WHERE LOAD_FLAG = 1;
UPDATE CONTENTS_LKP
SET LOAD_FLAG = 1
WHERE PRIORITY = (
SELECT DECODE( PRIORITY,(SELECT MAX(PRIORITY) FROM CONTENTS_LKP) ,1 , PRIORITY+1)
FROM CONTENTS_LKP
WHERE CONTENT_TYPE = (SELECT DISTINCT CONTENT_TYPE FROM TGT_CONTENTS)
);
No comments:
Post a Comment