Search This Blog

Showing posts with label SQL Queries Interview Questions. Show all posts
Showing posts with label SQL Queries Interview Questions. Show all posts

Thursday, August 30, 2012

SQL Interview Questions Part-III

61. How to access the current value and next value from a sequence? Is it possible to access the current value in a session before accessing next value?
Sequence name CURRVAL, sequence name NEXTVAL. It is not possible. Only if you access next value in the session, current value can be accessed.

62.What is CYCLE/NO CYCLE in a Sequence?
CYCLE specifies that the sequence continue to generate values after reaching either maximum or minimum value. After pan-ascending sequence reaches its maximum value, it generates its minimum value. After a descending sequence reaches its minimum, it generates its maximum.
NO CYCLE specifies that the sequence cannot generate more values after reaching its maximum or minimum value.

63. What are the advantages of VIEW?
- To protect some of the columns of a table from other users.
- To hide complexity of a query.
- To hide complexity of calculations.

64. Can a view be updated/inserted/deleted? If Yes - under what conditions?
A View can be updated/deleted/inserted if it has only one base table if the view is based on columns from one or more tables then insert, update and delete is not possible.

65. If a view on a single base table is manipulated will the changes be reflected on the base table?
If changes are made to the tables and these tables are the base tables of a view, then the changes will be reference on the view.

66. Which of the following statements is true about implicit cursors?
1. Implicit cursors are used for SQL statements that are not named.
2. Developers should use implicit cursors with great care.
3. Implicit cursors are used in cursor for loops to handle data processing.
4. Implicit cursors are no longer a feature in Oracle.

67. Which of the following is not a feature of a cursor FOR loop?
1. Record type declaration.
2. Opening and parsing of SQL statements.
3. Fetches records from cursor.
4. Requires exit condition to be defined.

66. A developer would like to use referential datatype declaration on a variable. The variable name is EMPLOYEE_LASTNAME, and the corresponding table and column is EMPLOYEE, and LNAME, respectively. How would the developer define this variable using referential datatypes?
1. Use employee.lname%type.
2. Use employee.lname%rowtype.
3. Look up datatype for EMPLOYEE column on LASTNAME table and use that.
4. Declare it to be type LONG.

67. Which three of the following are implicit cursor attributes?
1. %found
2. %too_many_rows
3. %notfound
4. %rowcount
5. %rowtype

68. If left out, which of the following would cause an infinite loop to occur in a simple loop?
1. LOOP
2. END LOOP
3. IF-THEN
4. EXIT

69. Which line in the following statement will produce an error?
1. cursor action_cursor is
2. select name, rate, action
3. into action_record
4. from action_table;
5. There are no errors in this statement.

70. The command used to open a CURSOR FOR loop is
1. open
2. fetch
3. parse
4. None, cursor for loops handle cursor opening implicitly.

71. What happens when rows are found using a FETCH statement
1. It causes the cursor to close
2. It causes the cursor to open
3. It loads the current row values into variables
4. It creates the variables to hold the current row values

72. Read the following code:
10. CREATE OR REPLACE PROCEDURE find_cpt
11. (v_movie_id {Argument Mode} NUMBER, v_cost_per_ticket {argument mode} NUMBER)
12. IS
13. BEGIN
14. IF v_cost_per_ticket > 8.5 THEN
15. SELECT cost_per_ticket
16. INTO v_cost_per_ticket
17. FROM gross_receipt
18. WHERE movie_id = v_movie_id;
19. END IF;
20. END;
Which mode should be used for V_COST_PER_TICKET?
1. IN
2. OUT
3. RETURN
4. IN OUT
73. Read the following code:
22. CREATE OR REPLACE TRIGGER update_show_gross
23. {trigger information}
24. BEGIN
25. {additional code}
26. END;
The trigger code should only execute when the column, COST_PER_TICKET, is greater than $3. Which trigger information will you add?
1. WHEN (new.cost_per_ticket > 3.75)
2. WHEN (:new.cost_per_ticket > 3.75
3. WHERE (new.cost_per_ticket > 3.75)
4. WHERE (:new.cost_per_ticket > 3.75)

74. What is the maximum number of handlers processed before the PL/SQL block is exited when an exception occurs?
1. Only one
2. All that apply
3. All referenced
4. None

77. For which trigger timing can you reference the NEW and OLD qualifiers?
1. Statement and Row 2. Statement only 3. Row only 4. Oracle Forms trigger

78. Read the following code:
CREATE OR REPLACE FUNCTION get_budget(v_studio_id IN NUMBER)
RETURN number IS
v_yearly_budget NUMBER;
BEGIN
SELECT yearly_budget
INTO v_yearly_budget
FROM studio
WHERE id = v_studio_id;
RETURN v_yearly_budget;
END;
Which set of statements will successfully invoke this function within SQL*Plus?
1. VARIABLE g_yearly_budget NUMBER
EXECUTE g_yearly_budget := GET_BUDGET(11);
2. VARIABLE g_yearly_budget NUMBER
EXECUTE :g_yearly_budget := GET_BUDGET(11);
3. VARIABLE :g_yearly_budget NUMBER
EXECUTE :g_yearly_budget := GET_BUDGET(11);
4. VARIABLE g_yearly_budget NUMBER
31. CREATE OR REPLACE PROCEDURE update_theater
32. (v_name IN VARCHAR v_theater_id IN NUMBER) IS
33. BEGIN
34. UPDATE theater
35. SET name = v_name
36. WHERE id = v_theater_id;
37. END update_theater;

79. When invoking this procedure, you encounter the error:
ORA-000:Unique constraint(SCOTT.THEATER_NAME_UK) violated.
How should you modify the function to handle this error?
1. An user defined exception must be declared and associated
with the error code and handled in the EXCEPTION section.
2. Handle the error in EXCEPTION section by referencing the error
code directly.
3. Handle the error in the EXCEPTION section by referencing the UNIQUE_ERROR predefined exception.
4. Check for success by checking the value of SQL%FOUND immediately after the UPDATE statement.

80. Read the following code:
40. CREATE OR REPLACE PROCEDURE calculate_budget IS
41. v_budget studio.yearly_budget%TYPE;
42. BEGIN
43. v_budget := get_budget(11);
44. IF v_budget < 30000
45. THEN
46. set_budget(11,30000000);
47. END IF;
48. END; You are about to add an argument to CALCULATE_BUDGET.
What effect will this have?
1. The GET_BUDGET function will be marked invalid and must be recompiled before the next execution.
2. The SET_BUDGET function will be marked invalid and must be recompiled before the next execution.
3. Only the CALCULATE_BUDGET procedure needs to be recompiled.
4. All three procedures are marked invalid and must be recompiled.

81. Which procedure can be used to create a customized error message?
1. RAISE_ERROR
2. SQLERRM
3. RAISE_APPLICATION_ERROR
4. RAISE_SERVER_ERROR

82. The CHECK_THEATER trigger of the THEATER table has been disabled. Which command can you issue to enable this trigger?
1. ALTER TRIGGER check_theater ENABLE;
2. ENABLE TRIGGER check_theater;
3. ALTER TABLE check_theater ENABLE check_theater;
4. ENABLE check_theater;

83. What is the difference between Truncate and Delete interms of Referential Integrity?
DELETE removes one or more records in a table, checking referential Constraints (to see if there are dependent child records) and firing any DELETE triggers. In the order you are deleting (child first then parent) There will be no problems.
TRUNCATE removes ALL records in a table. It does not execute any triggers. Also, it
only checks for the existence (and status) of another foreign key Pointing to the
table. If one exists and is enabled, then you will get The following error. This
is true even if you do the child tables first.
ORA-02266: unique/primary keys in table referenced by enabled foreign keys
You should disable the foreign key constraints in the child tables before issuing
the TRUNCATE command, then re-enable them afterwards.


84. Examine this function:
61. CREATE OR REPLACE FUNCTION set_budget
62. (v_studio_id IN NUMBER, v_new_budget IN NUMBER) IS
63. BEGIN
64. UPDATE studio
65. SET yearly_budget = v_new_budget WHERE id = v_studio_id; IF SQL%FOUND THEN RETURN TRUEl; ELSE RETURN FALSE; END IF; COMMIT; END; Which code must be added to successfully compile this function?
1. Add RETURN right before the IS keyword.
2. Add RETURN number right before the IS keyword.
3. Add RETURN boolean right after the IS keyword.
4. Add RETURN boolean right before the IS keyword.

85. Under which circumstance must you recompile the package body after recompiling the package specification?
1. Altering the argument list of one of the package constructs
2. Any change made to one of the package constructs
3. Any SQL statement change made to one of the package constructs
4. Removing a local variable from the DECLARE section of one of the package constructs

86. Procedure and Functions are explicitly executed. This is different from a database trigger. When is a database trigger executed?
1. When the transaction is committed
2. During the data manipulation statement
3. When an Oracle supplied package references the trigger
4. During a data manipulation statement and when the transaction is committed

87. Which Oracle supplied package can you use to output values and messages from database triggers, stored procedures and functions within SQL*Plus?
1. DBMS_DISPLAY
2. DBMS_OUTPUT
3. DBMS_LIST
4. DBMS_DESCRIBE

88. What occurs if a procedure or function terminates with failure without being handled?
1. Any DML statements issued by the construct are still pending and can be committed or rolled back.
2. Any DML statements issued by the construct are committed
3. Unless a GOTO statement is used to continue processing within the BEGIN section,the construct terminates.
4. The construct rolls back any DML statements issued and returns the unhandled exception to the calling environment.

89. Examine this code
71. BEGIN
72. theater_pck.v_total_seats_sold_overall := theater_pck.get_total_for_year;
73. END; For this code to be successful, what must be true?
1. Both the V_TOTAL_SEATS_SOLD_OVERALL variable and the GET_TOTAL_FOR_YEAR function must exist only in the body of the THEATER_PCK package.
2. Only the GET_TOTAL_FOR_YEAR variable must exist in the specification of the THEATER_PCK package.
3. Only the V_TOTAL_SEATS_SOLD_OVERALL variable must exist in the specification of the THEATER_PCK package.
4. Both the V_TOTAL_SEATS_SOLD_OVERALL variable and the GET_TOTAL_FOR_YEAR function must exist in the specification of the THEATER_PCK package.

90. A stored function must return a value based on conditions that are determined at runtime. Therefore, the SELECT statement cannot be hard-coded and must be created dynamically when the function is executed. Which Oracle supplied package will enable this feature?
1. DBMS_DDL
2. DBMS_DML
3. DBMS_SYN
4. DBMS_SQL

91 How to implement ISNUMERIC function in SQL *Plus ? Method
1: Select length (translate(trim (column_name),'+-.0123456789',''))from dual; Will give you a zero if it is a number or greater than zero if not numeric (actually gives the count of non numeric characters) Method 2: select instr(translate('wwww','abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ','XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXX'),'X') FROM dual; It returns 0 if it is a number, 1 if it is not.

92 How to Select last N records from a Table? select * from (select rownum a, CLASS_CODE,CLASS_DESC from clm) where a > ( select (max(rownum)-10) from clm) Here N = 10
The following query has a Problem of performance in the execution of the following
query where the table ter.ter_master have 22231 records. So the results are obtained
after hours.
Cursor rem_master(brepno VARCHAR2) IS
select a.* from ter.ter_master a
where NOT a.repno in (select repno from ermast) and
(brepno = 'ALL' or a.repno > brepno)
Order by a.repno
What are steps required tuning this query to improve its performance?
-Have an index on TER_MASTER.REPNO and one on ERMAST.REPNO
-Be sure to get familiar with EXPLAIN PLAN. This can help you determine the execution
path that Oracle takes. If you are using Cost Based Optimizer mode, then be sure that
your statistics on TER_MASTER are up-to-date. -Also, you can change your SQL to:
SELECT a.*
FROM ter.ter_master a
WHERE NOT EXISTS (SELECT b.repno FROM ermast b
WHERE a.repno=b.repno) AND
(a.brepno = 'ALL' or a.repno > a.brepno)
ORDER BY a.repno;

93.

Examine this database trigger
CREATE OR REPLACE TRIGGER prevent_gross_modification
{additional trigger information}
BEGIN
IF TO_CHAR(sysdate, DY) = MON
THEN
RAISE_APPLICATION_ERROR(-20000,Gross receipts cannot be deleted on Monday);
END IF;
END;
This trigger must fire before each DELETE of the GROSS_RECEIPT table. It should fire only once for the entire DELETE statement. What additional information must you add?
1. BEFORE DELETE ON gross_receipt
2. AFTER DELETE ON gross_receipt
3. BEFORE (gross_receipt DELETE)
4. FOR EACH ROW DELETED FROM gross_receipt

SQL Queries Interview Questions

SQL Queries Interview Questions

Solve the below examples by writing SQL queries.

1. 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 20

Samsung 20 18 20

Nokia 25 16 8


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)

)A

PIVOT ( 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_2012

FROM PRODUCTS P,

SALES S

WHERE (P.PRODUCT_ID = S.PRODUCT_ID)

GROUP BY P.PRODUCT_NAME;


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 10 20 9000 7000

2011 15 18 9000 7000

2012 20 20 9000 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 IPHONE_PRICE,

S_S.PRICE SAM_PRICE

FROM PRODUCTS P_I,

SALES S_I,

PRODUCTS P_S,

SALES S_S

WHERE P_I.PRODUCT_ID = S_I.PRODUCT_ID

AND P_S.PRODUCT_ID = S_S.PRODUCT_ID

AND P_I.PRODUCT_NAME = 'IPhone'

AND P_S.PRODUCT_NAME = 'Samsung'

AND S_I.YEAR = S_S.YEAR


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 2011 0.333333333

IPhone 2012 0.444444444

IPhone 2010 0.222222222

Nokia 2012 0.163265306

Nokia 2011 0.326530612

Nokia 2010 0.510204082

Samsung 2010 0.344827586

Samsung 2012 0.344827586

Samsung 2011 0.310344828


4. Write a query to find the products whose quantity sold in a year should be greater than the average quantity of the product 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.QUANTITY

FROM PRODUCTS P,

SALES S

WHERE P.PRODUCT_ID = S.PRODUCT_ID

AND S.QUANTITY >

(SELECT AVG(QUANTITY)

FROM SALES S1

WHERE S1.PRODUCT_ID = S.PRODUCT_ID

);

PRODUCT_NAME YEAR QUANTITY

--------------------------

Nokia 2010 25

IPhone 2012 20

Samsung 2012 20

Samsung 2010 20


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_PRODUCTS

FROM SALES

GROUP BY YEAR;

YEAR NUM_PRODUCTS

------------------

2010 3

2011 3

2012 3

SQL Queries Interview Questions - Oracle Part 3

SQL Queries Interview Questions

1. 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, jhon

sam, vijay

sam, anand


Solution:

SELECT f1.name,

f2.friend_name as friend_of_friend

FROM friends f1,

friends f2

WHERE f1.name = 'sam'

AND f1.friend_name = f2.name

AND NOT EXISTS

(SELECT 1 FROM friends f3

WHERE f3.name = f1.name

AND f3.friend_name = f2.friend_name);


2. 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, 200, 2009

B, 155, 2009

C, 455, 2009

D, 620, 2009

E, 135, 2009

F, 390, 2009

G, 999, 2010

H, 810, 2010

I, 910, 2010

J, 109, 2010

L, 260, 2010

M, 580, 2010


Solution:

SELECT products,

quantity_sold,

year

FROM

(

SELECT products,

quantity_sold,

year,

rownum r

from t

ORDER BY quantity_sold DESC

)A

WHERE r <= 5;


3. This is an extension to the problem 3. Write a query to produce the same output using row_number analytical function?

Solution:

SELECT products,

quantity_sold,

year

FROM

(

SELECT products,

quantity_sold,

year,

row_number() OVER(

ORDER BY quantity_sold DESC) r

from t

)A

WHERE r <= 5;


4. 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,

year

FROM

(

SELECT products,

quantity_sold,

year,

row_number() OVER(

PARTITION BY year

ORDER BY quantity_sold DESC) r

from t

)A

WHERE r <= 5;

5. Load the below products table 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 Nokia

200 IPhone

300 Samsung

400 LG

500 BlackBerry

600 Motorola

The 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

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_PRODUCTS

SELECT PRODUCT_ID,

PRODUCT_NAME,

SYSDATE INSERT_DATE

FROM

(

SELECT PRODUCT_ID,

PRODUCT_NAME

FROM PRODUCTS S

WHERE 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.

)A

WHERE ROWNUM <= 2;

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;

6. 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 MOVIE

2 MOVIE

3 AUDIO

4 AUDIO

5 MAGAZINE

6 MAGAZINE

The 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 1

AUDIO 2 0

MAGAZINE 3 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);

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)

);

SQL Queries Interview Questions - Oracle Part 2

SQL Queries Interview Questions - Oracle Part 2


1. 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 20

Samsung 20 18 20

Nokia 25 16 8


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)

)A

PIVOT ( 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_2012

FROM PRODUCTS P,

SALES S

WHERE (P.PRODUCT_ID = S.PRODUCT_ID)

GROUP BY P.PRODUCT_NAME;


2. 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_PRODUCTS

FROM SALES

GROUP BY YEAR;

YEAR NUM_PRODUCTS

------------------

2010 3

2011 3

2012 3

3. Write a query to generate sequence numbers from 1 to the specified number N?

Solution:

SELECT LEVEL FROM DUAL CONNECT BY LEVEL<=&N;


4. 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';


5. 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, 3

B, 5

C, 2


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

Products, Repeat

----------------

A, 3

A, 3

A, 3

B, 5

B, 5

B, 5

B, 5

B, 5

C, 2

C, 2


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;


6. Write a query to display each letter of the word "SMILE" in a separate row?

S

M

I

L

E


Solution:

SELECT SUBSTR('SMILE',LEVEL,1) A

FROM DUAL

CONNECT BY LEVEL <=LENGTH('SMILE');


7. 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')

);

8. Consider the following friends table as the source

Name, Friend_Name

-----------------

sam, ram

sam, vamsi

vamsi, ram

vamsi, jhon

ram, vijay

ram, anand


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 are friends of friends. The output should look as

Name, Friend_of_Firend

----------------------

sam, ram

sam, jhon

sam, vijay

sam, anand


Solution:

SELECT f1.name,

f2.friend_name as friend_of_friend

FROM friends f1,

friends f2

WHERE f1.name = 'sam'

AND f1.friend_name = f2.name;