Sunday, 26 August 2012

SQL Interview Questions and Answers Part1




Q) i have emp table in which columns are empid,empname,sal now i want to increase the sal of the particular emp whose sal is <10000 with 2000RS & sal >10000 & <20000 with 4000RS and whose sal is >20000 with 5000RS now write a single update query.

UPDATE Emp
SET sal = sal +
CASE
WHEN sal>=1000 AND sal<2000 THEN 200
WHEN sal>=2000 AND sal<3000 THEN 300
END;


SELECT deptno, empno, sal
FROM emp e
WHERE
2 > ( SELECT COUNT(e1.sal)
      FROM emp e1
      WHERE e.deptno = e1.deptno AND e.sal < e1.sal )
ORDER BY 1,3 DESC;


I am looking at the following output. We need to stick to this format.

Total                1980                1981                1982                1983
-----------          ------------         ------------         -------------        -----------
14                    1                      10                    2                      1


SELECT COUNT (*),  COUNT(DECODE(TO_CHAR (hiredate, 'YYYY'),'1980', empno)) "1980",
                             COUNT (DECODE (TO_CHAR (hiredate, 'YYYY'), '1981', empno)) "1981",
                             COUNT (DECODE (TO_CHAR (hiredate, 'YYYY'), '1982', empno)) "1982",
                             COUNT (DECODE (TO_CHAR (hiredate, 'YYYY'), '1983', empno)) "1983"
FROM emp;

     
SELECT a.deptno, ename, sal, (SELECT SUM(sal) FROM emp b WHERE a.deptno = b.deptno)
FROM emp a
ORDER BY a.deptno;

OUTPUT :
=======
DEPTNO                      ENAME            SAL            SUM (SAL)
=========                  =======          ====           =========
       10                         KING                5000                   11725
       30                         BLAKE             2850                 10900
       10                         CLARK             2450                 11725
       10                         JONES             2975                 11725
       30                         MARTIN            1250                 10900
       30                         ALLEN              1600                 10900
       30                         TURNER           1500                 10900
       30                         JAMES               950                 10900
       30                         WARD              2750                 10900
       20                         SMITH              8000                 33000
       20                         SCOTT             3000                 33000
       20                         MILLER          20000                 33000


The output is as follows - we need to stick to this format :

Job                  Dept 10                                    Dept 20                        Dept 30                        Total
----------            ---------------                             -------------                    -------------                    ---------
ANALYST                                                         6000                                                                6000
CLERK               1300                                      1900                            950                              4150
MANAGER         2450                                      2975                            2850                            8275
PRESIDENT       5000                                                                                                              5000
SALESMAN                                                                                         5600                            5600


SELECT job "Job", SUM (DECODE (deptno, 10, sal)) "Dept 10",
                             SUM (DECODE (deptno, 20, sal)) "Dept 20",
                             SUM (DECODE (deptno, 30, sal)) "Dept 30",
                             SUM (sal) "Total"
FROM emp
GROUP BY job ;


SELECT DEPTNO, ENAME, SAL
FROM EMP A
WHERE
3 = (SELECT COUNT(B.SAL) FROM EMP B
WHERE A.SAL < B.SAL) ORDER BY SAL DESC;


SELECT DEPTNO, ENAME, SAL
FROM EMP 
WHERE ROWID = (SELECT ROWID FROM EMP   WHERE ROWNUM <= 5
      MINUS
      SELECT ROWID FROM EMP WHERE ROWNUM < 5)


Name                            Null?              Type
-------------------------------------------------------------------
SUB                             NOT NULL       VARCHAR2(4)
SUPER                                    VARCHAR2(4)
PRICE                                      NUMBER(6,2)


SELECT sub, super
FROM parts
CONNECT BY PRIOR sub = super
START WITH sub = 'p1';


DELETE FROM table_name A
WHERE ROWID > (  SELECT min(ROWID) FROM table_name B  WHERE A.col = B.col);


SELECT *
FROM   emp
WHERE  (ROWID,0) IN (SELECT ROWID, MOD(ROWNUM,4)
                                       FROM   emp);

SELECT ename, deptno, sal
FROM (SELECT * FROM emp ORDER BY sal DESC)
WHERE ROWNUM < 10;


        SELECT
    f2,
               COUNT(DECODE(greatest(f1,59), least(f1,100), 1, 0)) "Range 60-100",
               COUNT(DECODE(greatest(f1,30), least(f1, 59), 1, 0)) "Range 30-59",
               COUNT(DECODE(greatest(f1,29), least(f1,  0), 1, 0)) "Range 00-29"
        FROM   my_table
        GROUP BY f2;


SELECT ename "Name", sal "Salary",
              DECODE( TRUNC(sal/1000, 0), 0, 0.0,
                                          1, 0.1,
                                          2, 0.2,
                                          3, 0.3) "Tax rate"
FROM   emp;


COL NAME      DATATYPE
----------------------------------------
DNO                 NUMBER
SEX                 CHAR

SELECT dno, SUM(DECODE(sex,'M',1,0)) MALE,
             SUM(DECODE(sex,'F',1,0)) FEMALE,
             COUNT(DECODE(sex,'M',1,'F',1)) TOTAL
FROM   t1
GROUP BY dno;


SELECT EXP(SUM(LN(col1))) FROM srinu;


SELECT num
FROM satyam
GROUP BY num
HAVING COUNT(*) > 1;


*
**
***
****
*****

SELECT RPAD(DECODE(temp,temp,'*'),ROWNUM,'*')
FROM srinu1;


FUNCTION F_BALANCE_VALUE
(p_business_group_id number, p_payroll_action_id number,
p_balance_name varchar2, p_dimension_name varchar2) RETURN NUMBER
IS
l_bal number;
l_defined_bal_id number;
l_assignment_action_id number;
BEGIN
            SELECT assignment_action_id
              INTO l_assignment_action_id
              FROM
              pay_assignment_actions
                        WHERE
                        assignment_id = :p_assignment_id
                        AND payroll_action_id = p_payroll_action_id;
 
            SELECT
            defined_balance_id
            INTO
            l_defined_bal_id
            FROM
            pay_balance_types pbt,
            pay_defined_balances pdb,
            pay_balance_dimensions pbd
            WHERE
            pbt.business_group_id = p_business_group_id
            AND UPPER(pbt.balance_name) = UPPER(p_balance_name)
            AND pbt.business_group_id = pdb.business_group_id
            AND pbt.balance_type_id = pdb.balance_type_id
            AND UPPER(pbd.dimension_name) = UPPER(p_dimension_name)
            AND pdb.balance_dimension_id = pbd.balance_dimension_id;
           
    l_bal := pay_balance_pkg.get_value(l_defined_bal_id,l_assignment_action_id);
 
  RETURN (l_bal);
 
exception
             WHEN no_data_found THEN
                  RETURN 0; 
END;


FUNCTION f_element_value(
                         p_classification_name in varchar2,
                         p_element_name        in varchar2,
                         p_business_group_id   in number,
                         p_input_value_name    in varchar2,
                         p_payroll_action_id      in number,
                         p_assignment_id         in number
                         )
                          RETURN number
IS
     l_element_value   number(14,2) default 0;
     l_input_value_id  pay_input_values_f.input_value_id%type;
     l_element_type_id pay_element_types_f.element_type_id%type;
BEGIN
                        SELECT DISTINCT element_type_id
                        INTO   l_element_type_id
                        FROM   pay_element_types_f pet,
                                     pay_element_classifications pec
                        WHERE  pet.classification_id = pec.classification_id
                        AND    upper(classification_name) = upper(p_classification_name)
                        AND    upper(element_name) = upper(p_element_name)
                        AND    pet.business_group_id = p_business_group_id;

              SELECT input_value_id
                        INTO   l_input_value_id
                        FROM   pay_input_values_f
                        WHERE  upper(name) = upper(p_input_value_name)
                        AND    element_type_id = l_element_type_id;
           
            SELECT NVL(prrv.result_value,0)
            INTO   l_element_value
            FROM   pay_run_result_values prrv,
            pay_run_results prr,
                        pay_assignment_actions paa
              WHERE  prrv.run_result_id = prr.run_result_id
            AND    prr.assignment_ACTION_ID = paa.assignment_action_id
            AND    paa.assignment_id = p_assignment_id
            AND    input_value_id = l_input_value_id
              AND    paa.payroll_action_id = p_payroll_action_id;

            RETURN (l_element_value);
 
exception
             WHEN no_data_found THEN
                  RETURN 0;
END;


SELECT ename,
NVL(LENGTH(REPLACE(TRANSLATE(UPPER(RTRIM(ename)),'ABCDEFGHIJKLMNOPQRSTUVWXYZ'' ','                           @'),' ',''))+1,1) word_length
FROM emp;

Explanation :

TRANSLATE(UPPER(RTRIM(ename)),'ABCDEFGHIJKLMNOPQRSTUVWXYZ'' ','                           @') -- This will translate all the characters FROM A-Z including a single quote to a space. It will also translate a space to a @.

REPLACE(TRANSLATE(UPPER(RTRIM(ename)),'ABCDEFGHIJKLMNOPQRSTUVWXYZ'' ','                           @'),' ','') -- This will replace every space with nothing in the above result.

LENGTH(REPLACE(TRANSLATE(UPPER(RTRIM(ename)),'ABCDEFGHIJKLMNOPQRSTUVWXYZ'' ','                           @'),' ',''))+1 -- This will give u the count of @ characters in the above result.


CREATE OR REPLACE FUNCTION is_leap_year (p_date IN DATE)  RETURN VARCHAR2
 AS
 v_test DATE;
 BEGIN
             v_test := TO_DATE ('29-Feb-' || TO_CHAR (p_date,'YYYY'),'DD-Mon-YYYY');
             RETURN 'Y';
 EXCEPTION
 WHEN OTHERS THEN
             RETURN 'N';
 END is_leap_year;

SQL> SELECT hiredate, TO_CHAR (hiredate, 'Day') weekday
          FROM emp
          WHERE is_leap_year (hiredate) = 'Y';

17 comments:

  1. This was really a good post and also very informative.for more details

    http://www.tekclasses.com/

    ReplyDelete
  2. Your blog is really useful. Thanks for sharing this useful
    blog..Suppose if anyone interested to learn

    http://www.tekclasses.com/

    ReplyDelete
  3. Very good collection of question and answers thank you for sharing this article. Know more about ETL Testing Training

    ReplyDelete
  4. Very good collection of question and answers thank you for sharing this article. Know more about ETL Testing Training

    ReplyDelete
  5. very impressive and appreciate for sharing with us.

    ReplyDelete
  6. Hello,
    This is excellent information. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...SQL Interview Questions.

    ReplyDelete
  7. OlĂ ,


    Allow me to show my gratitude bloggers. You guys are like unicorns. Never seen but always spreading magic. Your content is yummy. So satisfied.

    I am attempting to create a single SQL Statement that will get me record counts from 3 Tables and have the results returned in a single Record.

    I Feel I am close because I have CTE statement that gets me my results but If there counts for multiple tables on the same record I get 2 records for that customer.
    WITH
    cte as
    (SELECT DUNS.Duns, DUNS.Duns_Name, 0 AS CoilCountInbound, COUNT(LIVMATL.OP_Crnt_ID) AS CoilCount, 0 AS CoilCountShipped, 0 AS CoilCountTotal
    FROM LIVMATL LEFT OUTER JOIN DUNS ON LIVMATL.Stl_Prod_Duns = DUNS.Duns
    WHERE DUNS.Customer_Type = 'I' OR DUNS.Customer_Type = 'C'
    GROUP by DUNS.Duns,DUNS.Duns_Name),

    cte2 AS
    (SELECT DUNS.Duns, DUNS.Duns_Name, 0 AS CoilCountInbound, 0 AS CoilCount, COUNT(LIVILOD.OP_Crnt_ID) AS CoilCountShipped, 0 AS CoilCountTotal
    FROM LIVILOD LEFT OUTER JOIN DUNS ON LIVILOD.Stl_Prod_Duns = DUNS.Duns LEFT OUTER JOIN LIVMLOD ON (LIVILOD.Master_Ref_Nbr = LIVMLOD.Master_Ref_Nbr)
    WHERE (DUNS.Customer_Type = 'I' OR DUNS.Customer_Type = 'C') AND (LIVMLOD.Ship_Date >= '04/06/18' AND LIVMLOD.Ship_Date <= '04/13/18')
    GROUP by DUNS.Duns,DUNS.Duns_Name),

    cte3 AS
    (SELECT DUNS.Duns, DUNS.Duns_Name, COUNT(INBOUND.SP_Matl_ID) AS CoilCountInbound, 0 AS CoilCount, 0 AS CoilCountShipped, 0 AS CoilCountTotal
    FROM INBOUND LEFT OUTER JOIN DUNS ON INBOUND.Stl_Prod_Duns = DUNS.Duns
    WHERE DUNS.Customer_Type = 'I' OR DUNS.Customer_Type = 'C'
    GROUP by DUNS.Duns,DUNS.Duns_Name)

    SELECT
    COALESCE(A.Duns, B.Duns, C.Duns) as Duns,
    COALESCE(A.Duns_Name, B.Duns_Name, C.Duns_Name) as Duns_Name,
    ISNULL(C.CoilCountInbound,0) AS CoilCountInbound,
    ISNULL(A.CoilCount,0) AS CoilCount,
    ISNULL(B.CoilCountShipped,0) AS CoilCountShipped,
    COALESCE(A.CoilCount,0) + COALESCE(B.CoilCountShipped,0) + COALESCE(C.CoilCountInbound,0) AS CoilCountTotal

    FROM cte A FULL JOIN cte2 B ON A.Duns = B.Duns FULL JOIN cte3 C on B.Duns = C.Duns

    ORDER BY Duns_Name
    Results:
    Records 6 & 7, 10 & 11


    I expected those to be in
    a single line for that customer. Names and ID's are the same....






    It was cool to see your article pop up in my google search for the process yesterday. Great Guide.
    Keep up the good work!


    Thanks a heaps,
    Ajeeth Kapoor

    ReplyDelete
  8. This information you provided in the blog that is really unique I love it!! Thanks for sharing such a great blog Keep posting..
    ETL Interview Questions and Answers

    ReplyDelete
  9. I love this blog . This is one of the best blog i ever seen. It's all about what i'm searching for. I love to read this blog again and again . Every time i enter this blog i get something new. This blog inspire me to write new blog. I write a blog name tutorialabc.com. It's about sql,c#,net etc

    ReplyDelete
  10. Nice set of interview questions and answers.i have gone through it very helpful one thanks for sharing...
    SQL Interview Questions & Answers.

    ReplyDelete
  11. Nice set of interview questions and answers.i have gone through it very helpful one thanks for sharing...
    Best Training and Real Time Support

    Android Training From India

    Appium Training From India

    ReplyDelete


  12. My name is Leah Brown, I'm a happy woman today? I told myself that any loan lender that could change my life and that of my family after having been scammed separately by these online loan lenders, I will refer to anyone who is looking for loan for them. It gave me and my family happiness, although at first I had a hard time trusting him because of my experiences with past loan lenders, I needed a loan of $300,000.00 to start my life everywhere as single mother with 2 children, I met this honest and God fearing online loan lender Gain Credit Loan who helped me with a $300,000.00 loan, working with a loan company Good reputation. If you are in need of a loan and you are 100% sure of paying the loan please contact (gaincreditloan1@gmail.com)

    ReplyDelete
  13. Nice information, this is will helpfull a lot, Thank for sharing, Keep do posting i like to follow this
    informatica online training
    informatica online course

    ReplyDelete

  14. Thank you for sharing wonderful information with us to get some idea about that content.
    ETL Testing Online Training
    ETL Testing Certification

    ReplyDelete
  15. Thanks for sharing your expertise in Salesforce training. Your blog posts are a valuable resource for those looking to build their Salesforce skills and explore career opportunities in the Salesforce ecosystem. Please visit our website:- Salesforce Training

    ReplyDelete