SQL Queries Interview Questions
SQL Queries Interview Questions
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 examples on 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.
CREATE TABLE PRODUCTS ( PRODUCT_ID PRODUCT_NAME ); CREATE TABLE SALES ( SALE_ID PRODUCT_ID YEAR Quantity PRICE ); INTEGER, INTEGER, INTEGER, INTEGER, INTEGER INTEGER, 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 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;
SALE_ID PRODUCT_ID YEAR QUANTITY PRICE -------------------------------------1 2 3 4 5 6 7 8 9 100 100 100 200 200 200 300 300 300 2010 2011 2012 2010 2011 2012 2010 2011 2012 25 16 8 10 15 20 20 18 20 5000 5000 5000 9000 9000 9000 7000 7000 7000
Here 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 increasing every 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
PRODUCT_NAME YEAR QUANTITY QUAN_PREV_YEAR ----------------------------------------Nokia Nokia Nokia IPhone IPhone IPhone Samsung Samsung Samsung 2012 2011 2010 2012 2011 2010 2012 2011 2010 8 16 25 20 15 10 20 18 20 16 25 0 15 10 0 18 20 0
Here 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 years 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 P.PRODUCT_NAME, S.QUANTITY LEAD(S.QUANTITY,1,0) OVER ( PARTITION BY P.PRODUCT_ID ORDER BY S.YEAR DESC ) QUAN_DIFF FROM PRODUCTS P, SALES S WHERE )A GROUP BY PRODUCT_NAME HAVING MIN(QUAN_DIFF) >= 0; P.PRODUCT_ID = S.PRODUCT_ID
PRODUCT_NAME -----------IPhone
2. 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.
PRODUCT_NAME -----------LG
SELECT P.PRODUCT_NAME FROM WHERE PRODUCTS P P.PRODUCT_ID NOT IN (SELECT DISTINCT PRODUCT_ID FROM SALES);
PRODUCT_NAME -----------LG
WHERE
PRODUCT_NAME -----------LG
3. 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_NAME FROM PRODUCTS P, SALES S_2012, SALES S_2011 WHERE AND AND AND AND P.PRODUCT_ID = S_2012.PRODUCT_ID S_2012.YEAR = 2012 S_2011.YEAR = 2011 S_2012.PRODUCT_ID = S_2011.PRODUCT_ID S_2012.QUANTITY < S_2011.QUANTITY;
PRODUCT_NAME ------------
Nokia
4. 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, YEAR FROM ( SELECT P.PRODUCT_NAME, S.YEAR, RANK() OVER ( PARTITION BY S.YEAR ORDER BY S.QUANTITY DESC ) RNK FROM PRODUCTS P, SALES S WHERE ) A WHERE RNK = 1; P.PRODUCT_ID = S.PRODUCT_ID
5. 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_SALES FROM PRODUCTS P LEFT OUTER JOIN SALES S ON (P.PRODUCT_ID = S.PRODUCT_ID)
GROUP BY P.PRODUCT_NAME;
SELECT P.PRODUCT_NAME, S.YEAR, S.QUANTITY FROM PRODUCTS P, SALES S WHERE AND P.PRODUCT_ID = S.PRODUCT_ID S.QUANTITY > (SELECT AVG(QUANTITY) FROM SALES S1 WHERE S1.PRODUCT_ID = S.PRODUCT_ID );
Samsung Samsung
2012 2010
20 20
2. 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 2011 2012 10 15 20 20 18 20 9000 9000 9000 7000 7000 7000
Solution: 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 S_S.PRICE FROM PRODUCTS P_I, SALES S_I, PRODUCTS P_S, SALES S_S WHERE P_I.PRODUCT_ID = S_I.PRODUCT_ID IPHONE_PRICE, SAM_PRICE
3. 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 price in 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_RATIO FROM PRODUCTS P, SALES S WHERE (P.PRODUCT_ID = S.PRODUCT_ID);
PRODUCT_NAME YEAR
RATIO
----------------------------IPhone IPhone IPhone Nokia Nokia 2011 2012 2010 2012 2011 0.333333333 0.444444444 0.222222222 0.163265306 0.326530612
4. 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
Solution: 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.YEAR FROM PRODUCTS P, SALES S WHERE (P.PRODUCT_ID = S.PRODUCT_ID)
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_2012 FROM PRODUCTS P, SALES S WHERE (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
GROUP BY YEAR;
YEAR
NUM_PRODUCTS
2. Write a query to display only friday dates from Jan, 2000 to till now? Solution:
SELECT
C_DATE, TO_CHAR(C_DATE,'DY')
3. Write a query to duplicate each row based on the value in the repeat column? The input table data looks like as below
Now 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
Solution:
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?
S M I L E
Solution:
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:
Solution2:
Here 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 arefriends of friends. The output should look as
Name, Friend_of_Firend ---------------------sam, sam, sam, sam, ram jhon vijay anand
Solution:
SELECT
FROM
WHERE
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 asfriends 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
Solution:
SELECT
FROM
f1.name = 'sam' f1.friend_name = f2.name 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 products based on the quantity sold without using the row_number analytical function? The source data looks as
Products, quantity_sold, year ----------------------------A, B, C, D, E, F, G, H, I, J, L, M, 200, 155, 455, 620, 135, 390, 999, 810, 910, 109, 260, 580, 2009 2009 2009 2009 2009 2009 2010 2010 2010 2010 2010 2010
Solution:
SELECT
products,
4. This is an extension to the problem 3. Write a query to produce the same output using row_number analytical function? Solution:
SELECT
quantity_sold, year, row_number() OVER( ORDER BY quantity_sold DESC) r from )A WHERE r <= 5; t
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
FROM ( SELECT products, quantity_sold, year, row_number() OVER( PARTITION BY year ORDER BY quantity_sold DESC) r
from )A
WHERE r <= 5;
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;
PRODUCT_ID PRODUCT_NAME
----------------------100 200 300 400 500 600 Nokia IPhone Samsung LG BlackBerry Motorola
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
CREATE TABLE TGT_PRODUCTS ( PRODUCT_ID PRODUCT_NAME INSERT_DATE ); INTEGER, VARCHAR2(30), 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_PRODUCTS SELECT PRODUCT_ID, PRODUCT_NAME, SYSDATE INSERT_DATE FROM ( SELECT PRODUCT_ID,
PRODUCT_NAME FROM PRODUCTS S WHERE NOT EXISTS ( SELECT 1 FROM WHERE ) ORDER BY DBMS_RANDOM.VALUE --Random number generator in oracle. )A WHERE ROWNUM <= 2; TGT_PRODUCTS T T.PRODUCT_ID = S.PRODUCT_ID
The last step is to delete the products from the table which are loaded 30 days back.
DELETE FROM TGT_PRODUCTS WHERE INSERT_DATE < SYSDATE - 30;
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;
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 LOAD_FLAG ); INTEGER, 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;
AUDIO MAGAZINE
2 3
0 0
Here 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);
WHERE PRIORITY = ( SELECT DECODE( PRIORITY,(SELECT MAX(PRIORITY) FROM CONTENTS_LKP) ,1 , PRIORITY+1) FROM WHERE ); CONTENTS_LKP CONTENT_TYPE = (SELECT DISTINCT CONTENT_TYPE FROM TGT_CONTENTS)