Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

  • Upload
    raj

  • View
    217

  • Download
    0

Embed Size (px)

Citation preview

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    1/68

    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 interviewquestionson SQL queries you have to create the products, sales tables in your oracledatabase. 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 INTOPRODUCTS VALUES ( 100, 'Nokia');

    INSERT INTO PRODUCTS VALUES ( 200, 'IPhone');

    INSERT INTO PRODUCTS VALUES ( 300, 'Samsung');

    INSERT INTO PRODUCTS VALUES ( 400, 'LG');

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    2/68

    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 Nokia

    200 IPhone

    300 Samsung

    The salestable contains the following data.

    SELECT * FROM SALES;

    SALE_ID PRODUCT_ID YEAR QUANTITY PRICE

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    3/68

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

    1 100 2010 25 5000

    2 100 2011 16 5000

    3 100 2012 8 5000

    4 200 2010 10 9000

    5 200 2011 15 9000

    6 200 2012 20 9000

    7 300 2010 20 7000

    8 300 2011 18 7000

    9 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 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

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    4/68

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    5/68

    (

    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 P.PRODUCT_ID = S.PRODUCT_ID

    )A

    GROUPBY PRODUCT_NAME

    HAVING MIN(QUAN_DIFF) >= 0;

    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.

    SELECT P.PRODUCT_NAME

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    6/68

    FROM PRODUCTS P

    LEFT OUTER JOIN

    SALES S

    ON (P.PRODUCT_ID = S.PRODUCT_ID);

    WHERE S.QUANTITY IS NULL

    PRODUCT_NAME

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

    LG

    Method2:Using the NOT IN operator.

    SELECT P.PRODUCT_NAME

    FROM PRODUCTS P

    WHERE P.PRODUCT_ID NOT IN

    (SELECT DISTINCT PRODUCT_ID FROM SALES);

    PRODUCT_NAME

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

    LG

    Method3:Using the NOT EXISTS operator.

    SELECT P.PRODUCT_NAME

    FROM PRODUCTS P

    WHERE NOT EXISTS

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    7/68

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    8/68

    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. Thequery 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 P.PRODUCT_ID = S.PRODUCT_ID

    ) A

    WHERE RNK = 1;

    PRODUCT_NAME YEAR

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

    Nokia 2010

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    9/68

    Samsung 2011

    IPhone 2012

    Samsung 2012

    5.Write a query to find the total sales of each product.?

    Solution:

    This is a 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_SALES

    FROM PRODUCTS P

    LEFT OUTER JOIN

    SALES S

    ON (P.PRODUCT_ID = S.PRODUCT_ID)

    GROUP BY P.PRODUCT_NAME;

    PRODUCT_NAME TOTAL_SALES

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

    LG 0

    IPhone 405000

    Samsung 406000

    Nokia 245000

    SQL 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 the questionsmentioned here.

    http://www.folkstalk.com/2011/12/sql-queries-interview-questions-oracle.htmlhttp://www.folkstalk.com/2011/12/sql-queries-interview-questions-oracle.htmlhttp://www.folkstalk.com/2011/12/sql-queries-interview-questions-oracle.htmlhttp://www.folkstalk.com/2011/12/sql-queries-interview-questions-oracle.html
  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    10/68

    Solve the below examplesby writing SQL queries.

    1.Write a queryto find the productswhose quantity sold in a year should be greater than the average quantity sold

    across all the years?

    Solution:

    This can be solvedwith 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

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    11/68

    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

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    12/68

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    13/68

    4.In the SALES tablequantity 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,

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    14/68

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    15/68

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    16/68

    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 = A.L

    ORDER BY T.PRODUCTS;

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    17/68

    4. Write a query to display each letter of the word "SMILE" in a separaterow?

    S

    M

    I

    L

    E

    Solution:

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

    FROM DUAL

    CONNECT BY LEVEL

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    18/68

    FROM DUAL

    CONNECT BY LEVEL

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    19/68

    FROM friends f1,

    friends f2

    WHERE f1.name = 'sam'

    AND f1.friend_name = f2.name;

    2. This is an extensionto the problem 1. In the output, you can see ram is displayedas 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);

    3. Write a query to get the top 5productsbased on the quantity sold without using the row_number

    analytical function? The source data looks as

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    20/68

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    21/68

    from t

    ORDER BY quantity_sold DESC

    )A

    WHERE r

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    22/68

    year

    FROM

    (

    SELECT products,

    quantity_sold,

    year,

    row_number() OVER(

    PARTITION BY year

    ORDER BY quantity_sold DESC) r

    from t

    )A

    WHERE r

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    23/68

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    24/68

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    25/68

    WHERE ROWNUM

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    26/68

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

    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 mentionthe 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);

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    27/68

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

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

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    28/68

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    29/68

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    30/68

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    31/68

    14.Display the filenames that matches the pattern.

    We can just display the files that contains the given string/pattern.

    grep -l "string" file.txt

    15.Display the file names that do not contain the pattern.

    We can display the files which do not contain the matched string/pattern.

    grep -l "string" file.txt

    16.Displaying only the matched pattern.

    By default, grep displays the entire line which has the matched string. We can make the grep to display only the

    matched string by using the -o option.

    grep -o "string" file.txt

    17.Displaying the line numbers.

    We can make the grep command to display the position of the line which contains the matched string in a file

    using the -n option

    grep -n "string" file.txt

    18.Displaying the position of the matched string in the line

    The -b option allows the grep command to display the character position of the matched string in a file.

    grep -o -b "string" file.txt

    19.Matchingthe lines that start with a string

    The ^ regular expression pattern specifies the start of a line. This can be used in grep to match the lines which start

    with the given string or pattern.

    grep "^start" file.txt

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    32/68

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    33/68

    >cat file.txt

    This is a sample unix file

    Learning about unix server is awesome

    3. Displaying first few lines from a file.

    The headcommand can be used to print the specified numberof lines from the starting of a file. The below head

    command displays the first five lines of file.

    >head -5 logfile.dat

    4. Displaying last few lines from a file.

    The tail command can be used to print the specified number of lines from the ending of a file. The below tail

    command displays the last three lines of file.

    >tail -3 logfile.dat

    5. Changing the directories

    The cd command can be used to change from one directory to another directory. You need to specify the target

    directory where you want to go.

    >cd /var/tmp

    After typing this cd command you will be in /var/tmp directory.

    6. Creatinga file.

    The touch command simply creates an empty file. The below touch command creates a new file in the current

    directory.

    touch new_file.txt

    7. copying the contents of one file into another.

    The cp command is used to copy the content of source file into the target file. If the target file already have data,

    then it will be overwritten.

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    34/68

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    35/68

    SQL Queries Interview Questions - Oracle Analytical Functions Part 1Analytic functions compute aggregate values based on a groupof rows. They differ from aggregate functions in

    that they returnmultiple 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 the interviewquestions, we will see the differencebetween the aggregate functions and

    analytic functions with an example. I have used SALES TABLEas 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);

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    36/68

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    37/68

    9 200 2008 13 9000

    10 200 2009 14 9000

    11 300 2010 20 7000

    12 300 2011 18 7000

    13 300 2012 20 7000

    14 300 2008 17 7000

    15 300 2009 19 7000

    Difference Between Aggregate and Analytic Functions:

    Q.Write a query to find the numberof products sold in each year?

    The SQL query Using Aggregate functions is

    SELECT Year,

    COUNT(1) CNT

    FROM SALES

    GROUP BY YEAR;

    YEAR CNT

    ---------

    2009 3

    2010 3

    2011 3

    2008 3

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    38/68

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    39/68

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    40/68

    100 10 71

    100 25 71

    100 16 71

    100 8 71

    200 15 72

    200 10 72

    200 20 72

    200 14 72

    200 13 72

    300 20 94

    300 18 94

    300 17 94

    300 20 94

    300 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 is

    SELECT PRODUCT_ID,

    QUANTITY,

    SUM(QUANTITY) OVER( PARTITION BY PRODUCT_ID

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    41/68

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    42/68

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    43/68

    200 14 49

    200 13 42

    200 10 37

    300 20 20

    300 20 40

    300 19 59

    300 18 57

    300 17 54

    The ROWS BETWEEN clause specifies the range ofrows to consider for calculatingthe 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) MEDIAN

    FROM SALES;

    PRODUCT_ID QUANTITY MEDIAN

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

    100 8 12

    100 10 12

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    44/68

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    45/68

    QUANTITY,

    ROW_NUMBER() OVER(PARTITION BY PRODUCT_ID

    ORDER BY QUANTITY ASC) MIN_SALE_RANK

    FROM SALES

    ) WHERE MIN_SALE_RANK = 1;

    PRODUCT_ID YEAR QUANTITY

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

    100 2012 8

    200 2010 10

    300 2008 17

    SQL Interview Questions and Answers1. What is Normalization?

    Normalization is the process of organizingthe 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

    create separatetables for each group of related data and identify each row with a uniquecolumn or set of columns

    (Primary Key)

    Second Normal Form: First it shouldmeet the requirement of first normal form. Removes the subsets of

    data that apply to multiple rows of a table and place them in separate tables. Relationships must be created

    between the new tables and their predecessors through the use of foreign keys.

    Third Normal Form: First it should meet the requirements of second normal form. Remove columns that

    are not depending upon the primary key.

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    46/68

    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 a Transaction?

    A transaction is a logical unit of work performed against a database in which all steps must be performed or none.

    5. What are ACID properties?

    A database transaction must 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 the transaction is

    committed.

    Durability: Once a transaction is committed, it should be 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 is a 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

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    47/68

    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 by creatinga junction table with the key from both thetables formingthe 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 down the generalsyntax of a select statement?

    The basicsyntax of a select statement is

    SELECT 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. Consider the productstableas

    an example.

    Table Name: Products

    Year product

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

    2010 A

    2010 B

    2010 C

    2010 D

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    48/68

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    49/68

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    50/68

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    51/68

    2 B 40

    2 C 50

    3 A 60

    3 B 70

    3 C 80

    The query to convert rows into columns is

    SELECT *

    FROM sales_rev

    UNPIVOT [EXCLUDE NULLs | INCLUDE NULLs] (price FOR product IN (a_product AS 'A', b_product AS

    'B', c_product_c AS 'C'));

    Pointsto noteabout the query

    The columns price and product in the unpivot clause are required and these names need not to be present

    in the table.

    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 findthe Minimumand maximum values of continuous sequencenumbersin a groupof rows.

    I know theproblemis not clear without giving an example. Let say I have the Employees table with the below

    data.

    Table Name: Employees

    Dept_Id Emp_Seq

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

    10 1

    10 2

    10 3

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    52/68

    10 5

    10 6

    10 8

    10 9

    10 11

    20 1

    20 2

    I want to find the minimum and maximum values of continuous Emp_Seq numbers. The output should look as.

    Dept_Id Min_Seq Max_Seq

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

    10 1 3

    10 5 6

    10 8 9

    10 11 11

    20 1 2

    Write an SQL query in oracle to find the minimum and maximum values of continuous Emp_Seq in each

    department?

    STEP1: First we will generate uniquesequence numbers in 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) rn

    FROM employees;

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    53/68

    Dept_Id Emp_Seq rn

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

    10 1 1

    10 2 2

    10 3 3

    10 5 4

    10 6 5

    10 8 6

    10 9 7

    10 11 8

    20 1 1

    20 2 2

    STEP2: Subtract the value of rn from emp_seq to identify the continuous sequencesas a group. The SQL query is

    SELECT Dept_Id,

    Emp_Seq,

    Emp_Seq-ROW_NUMBER() OVER (PARTITION BY Dept_Id ORDER BY Emp_Seq) Dept_Split

    FROM employees;

    Dept_Id Emp_Seq Dept_Split

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

    10 1 0

    10 2 0

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    54/68

    10 3 0

    10 5 1

    10 6 1

    10 8 2

    10 9 2

    10 11 3

    20 1 0

    20 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 is

    SELECT Dept_Id,

    MIN(Emp_Seq) Min_Seq,

    MAX(Emp_Seq) Max_Seq

    FROM

    (

    SELECT Dept_Id,

    Emp_Seq,

    Emp_Seq-ROW_NUMBER() OVER (PARTITION BY Dept_Id ORDER BY Emp_Seq) Dept_Split

    FROM employees;

    ) A

    Group BY Dept_Id, Dept_Split

    Rewrite Sql Query | Sql Performance Tuning

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    55/68

    Tuning 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 used the 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 also the sales of 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

    ) T

    LEFT OUTER JOIN

    (

    SELECT YEAR,

    SUM(PRICE) PROD_10_SAL

    FROM SALES

    WHERE PRODUCT_ID = 10

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    56/68

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    57/68

    WHERE S.SALE_ID IS NULL;

    The same query can be rewritten using NOT EXISTS and NOT IN as

    SELECT P.PRODUCT_ID,

    P.PRODUCT_NAME

    FROM PRODUCTS P

    WHERE NOT EXISTS

    (

    SELECT 1

    FROM SALES S

    WHERE S.PRODUCT_ID = P.PRODUCT_ID);

    SELECT P.PRODUCT_ID,

    P.PRODUCT_NAME

    FROM PRODUCTS P

    WHERE 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

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    58/68

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    59/68

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    60/68

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    61/68

    cutf -d' '

    6. How to reverse a string in unix?

    echo "java" | rev

    7. How to get the 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 to checkif the last command was successful in Unix?

    echo $?

    10. Write command to list 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 your home 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 alternative solutionis using the sed command

    sed '21,$ d' filename

    The d option here deletes the lines from 21 to the end of the file

    15. Write a 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 2

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    62/68

    1. 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 to converta string from lower case to upper case?

    echo "apple" | tr [a-z] [A-Z]

    3. Write a command to convert a string to Initcap.

    echo apple | awk '{print toupper(substr($1,1,1)) tolower(substr($1,2))}'

    4. Write a command to redirect the output of date command to multiple files?

    The tee command writes the output to multiple files and alsodisplays the output on the terminal.

    date | tee -a file1 file2 file3

    5. How do you list the hidden files in current 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 currently running processinto background.

    7. How do you make an existing file empty?

    cat /dev/null > filename

    8. How do you remove the first numberon 10th line in file?

    sed '10 s/[0-9][0-9]*//' < filename

    9. What is the 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 lines also.

    10. How do you display from the 5th characterto 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}'

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    63/68

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    64/68

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    65/68

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    66/68

    9. How to replace the character '/' with ',' in a file?

    sed 's/\//,/' < filename

    sed 's|/|,|' < filename

    10. Write a command to find the number of files in a directory.

    ls -l|grep '^-'|wc -l

    Top Unix Interview Questions - Part 71. Writea command to display your name100 times.

    The Yes utilitycan be used to repeatedly output a line with the specified string or 'y'.

    yes | head -100

    2. Write a command to display the first 10 characters from each line of a file?

    cut -c -10 filename

    3. The fieldsin each line are delimited by comma. Write a command to display third field from each line of a file?

    cut -d',' -f2 filename

    4. Write a command to print the fields from 10 to 20 from each line of a file?

    cut -d',' -f10-20 filename

    5. Write a command to print the first 5 fields from each line?

    cut -d',' -f-5 filename

    6. By default the cut commanddisplays the entire line if there is no delimiter in it. Which cut optionis used to

    supress these kind of lines?

    The -s option is used to supress the lines thatdo not contain the delimiter.

    7. Write a command to replace the word "bad" with "good" in file?

    sed s/bad/good/ < filename

    8. Write a command to replace the word "bad" with "good" globally in a file?

    sed s/bad/good/g < filename

    9. Write a command to replace the word "apple" with "(apple)" in a file?

    sed s/apple/(&)/ < filename

    10. Write a command to switchthe two consecutive words "apple" and "mango" in a file?

    sed 's/\(apple\) \(mango\)/\2 \1/' < filename

    11. Write a command to display the characters from 10 to 20 from each line of a file?

    cut -c 10-20 filename

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    67/68

    1. Write a command to print the lines thathas the thepattern"july" in all the files in a particular directory?

    grep july *This will print all the lines in all files that contain the word july along withthe filename. If any of the files

    contain words like "JULY" or "July", the above command would not print those lines.

    2. Write a command to print the lines thathas the word "july" in all the files in a directory and also suppress the

    filename in the output.grep -h july *

    3. Write a command to print the lines thathas the word "july" while ignoring the case.

    grep -i july *The option i make the grep command to treat the patternas case insensitive.

    4. When you use a single fileas input to the grep command to search fora pattern, it won't print the filename in

    the output. Now write a grep command to print the filename in the output without using the '-H' option.

    grep patternfilename /dev/null

    The /dev/null or null device is special file that discards the data written to it. So, the /dev/null is always an emptyfile.

    Another way to print the filename is using the '-H' option. The grep command for this isgrep -H patternfilename

    5. Write a command to print the filenames in a directory that does not contain the word "july"?

    grep -L july *

    The '-L' option makes the grep command to print the filenames that do not contain the specified pattern.

    6. Write a command to print the line numbersalong with the line that has the word "july"?

    grep -n july filename

    The '-n' option is used to print the line numbersin a file. The line numbersstart from 1

    7. Write a command to print the lines thatstarts with the word "start"?

    grep '^start' filenameThe '^' symbol specifies the grep command to search forthe patternat the start of the line.

    8. In the text file, some lines are delimited by colon and some are delimited by space. Write a command to print

    the third field of each line.

    awk '{ if( $0 ~ /:/ ) { FS=":"; } else { FS =" "; } print $3 }' filename

    9. Write a command to print the line numberbefore each line?awk '{print NR, $0}' filename

    10. Write a command to print the second and third line of a file without using NR.

    awk 'BEGIN {RS="";FS="\n"} {print $2,$3}' filename

    11. How to createan alias for the complex command and remove the alias?

    The alias utility is used to createthe alias for a command. The below command createsalias for ps -aef command.

    alias pg='ps -aef'

    If you use pg, it will work the same way as ps -aef.

    To remove the alias simply use the unalias command as

    unalias pg

    12. Write a command to display todays date in the format of 'yyyy-mm-dd'?

  • 7/26/2019 Sqlqueriesinterviewquestions 120708121732 Phpapp02 (2)

    68/68

    The date command can be used to display todays date with time

    date '+%Y-%m-%d'