0% found this document useful (0 votes)
534 views

Complex Queries in SQL

The document provides examples of complex SQL queries for common interview questions. It includes queries to fetch alternate records, find the 3rd highest/lowest salary, select the first or last n records, find departments with no employees, and more. Examples are provided for getting the nth highest salary, selecting distinct records, deleting duplicate rows, counting employees by department, and other common SQL tasks.

Uploaded by

Vibhor Jain
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
534 views

Complex Queries in SQL

The document provides examples of complex SQL queries for common interview questions. It includes queries to fetch alternate records, find the 3rd highest/lowest salary, select the first or last n records, find departments with no employees, and more. Examples are provided for getting the nth highest salary, selecting distinct records, deleting duplicate rows, counting employees by department, and other common SQL tasks.

Uploaded by

Vibhor Jain
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Complex Queries in SQL ( Oracle )

These questions are the most frequently asked in interviews.

1. To fetch ALTERNATE records from a table. (EVEN NUMBERED)


select * from emp where rowid in (select decode(mod(rownum,2),0,rowid, null)
from emp);

2. To select ALTERNATE records from a table. (ODD NUMBERED)


select * from emp where rowid in (select decode(mod(rownum,2),0,null ,rowid)
from emp);

3. Find the 3rd MAX salary in the emp table.


select distinct sal from emp e1 where 3 = (select count(distinct sal) from emp e2
where e1.sal <= e2.sal);

4. Find the 3rd MIN salary in the emp table.


select distinct sal from emp e1 where 3 = (select count(distinct sal) from emp
e2where e1.sal >= e2.sal);

5. Select FIRST n records from a table.


select * from emp where rownum <= &n;

6. Select LAST n records from a table


select * from emp minus select * from emp where rownum <= (select count(*) -
&n from emp);

7. List dept no., Dept name for all the departments in which there are no
employees in the department.
select * from dept where deptno not in (select deptno from emp);
alternate solution: select * from dept a where not exists (select * from emp b
where a.deptno = b.deptno);
altertnate solution: select empno,ename,b.deptno,dname from emp a, dept b
where a.deptno(+) = b.deptno and empno is null;

8. How to get 3 Max salaries ?


select distinct sal from emp a where 3 >= (select count(distinct sal) from emp b
where a.sal <= b.sal) order by a.sal desc;

9. How to get 3 Min salaries ?


select distinct sal from emp a where 3 >= (select count(distinct sal) from emp b
where a.sal >= b.sal);
10. How to get nth max salaries ?
select distinct hiredate from emp a where &n = (select count(distinct sal) from
emp b where a.sal >= b.sal);

11. Select DISTINCT RECORDS from emp table.


select * from emp a where rowid = (select max(rowid) from emp b where
a.empno=b.empno);

12. How to delete duplicate rows in a table?


delete from emp a where rowid != (select max(rowid) from emp b where
a.empno=b.empno);

13. Count of number of employees in department wise.


select count(EMPNO), b.deptno, dname from emp a, dept b where
a.deptno(+)=b.deptno group by b.deptno,dname;

14. Suppose there is annual salary information provided by emp table. How to
fetch monthly salary of each and every employee?

select ename,sal/12 as monthlysal from emp;

15. Select all record from emp table where deptno =10 or 40.

select * from emp where deptno=30 or deptno=10;

16. Select all record from emp table where deptno=30 and sal>1500.

select * from emp where deptno=30 and sal>1500;

17. Select all record from emp where job not in SALESMAN or CLERK.

select * from emp where job not in ('SALESMAN','CLERK');

18. Select all record from emp where ename in


'BLAKE','SCOTT','KING'and'FORD'.

select * from emp where ename in('JONES','BLAKE','SCOTT','KING','FORD');

19. Select all records where ename starts with S and its lenth is 6 char.

select * from emp where ename like'S____';

20. Select all records where ename may be any no of character but it should
end with R.

select * from emp where ename like'%R';


21. Count MGR and their salary in emp table.

select count(MGR),count(sal) from emp;

22. In emp table add comm+sal as total sal .

select ename,(sal+nvl(comm,0)) as totalsal from emp;

23. Select any salary <3000 from emp table.

select * from emp where sal> any(select sal from emp where sal<3000);

24. Select all salary <3000 from emp table.

select * from emp where sal> all(select sal from emp where sal<3000);

25. Select all the employee group by deptno and sal in descending order.

select ename,deptno,sal from emp order by deptno,sal desc;

26. How can I create an empty table emp1 with same structure as emp?

Create table emp1 as select * from emp where 1=2;

27. How to retrive record where sal between 1000 to 2000?


Select * from emp where sal>=1000 And sal<2000

28. Select all records where dept no of both emp and dept table matches.
select * from emp where exists(select * from dept where
emp.deptno=dept.deptno)

29. If there are two tables emp1 and emp2, and both have common record. How
can I fetch all the recods but common records only once?
(Select * from emp) Union (Select * from emp1)

30. How to fetch only common records from two tables emp and emp1?
(Select * from emp) Intersect (Select * from emp1)

31. How can I retrive all records of emp1 those should not present in emp2?
(Select * from emp) Minus (Select * from emp1)

32. Count the totalsa deptno wise where more than 2 employees exist.
SELECT deptno, sum(sal) As totalsal
FROM emp
GROUP BY deptno
HAVING COUNT(empno) >
Question 1: What are the results returned from the
T-SQL below?

CREATE TABLE a (id INT, second_id INT);


INSERT a (id, second_id)

SELECT 1, 3
UNION ALL
SELECT 2, NULL
UNION ALL
SELECT 3, 3;

SELECT
COUNT(*) AS CountTotal
, COUNT(second_id) AS CountSecondId
, COUNT(DISTINCT second_id) AS CountDistinctSecondId
FROM a;

Answer 1:
3,2,1
(Because Count(Column_Name) doesnt consider NULL Value)

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

2. Given the following tables:>

SELECT * FROM runners;


+----+--------------+
| id | name |
+----+--------------+
| 1 | John Doe |
| 2 | Jane Doe |
| 3 | Alice Jones |
| 4 | Bobby Louis |
| 5 | Lisa Romero |
+----+--------------+

SELECT * FROM races;


+----+----------------+-----------+
| id | event | winner_id |
+----+----------------+-----------+
| 1 | 100 meter dash | 2 |
| 2 | 500 meter dash | 3 |
| 3 | cross-country | 2 |
| 4 | triathalon | NULL |

select * from runners where id not in (select winner_id from races)

Explain your answer and also provide an alternative version of this


query that will avoid the issue that it exposes.

Answer 2:

As races table contains the record with NULL value the Query will not
yield the desired result
Correct Query: select * from runners where id not in (select
winner_id from races where winner_id is not null)

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

Question 3:

What will be the result of the query below? Explain your answer and
provide a version that behaves correctly.
select case when null = null then 'Yup' else 'Nope' end as Result;

Answer 3:

Result: Nope

Because a NULL value cannot be compared with NULL, we can make


use of ISNULL() function to replace the value with certain number say 1

Correct Query: select case when Isnull(null,1) = Isnull(null,1)


then 'Yup' else 'Nope' end as Result;

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

Question 4:

Given a table, such as the one below, that hasm = male and f = female
Swap all f and m values (i.e., change all f values to m and vice versa)
with a single update query and no intermediate temp table.

Id Name Sex Salary

1 A m 25002

2 B f 15003

3 C m 55004

4 D f 500

Answer 4:

Update table
Set Sex=(Case Sex when m then f else m end)
***************************************************

Question 5:

Assume a schema of

Emp ( Id, Name, DeptId )

, Dept ( Id, Name).

If there are 10 records in the Emp table and 5 records in the Dept table,
how many rows will be displayed in the result of the following SQL
query:
Select * From Emp, Dept

Answer 5:

Its 10*5=50 rows

Explanation: So simply its multiplication of the 2 numbers,say if table A


have 17 records and table B have 3 records then

No. of rows for the Query : Select * from TableA,TableB

Would be 17*3=51

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

Question 6:

What is wrong with this SQL query? Correct it so it executes properly.


SELECT Id, YEAR(BillingDate) AS BillingYear FROM Invoices
WHERE BillingYear >= 2010;

Answer 6:
The where clause cannot read the name given to the column in the Select
clause because the execution of the Query takes place in following order

From
Where
Groub by
Having
Select
Order by

Correct Query:
SELECT Id, YEAR(BillingDate) AS BillingYear
FROM Invoices
WHERE YEAR(BillingDate) >= 2010;

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

Question 7:

Considering the database schema displayed in the SQLServer-style


diagram below, write a SQL query to return a list of all the invoices. For
each invoice, show the Invoice ID, the billing date, the customers name,
and the name of the customer who referred that customer (if any). The
list should be ordered by billing date.
Answer 7:

Select I.id,I.billingdate,C.Name,V.Name as ReferredByz


From Invoices I
Join Customer on C.Id=I.Customerid
Left Join Customer V on C.id=V.ReferredBy

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

Question 8:

I have a table which contains positive and negative numbers. I have to


find out sum of positive and negative numbers

Answer 8:

Select
sum(case when num > 0 then num else null end) pos,
sum(case when num < 0 then num else null end) neg
from temp
***************************************************

Question 9:

Example of RECURSIVE CTE

Say you have table called


dbo.Policy

CREATE TABLE [dbo].[Policy](


[PolicyNo] [int] NULL,
[StartPg] [int] NULL,
[EndPg] [int] NULL)

It contains the following record


PolicyNo StartPg EndPg
100 1 5
200 50 55
300 90 95

Now in another table

CREATE TABLE [dbo].[PolicyPg](


[PolicyNo] [int] NULL,
[PageNo] [int] NULL
) ON [PRIMARY]

you have to insert the records dynamically determining the page range
between the StartPg and EndPg from the first table i.e. [dbo].[Policy]
and insert the page numbers individually for each policy number in
second table i.e. [dbo].[PolicyPg]

Desired Result in [dbo].[PolicyPg] should look like this:


PolicyNo PageNo
100 1
100 2
100 3
100 4
100 5
200 51
200 52
200 53
200 54
200 55
200 50
300 90
300 91
300 92
300 93
300 94
300 95

Answer 9:

This can be achieved by making use of Recursive CTE


With Tab as(
Select PolicyNo,StartPg from Policy
union all
Select P.PolicyNo,T.StartPg+1 from Policy P,Tab T
where P.PolicyNo=T.PolicyNo and T.StartPg+1<=P.EndPg
)

Select * from Tab


order by PolicyNo

***************************************************
Question 10:

There is a table called [Tab A] which contains the following record


inside it

S.NO. ColA ColB ColC ColD

1 23 32 44 55

2 44 65 78 24

3 67 99 22 56

4 12 15 18 19

Desired Result: Get the maximum value of individual Row in a


new column(highlighted in yellow) i.e.

Answer 10:

I can think again of making use of CTE expression in this case, but
experts out there can follow any approach which they feel is more
simple and easy to write
;With tabB as
(Select ColA,ColB,ColC,ColD,ROW_NUMBER() over(order by
ColA) as RowNum from TabA),

tabC as
(Select RowNum,ColA as Col from tabB
union all
Select RowNum,ColB from tabB
union all
Select RowNum,ColC from tabB
union all
Select RowNum,ColD from tabB),

tabD as
(Select B.RowNum,ColA,ColB,ColC,ColD,max(Col) as MaxVal from
tabB B,tabC C where B.RowNum=C.RowNum group by
ColA,ColB,ColC,ColD,B.RowNum)

Select * from tabD

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

Question 11:

Now lets see how well you understand simple


JOINS. Kindly read this carefully as there are
chances of you making mistakes in this simple
question.

Say there are 2 tables TableA and TableB


The main motive here is to understand that the value which are
common in both table i.e. 1 in our case,so how different joins would
appear.

A. INNER JOIN

Select * from dbo.tableA A


join tableB B on A.ColumnA=B.ColumnB

Answer A:

ColumnA ColumnB

1 1

1 1

B. LEFT OUTER JOIN

Select * from
dbo.tableA A
left join tableB B on A.ColumnA=B.ColumnB

Answer B:

ColumnA ColumnB
1 1

1 1

2 NULL

NULL NULL

C. RIGHT OUTER JOIN

Select * from dbo.tableA A


right join tableB B on A.ColumnA=B.ColumnB

Answer C:

ColumnA ColumnB

1 1

1 1

NULL NULL

You might also like