If you can't read please download the document
Upload
pyadav010186
View
28.133
Download
3
Embed Size (px)
Citation preview
SQL Queries Interview Questions - Oracle Part 1As a database
developer, writingSQL queries, PLSQL code is part of daily life.
Having a good knowledge on SQL is really important. Here i am
posting some practicalexamplesonSQL queries.
To solve theseinterviewquestionsonSQL queriesyou have to createthe
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 productstable contains the below data.SELECT * FROM
PRODUCTS;
PRODUCT_ID PRODUCT_NAME-----------------------100 Nokia200
IPhone300 Samsung
The salestable 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
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 belowSQL queries.
1.Write a SQL query to findthe productswhich 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 isSELECT 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 0
Here thelead 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 isSELECT 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------------IPhone
2.Write a SQL query to findthe productswhich 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------------LG
Method2:Using the NOT IN operator.SELECT P.PRODUCT_NAMEFROM
PRODUCTS PWHERE P.PRODUCT_ID NOT IN (SELECT DISTINCT PRODUCT_ID
FROM SALES);
PRODUCT_NAME------------LG
Method3: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------------LG
3.Write a SQL query to findthe productswhose sales decreased in
2012 compared to 2011?
Solution:
Here Nokia is the only product whose sales decreased in year 2012
when compared withthe salesin the year 2011. The SQL query to get
the required output isSELECT 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------------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 isSELECT
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 2012
5.Write a query to find the total sales of each product.?
Solution:
This isa simplequery. 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 2This is continuation to my previous post,SQL Queries
Interview Questions - Oracle Part 1, Where i have used PRODUCTS and
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 thequestionsmentioned
here.
Solve the belowexamplesby writing SQL queries.
1.Write a queryto findthe productswhose quantity sold in a year
should be greater than the average quantity sold across all the
years?
Solution:
This can besolvedwith the help of correlated query. The SQL query
for this isSELECT 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 20
2.Write a queryto comparethe productssales of "IPhone" and
"Samsung" in each year? The output should look like asYEAR
IPHONE_QUANT SAM_QUANT IPHONE_PRICE
SAM_PRICE---------------------------------------------------2010 10
20 9000 70002011 15 18 9000 70002012 20 20 9000 7000
Solution:
By using self-join SQL query we can get the required result. The
required SQL query isSELECT 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.YEAR
3.Write a queryto find the ratios ofthe salesof a product?
Solution:
The ratio of aproduct iscalculated as the total salespricein a
particular year divide by the total salespriceacross all years.
Oracle provides RATIO_TO_REPORT analytical function for finding the
ratios. The SQL query isSELECT 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.310344828
4.Inthe SALEStablequantity of eachproduct isstored in rows for
every year. Nowwrite a queryto transpose the quantity for each
product and display it in columns? The output should look like
asPRODUCT_NAME QUAN_2010 QUAN_2011
QUAN_2012------------------------------------------IPhone 10 15
20Samsung 20 18 20Nokia 25 16 8
Solution:
Oracle 11g provides a pivot function to transpose the row data into
column data. The SQL query for this isSELECT * 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 queryto find thenumberof 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 thisquestionisSELECT YEAR, COUNT(1)
NUM_PRODUCTSFROM SALESGROUP BY YEAR;
YEAR NUM_PRODUCTS------------------2010 32011 32012 3
SQL Queries Interview Questions - Oracle Part 3Here I am providing
Oracle SQL QueryInterviewQuestions. If you find any bugs in the
queries, Please do comment. So, that i will rectify them.
1.Write a queryto generate sequence numbers from 1 to the specified
number N?
Solution:SELECT LEVEL FROM DUAL CONNECT BY LEVELmkdir backup
This will createthe backupdirectory in the current directory.
9.Renaming and moving the files.
The mv command is used to rename the files and it also used for
moving the files from one directory into another directory.Renaming
the file.
>mv file.txt new_file.txt
Moving the file to another directory.
>mv new_file.txt tmp/
10.Finding thenumberof lines in a file
The wc command can be used to find thenumberof line, words and
characters in a file.>wc logfile.txt21 26 198 logfile.txt
To know about theunix command, it is always good to see the man
pages. To see the man pages simply pass the command as anargumentto
the man.man ls
SQL Queries Interview Questions - Oracle Analytical Functions
Part 1Analytic functions compute aggregate values based ona groupof
rows. They differ from aggregate functions in that
theyreturnmultiple 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
betterperformancewhen compared to native SQL.
Before starting with theinterviewquestions, we will seethe
differencebetween the aggregate functions and analytic functions
with an example. I have used SALESTABLEas an example to solve
theinterviewquestions. Please create the below salestablein 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 thenumberof products sold in each
year?
The SQL query Using Aggregate functions isSELECT Year, COUNT(1)
CNTFROM SALESGROUP BY YEAR;
YEAR CNT---------2009 32010 32011 32008 32012 3
The SQL query Using Aanalytic functions isSELECT 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 3
From the ouputs, you can observe that the aggregate
functionsreturnonly 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 thetable.
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 theInterviewQuestions 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 isSELECT 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 94
2.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 isSELECT 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 94
The 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 isSELECT 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
54
The ROWS BETWEEN clause specifies therange ofrows to consider
forcalculatingthe SUM.
4.Write a SQL query to find the Median of sales of a product?
Solution:
The SQL query forcalculatingthe median isSELECT 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 19
5.Write a SQL query to find the minimum sales of a product without
using the group by clause.
Solution:
The SQL query isSELECT 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 Interview Questions and Answers1.What is
Normalization?
Normalization is the process oforganizingthe columns, tables of a
database to minimize the redundancy of data. Normalization involves
in dividing large tables into smaller tables and defining
relationships between them. Normalization is used in OLTP
systems.
2.What are different types of Normalization Levels or Normalization
Forms?
The different types of Normalization Forms are:First Normal
Form:Duplicatecolumns from the same table needs to be eliminated.
We have to createseparatetables for each group of related data and
identify each row with auniquecolumn or set of columns (Primary
Key)
Second Normal Form: Firstit shouldmeet the requirement of first normal form. Removes the subsets of data that apply to multiple rows of a table and place them inseparatetables. Relationships must be created between the new tables and their predecessors through the use of foreign keys.
Third Normal Form: Firstit shouldmeet the requirements of second normal form. Remove columns that are not depending upon the primary key.
Fourth Normal Form: There should not be any multi-valued dependencies.
Most databases will be in Third Normal Form
3.What is De-normalization?
De-normalization is the process of optimizing the read performance
of a database by adding redundant data or by grouping data.
De-normalization is used in OLAP systems.
4.What is aTransaction?
Atransactionis a logical unit of work performed against a database
in which all steps must be performed or none.
5.What are ACID properties?
A databasetransactionmust be Atomic, Consistent, Isolation and
Durability.Atomic: Transactions must be atomic. Transactions must
fail or succeed as a single unit.
Consistent: The database must always be in consistent state. There should not be any partial transactions
Isolation: The changes made by a user should be visible only to that user until thetransactionis committed.
Durability: Once atransactionis committed,it shouldbe permanent and cannot be undone.
6.Explain different storage models of OLAP?MOLAP: The data is
stored in multi-dimensional cube. The storage is not in the
relational database, but in proprietary formats.
ROLAP: ROLAP relies on manipulating the data stored in the RDBMS for slicing and dicing functionality.
HOLAP: HOLAP combines the advantages of both MOLAP and ROLAP. For summary type information, HOLAP leverages on cube technology for faster performance. For detail information, HOLAP can drill through the cube.
7.Explain one-to-one relationship with an example?
One to one relationship isa simplereference between two tables.
Consider Customer and Address tables as an example. A customer can
have only one address and an address references only one
customer.
8.Explain one-to-many relationship with an example?
One-to-many relationships can be implemented by splitting the data
into two tables with a primary key and foreign key
relationship.Here therow in one table is referenced by one or more
rows in the other table. An example is the Employees and
Departments table, where the row in the Departments table is
referenced by one or more rows in the Employees table.
9.Explain many-to-many relationship with an example?
Many-to-Many relationship is created between two tables bycreatinga
junction table with the key from both the tablesformingthe
composite primary key of the junction table.
An example is Students, Subjects and Stud_Sub_junc tables. A
student can opt for one or more subjects in a year. Similarly a
subject can be opted by one or more students. So a junction table
is created to implement the many-to-many relationship.
10. Write downthe generalsyntax of a select statement?
The basicsyntax of a select statement isSELECT Columns | *FROM
Table_Name[WHERE Search_Condition][GROUP BY
Group_By_Expression][HAVING Search_Condition][ORDER BY
Order_By_Expression [ASC|DESC]]String aggregating Analytic
Functions in Oracle DatabaseThe string aggregate functions
concatenate multiple rows into a single row. Considerthe
productstableas anexample.
TableName: ProductsYear product-------------2010 A2010 B2010 C2010
D2011 X2011 Y2011 Z
Here, in the output we will concatenatethe productsin each year by
a comma separator. The desired output is:year
product_list------------------2010 A,B,C,D2011 X,Y,Z
LISTAGG analyticfunctionin 11gR2:
The LISTAGGfunctioncan be used to aggregate the strings. You
canpassthe explicit delimiter to the LISTAGGfunction.SELECT year,
LISTAGG(product, ',') WITHIN GROUP (ORDER BY product) AS
product_listFROM productsGROUP BY year;
WM_CONCATfunction:
You cannotpassan explicit delimiter to the WM_CONCATfunction. It
uses comma as the string separator.SELECT year, wm_concat(product)
AS product_listFROM productsGROUP BY year;
Pivot and Unpivot Operators in Oracle Database 11gPivot:
The pviotoperatorconvertsrow data to column data andalsocan do
aggregates whileconverting. To see how pivotoperatorworks, consider
the following "sales"tableas anyexampleTableName:Salescustomer_id
product price--------------------------------------1 A 101 B202 A
302 B 402 C503 A 603 B 703 C 80The rows of the "sales"tableneeds to
be converted into columns as shown below
TableName:sales_revcutomer_id a_product b_product
c_product-----------------------------------------1 10 202 30 40
503 60 70 80
The query forconvertingthe rows to columns isSELECT *FROM (SELECT
customer_id,product,price from sales)pivot ( sum(price) as
total_price for (product) IN ( 'A' as a, 'B' as b, 'C' as c) )Pivot
can be used to generate the data in xml format. The query
forgeneratingthe data into xml fomat is shown below.SELECT *FROM
(SELECT customer_id,product,price from sales)pivot XML ( sum(price)
as total_price for (product) IN ( SELECT distinct product from
sales) )
Ifyou arenot using oracle 11g database, thenyou can implement the unpivot feature asconverting rows to columns
Unpivot:
Unpivotoperatorconvertsthe columns into rows.TableName:
sales_revcutomer_id a_product b_product
c_product-----------------------------------------1 10 202 30 40
503 60 70 80
TableName:salescustomer_id product price---------------------------1 A 101 B 202 A 302 B 402 C 503 A 603 B 703 C 80
The query to convert rows into columns isSELECT *FROM sales_revUNPIVOT [EXCLUDE NULLs | INCLUDE NULLs] (price FOR product IN (a_product AS 'A', b_product AS 'B', c_product_c AS 'C'));
Pointstonoteabout the queryThe columnspriceand product in the unpivot clause are required and these names need not to be present in thetable.
The unpivoted columns must be specified in the IN clause
By default the query excludes null values.
Min and Max values of contiguous rows - Oracle SQL QueryQ)How to
findtheMinimumand maximum values of continuoussequencenumbersina
groupof rows.
I know theproblemis not clear without giving an example. Let say I
have the Employees table with the below data.Table Name:
EmployeesDept_Id Emp_Seq---------------10 110 210 310 510 610 810
910 1120 120 2
I want to find theminimumand maximum values of continuous
Emp_Seqnumbers. The output should look as.Dept_Id Min_Seq
Max_Seq-----------------------10 1 310 5 610 8 910 11 1120 1
2
Write an SQL query in oracle to find theminimumand maximum values
of continuous Emp_Seq in each department?
STEP1: First we will generateuniquesequencenumbersin each
department using the Row_Number analytic function in the Oracle.
The SQL query is.SELECT Dept_Id, Emp_Seq, ROW_NUMBER() OVER
(PARTITION BY Dept_Id ORDER BY Emp_Seq) rnFROM employees;
Dept_Id Emp_Seq rn--------------------10 1 110 2 210 3 310 5 410
6 510 8 610 9 710 11 820 1 120 2 2
STEP2: Subtract the value of rn from emp_seq to identify the
continuoussequencesasa group. The SQL query isSELECT Dept_Id,
Emp_Seq, Emp_Seq-ROW_NUMBER() OVER (PARTITION BY Dept_Id ORDER BY
Emp_Seq) Dept_SplitFROM employees;
Dept_Id Emp_Seq Dept_Split---------------------------10 1 010 2
010 3 010 5 110 6 110 8 210 9 210 11 320 1 020 2 0
STEP3: The combination of the Dept_Id and Dept_Split fields will
become the group for continuous rows. Now use group by on these
fields and find the min and max values. The final SQL query
isSELECT Dept_Id, MIN(Emp_Seq) Min_Seq, MAX(Emp_Seq)
Max_SeqFROM(SELECT Dept_Id, Emp_Seq, Emp_Seq-ROW_NUMBER() OVER
(PARTITION BY Dept_Id ORDER BY Emp_Seq) Dept_SplitFROM employees;)
AGroup BY Dept_Id, Dept_Split
Rewrite Sql Query | Sql Performance TuningTuning an SQL query
for performance is a big topic. Here I will just cover how to
re-write a query and thereby improve the performance. Rewriting an
SQL query is one of the ways you can improve performance. You can
rewrite a query in many different ways.
To explain this, i have usedthe salesand products table.
SALES(SALE_ID, YEAR, PRODUCT_ID,PRICE);
PRODUCTS(PRODUCT_ID, PRODUCT_NAME);
Follow the below steps in re writing a query for
optimization.
1.Avoid Redundant Logic
I have seen people writing redundant sub-queries and worrying about
their query performance. As an example, find the total sales in
each year and alsothe salesof product with id 10 in each
year.SELECT T.YEAR, T.TOT_SAL, P.PROD_10_SAL( SELECT YEAR,
SUM(PRICE) TOT_SAL FROM SALES GROUP BY YEAR) TLEFT OUTER JOIN(
SELECT YEAR, SUM(PRICE) PROD_10_SAL FROM SALES WHERE PRODUCT_ID =
10) PON (T.YEAR = P.YEAR);
Most SQL developers write the above Sql query without even thinking
that it can be solved in a single query. The above query is
rewritten asSELECT YEAR, SUM(CASE WHEN PRODUCT_ID = 10 THEN PRICE
ELSE NULL END ) PROD_10_SAL, SUM(SALES) TOT_SALFROM SALESGROUP BY
YEAR;
Now you can see the difference, just by readingthe salestable one
time we will able to solve theproblem.
First take a look at of your query, identify the redundant logic
and then tune it.
2.LEFT OUTER JOIN, NOT EXISTS, NOT IN
Some times you can rewrite a LEFT OUTER JOIN by using NOT EXISTS or
NOT IN and vice versa. As an example, I want to findthe
productswhich do not sold in the year 2011.SELECT P.PRODUCT_ID,
P.PRODUCT_NAMEFROM PRODUCTS P LEFT OUTER JOIN SALES SON
(P.PRODUCT_ID = S.PRODUCT_ID)WHERE S.SALE_ID IS NULL;
The same query can be rewritten using NOT EXISTS and NOT IN
asSELECT P.PRODUCT_ID, P.PRODUCT_NAMEFROM PRODUCTS PWHERE NOT
EXISTS ( SELECT 1 FROM SALES S WHERE S.PRODUCT_ID =
P.PRODUCT_ID);
SELECT P.PRODUCT_ID, P.PRODUCT_NAMEFROM PRODUCTS PWHERE
PRODUCT_ID NOT IN ( SELECT PRODUCT_ID FROM SALES );
Analyze the performance of these three queries and use the
appropriate one.
Note:Be careful while using the NOT IN. If the sub query returns at
lease row with NULL data, then the main query won'treturna row at
all.
3.INNER JOIN, EXISTS, IN
As similar to LEFT OUTER JOIN, the INNER JOINS can also be
implemented with the EXISTS or INoperators. As an example, we will
findthe salesof products whose product ids exists inthe
productstable.SELECT S.PRODUCT_ID, SUM(PRICE)FROM SALES S JOIN
PRODUCTS PON (S.PRODUCT_ID = P.PRODUCT_ID)GROUP BY
S.PRODUCT_ID;
As we are not selecting any columns fromthe productstable, we can
rewrite the same query with the help of EXISTS or IN
operator.SELECT S.PRODUCT_ID, SUM(PRICE)FROM SALES SWHERE EXISTS (
SELECT 1 FROM PRODUCTS P WHERE P.PRODUCT_ID = S.PRODUCT_ID);GROUP
BY S.PRODUCT_ID;
SELECT S.PRODUCT_ID, SUM(PRICE)FROM SALES SWHERE PRODUCT_ID IN (
SELECT PRODUCT_ID FROM PRODUCTS P );GROUP BY S.PRODUCT_ID;
4.INNER JOIN, CORRELATED QUERY
We will seea simplejoin betweenthe SALESand PRODUCTS table.SELECT
S.SALE_ID, S.PRODUCT_ID, P.PRODUCT_NAMEFROM SALES S JOIN PRODUCTS
PON (S.PRODUCT_ID = P.PRODUCT_ID)
The above query can be rewritten with correlated query asSELECT
S.SALE_ID, S.PRODUCT_ID, (SELECT PRODUCT_NAME FROM PRODUCTS P WHERE
P.PRODUCT_ID = S.PRODUCT_ID)FROM SALES S
Analyze these two queries with the explain plan and check which one
gives better performance.
5.Using With Clause or Temporary Tables.
Try to avoid writing complex Sql queries. Split the queries and
store the data in temporary tables or use theOracle With
Clausefortemporary storage. This will improve the performance. You
can also use the temporary tables or with clause when you want to
reuse the same query more than once. This saves the time and
increases the performance.
Tips for increasing the query performance:Create the required
indexes.In the mean timeavoidcreatingtoo many indexeson a
table.
Rewrite the Sql query.
Use the explain plan, auto trace to know about the query execution.
Generate statistics on tables.
Specify the oracle Hints in the query.
Ask the DBA to watch the query and gather stats likeCPU usage, number of row read etc.
Top Unix Interview Questions - Part 11. How to display the 10th
line of a file?
head -10 filename | tail -1
2. How to remove theheaderfrom a file?
sed -i '1 d' filename
3. How to remove the footer from a file?
sed -i '$ d' filename
4.Writea command to find the length of a line in a file?
The below command can be used to get a line from a file.
sed n ' p' filename
We will seehow to findthe length of 10th line in a file
sed -n '10 p' filename|wc -c
5.How to getthe nth word of a line in Unix?
cut f -d' '
6. How to reverse a string in unix?
echo "java" | rev
7.How to getthe last word from a line in Unix file?
echo "unix is good" | rev | cut -f1 -d' ' | rev
8.How to replacethe n-th line in a file with a new line in
Unix?
sed -i'' '10 d' filename # d stands for delete
sed -i'' '10 i new inserted line' filename # i stands for
insert
9. How tocheckif the last command was successful in Unix?
echo $?
10.Writecommand tolist allthe links from a directory?
ls -lrt | grep "^l"
11. How will you find which operating system your system is running
on in UNIX?
uname -a
12.Createa read-only file in yourhome directory?
touch file; chmod 400 file
13. How do you see command line history in UNIX?
The 'history' command can be used to get the list of commands that
we are executed.
14. How to display the first 20 lines of a file?
By default,the headcommand displays the first 10 lines from a file.
If we change the option of head, then we can display as many lines
as we want.
head -20 filename
An alternativesolutionis using the sed command
sed '21,$ d' filename
The d option here deletes the lines from 21 to the end of the
file
15.Writea command to print the last line of a file?
The tail command can be used to display the last lines from a
file.
tail -1 filename
Alternative solutions are:
sed -n '$ p' filename
awk 'END{print $0}' filename
Top Unix Interview Questions - Part 21. How do you rename the
files in a directory with _new as suffix?
ls -lrt|grep '^-'| awk '{print "mv "$9" "$9".new"}' | sh
2.Writea command toconverta string from lower case to upper
case?
echo "apple" | tr [a-z] [A-Z]
3.Writea command toconverta string to Initcap.
echo apple | awk '{print toupper(substr($1,1,1))
tolower(substr($1,2))}'
4.Writea command to redirect the output of date command to multiple
files?
The tee command writes the output to multiple files andalsodisplays
the output on the terminal.
date | tee -a file1 file2 file3
5. How do you list the hidden files incurrent directory?
ls -a | grep '^\.'6. List out some of the Hot Keys available in
bash shell?Ctrl+l - Clears the Screen.
Ctrl+r - Does a search in previously given commands in shell.
Ctrl+u - Clears the typing before the hotkey.
Ctrl+a - Places cursor at the beginning of the command at shell.
Ctrl+e - Places cursor at the end of the command at shell.
Ctrl+d - Kills the shell.
Ctrl+z - Places the currentlyrunning processinto background.
7. How do you make an existing file empty?
cat /dev/null > filename
8. How do you remove the firstnumberon 10th line in file?
sed '10 s/[0-9][0-9]*//' < filename
9. What isthe differencebetween join -v and join -a?
join -v : outputs only matched lines between two files.
join -a : In addition to the matched lines, this will output
unmatched linesalso.
10. How do you display from the 5thcharacterto the end of the line
from a file?
cut -c 5- filename
Top Unix Interview Questions - Part 31. Display all the files in
current directory sorted by size?
ls -l | grep '^-' | awk '{print $5,$9}' |sort -n|awk '{print $2}'2.
Write acommandtosearch forthe file 'map' in the current
directory?
find -name map -type f3. How to display the first 10 characters
from each line of a file?
cut -c -10 filename4. Write acommandto remove the firstnumberon all
lines that start with "@"?
sed '\,^@, s/[0-9][0-9]*//' < filename5. How to print the file
names in a directory that has the word "term"?
grep -l term *
The '-l' option make the grepcommandto print only the filename
without printing the content of the file. As soon as the
grepcommandfinds the pattern in a file, it prints the pattern and
stops searching other lines in the file.6. How to run
awkcommandspecified in a file?
awk -f filename7. How do you display thecalendarfor the month march
in the year 1985?
The calcommandcan be used to display the current monthcalendar. You
can pass the month and year asargumentsto display the required
year, month combinationcalendar.
cal 03 1985
Thiswill displaythecalendarfor the March month and year 1985.8.
Write acommandto find the totalnumberof lines in a file?
wc -l filename
Other ways to pring the totalnumberof lines are
awk 'BEGIN {sum=0} {sum=sum+1} END {print sum}' filename
awk 'END{print NR}' filename9. How toduplicateempty lines in a
file?
sed '/^$/ p' < filename10. Explain iostat, vmstat and
netstat?Iostat: reports on terminal, disk and tape I/O
activity.
Vmstat: reports onvirtual memorystatistics for processes, disk, tape and CPU activity.
Netstat: reports on thecontentsof network data structures.
Top Unix Interview Questions - Part 41. How do you write
thecontentsof 3 files into asingle file?
cat file1 file2 file3 > file
2. How to displaythe fieldsin atext filein reverse order?
awk 'BEGIN {ORS=""} { for(i=NF;i>0;i--) print $i," "; print
"\n"}' filename
3. Write a command to find the sum of bytes (size of file) of all
files in a directory.
ls -l | grep '^-'| awk 'BEGIN {sum=0} {sum = sum + $5} END {print
sum}'
4. Write a command to print the lines which end with the word
"end"?
grep 'end$' filename
The '$' symbol specifies the grep command tosearch forthe pattern
at the end of the line.
5. Write a command to select only those lines containing "july" as
a whole word?
grep -w july filename
The '-w' option makes the grep command tosearch forexact whole
words. If the specified pattern is found in a string, then it is
not considered as a whole word. For example: In the string
"mikejulymak", the pattern "july" is found. However "july" is not a
whole word in that string.
6. How to remove the first 10 lines from a file?
sed '1,10 d' < filename
7. Write a command toduplicateeach line in a file?
sed 'p' < filename
8. How to extract theusernamefrom 'who am i' comamnd?
who am i| cut -f1 -d' '
9. Write a command to list the files in '/usr' directory that start
with 'ch' and then display thenumberof lines in each file?
wc -l /usr/ch*
Another way is
find /usr -name 'ch*' -type f -exec wc -l {} \;
10. How to remove blank lines in a file ?
grep -v ^$ filename > new_filename
Top Unix Interview Questions - Part 51. How to display the
processes that were run by your user name ?
ps -aef | grep
2. Write a command to display all the files recursively with path
under current directory?
find . -depth -print
3. Display zero byte size files in the current directory?
find -size 0 -type f
4. Write a command to display the third and fifth character from
each line of a file?
cut -c 3,5 filename
5. Write a command to print the fields from 10th to the end of the
line. The fields in the line are delimited by a comma?
cut -d',' -f10- filename
6. How to replace the word "Gun" with "Pen" in the first 100 lines
of a file?
sed '1,00 s/Gun/Pen/' < filename
7. Write a Unix command to display the lines in a file that do not
contain the word "RAM"?
grep -v RAM filename
The '-v' option tells the grep to print the lines that do not
contain the specified pattern.
8. How to print the squares of numbers from 1 to 10 using awk
command
awk 'BEGIN { for(i=1;i