Complex Queries in SQL

Published on November 2016 | Categories: Documents | Downloads: 80 | Comments: 0 | Views: 725
of 18
Download PDF   Embed   Report

Complex Queries in SQL

Comments

Content

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
select * from emp where rownum <= &n;

from

a

table.

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
select count(EMPNO), b.deptno, dname from emp
a.deptno(+)=b.deptno group by b.deptno,dname;

department
a, dept b

wise.
where

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
Select * from emp where sal>=1000 And sal<2000

between

1000

to

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
SELECT
deptno,
FROM
GROUP
HAVING COUNT(empno) > 2

wise

where more
sum(sal)
BY

than

2 employees exist.
As
totalsal
emp
deptno

Select Query
Page 1 of 3
The SELECT query is the most often used query in any database. So , learning this query is very
important. Even if you don't write it manually, as some tools make your task easier by providing
code assists. But this query helps you to understand many aspects of database concepts, ranging
from DBA task to PL/SQL. I hope this tutorial helps learning SELECT query faster and easier.
We will be referring tables from default schema/user SCOTT in Oracle.
The generalized select query looks like :
?
1
2 SELECT [ DISTINCT| ALL]
3
{ * | [columnName [ AS newColumnName ] ] ,
4
5
[columnName1 [ AS newColumnName1]],
6
7
.........,
8
9
.........,
10
}
11
12
FROM tableName [ALIAS][,]
13
14
[WHERE <condition>]
15
16
[GROUP BY columnlist ] [HAVING <condition>]
17
18
[ORDER BY columnlist]
19
We will start with simple query and then keep on building complex queries.

1.

Select all the details of the employee from emp table.

?
1

SELECT * FROM emp;

2. Select only the names of all the employees in emp table;
?
1

SELECT ename FROM emp;

3. Select records using multiple columns;
?
1 SELECT eno,ename,sal FROM emp;
4. Select records Using alias;
?
1 SELECT eno,ename,salary AS sal FROM emp;
a. Select records using multiple alias
?
1 SELECT eno AS empno,ename AS empname ,sal AS salary FROM emp;
b. Using functions to enhance alias
?
1 SELECT count(sal) as totalsal FROM emp;
5. Derived or Computed fields: Columns values were manipulated as it gets retrived.
a. Find the monthly salary of employee,( The salary stored is on Annum basis).
?
1

SELECT sal / 12 FROM emp;

b. Using Alias to decorate derived or computed fields.
?

1 SELECT sal / 12 AS monthly_salary FROM emp
c. Calculate the sum of monthly salary and the commissions of the employee.
?
1 SELECT ename,(sal / 12) + nvl(comm,0) AS monthsalwithcomm FROM emp;
Page 2 of 3
1. Using Aggregate functions: Count,Min,Max,Sum,Avg.
a. Find the number of rows in emp ?
?
1

SELECT count(*) FROM emp;

b. Find the how many different Job profile are there in Employee table ?
?
1 SELECT COUNT(DISTINCT job) FROM emp;
c. Find out how many people were given commision ? ( Count function does n't
include null as it counts)
?
1 SELECT COUNT(comm)FROM emp;
d.
e.
f.
?
1
Q5:Select

records

from

5.1
?
1 SELECT e.ename, d.deptno,e.sal FROM emp e,dept d;

two

tables;

5.2 Select records from two tables depending condition suppose where deptno of from both emp
and dept mathes
?
1 Select e.ename, d.deptno,e.sal from emp e,dept d
Q6:

Select

records

where e.deptno=d.deptno;

using

where

clause;

6.1
?
1 SELECT ename,sal FROM emp

WHERE sal>2000

6.2 Select records from emp and dept where both deptno matches
?
1 SELECT e.ename,e.sal,d.deptno FROM emp e,dept d WHERE e.deptno=d.deptno
6.3 Select secords where empno=1003
?
1 SELECT * FROM emp WHERE empno=1003
6.4 Select records where ename is KING
?
1 SELECT * FROM emp WHERE ename='KING';
Q7:Select

records

using

7.1
?
1 SELECT ename,sal FROM emp WHERE deptno=10 OR deptno= 20
7.2
?
1 SELECT * FROM emp WHERE city='LONDON' OR city='PARIS'
7.3
?
1 SELECT * FROM emp WHERE sal>2000 OR comm IS NOT NULL

or;

Q8:

Select

records

using

between

and;

8.1
?
1 SELECT * FROM emp WHERE sal BETWEEN 2000 AND 3000
8.2
?
1 SELECT * FROM dept WHERE deptno BETWEEN 20 AND 40;
8.3
?
1 SELECT * FROM emp WHERE empno BETWEEN 1001 TO 1010;
Q9:

Select

records

using

9.1
?
1 SELECT * FROM emp WHERE ename IN('SCOTT','WARD','ALLEN')
9.2
?
1 SELECT ename FROM emp WHERE sal IN(1000,2000.3000.3200,3300);
Q10: Select records using not in;

?
1 SELECT * FROM emp WHERE ename NOT IN('SCOTT','WARD','ALLEN')
Q11: Select records using null;

?
1 SELECT * FROM emp WHERE comm IS NULL;
Q12:Select records using not null;

?
1 SELECT * FROM emp WHERE comm IS NOT NULL;

in;

Q13:Select

records

using

like;

13.1
?
1 SELECT * FROM emp WHERE ename LIKE'S%';
13.2
?
1 SELECT * FROM emp WHERE ename LIKE 'sC___';
13.3
?
1 SELECT * FROM emp WHERE ename LIKE 'AL%';
13.4
?
1 SELECT * FROM emp WHERE ename LIKE 'A_L_N';
13.5
?
1 SELECT * FROM emp WHERE ename LIKE '___L%';

Q14:Select records using not like;

?
1 SELECT * FROM emp WHERE ename NOT LIKE 'A%';
Q15:Select
15.1

records

using

multiple

?
1 SELECT * FROM emp WHERE comm IS NOT NULL AND sal >2000 AND deptno>20;
15.2
?
1 SELECT * FROM emp WHERE sal>2000 AND deptno>20 AND ename NOT LIKE(A%)

conditions.

15.3
?
SELECT * FROM emp WHERE deptno<20 AND comm IS NOT NULL OR sal

1IN{1000,2000,3000,4000};
Q16:Select

records

using

function;

16.1
?
1 SELECT ename,sum(sal+comm) AS total FROM emp
16.2
?
1 SELECT count(*) FROM emp;
2 16.3
?
1 SELECT deptno,avg(sal) AS avgsal FROM emp GROUP BY deptno;

Q17:Select

records

using

order

by;

17.1
?
1 SELECT * FROM emp ORDER BY sal
17.2
?
1 SELECT ename,sal FROM emp ORDER BY sal,ename
17.3
?
1 SELECT empno,ename,sal FROM emp ORDER BY sal DESC,empno,empname
Page 3 of 3

Q18:Select

18.1
?

records

using

group

by;

1 SELECT deptno,sum(sal)FROM emp GROUP BY deptno
18.2
?
1 SELECT deptno,sum(sal) FROM emp GROUP BY deptno,ename ,empno
Q19:Select records using group by and having clause;
?
1 SELECT deptno,sum(sal) GROUP BY deptno HAVING deptno>20
Q20:select

with-in

select;

20.1
?
1 SELECT * FROM emp WHERE max(sal)<(SELECT max(sal) FROM emp)
20.2
?
1 SELECT * FROM emp WHERE deptno=(SELECT deptno FROM dept);
20.3
?
1 SELECT * FROM emp WHERE deptno NOT IN (SELECT deptno FROM dept);
Q21:create a table by selecting record from another table;

?
1 CREATE TABLE emp2 AS SELECT * FROM emp;
Q22:Select records using exist;

?
SELECT deptno FROM dept d WHERE EXISTS (SELECT * FROM emp e WHERE d.deptno =

1e.deptno);

Q23:Select sysdate;

?
1

SELECT sysdate FROM dual;

Q24:Select constraint name, constraint_type;

?
1 SELECT constraint_name, constraint_type
2 FROM user_constraints
3 WHERE table_name = 'emp';

Q25:Select

nextval,

currval

from

sequence;

25.1
?
1 SELECT emp_sequence.nextval FROM dual
25.2
?
1 SELECT emp_sequence.currval FROM dual
SQL Joins
Page 1 of 5

Joins In Sql
SQL joins are used to fetch data from two or more tables, based on conditions between
tables.
There are various type of joins. Like
=>Equi-Joins
=> Self-Join
=> Outer-Join
=> Semi-Join
=>Anti-Join
=> Cross-Join
Equi-join
It is a sql join where we use the equal sign as the comparison operator i.e "=" between two tables.By default this join is
inner-equi-join.

Examples:
Example1: Suppose we want to fetch records from two tables emp, dept where deptno of
employee is equal to dept no of dept.
The query is:

?
1 SELECT * FROM EMP E,DEPT D WHERE E.DEPTNO=D.DEPTNO;

Another way to write it,like

?
1SELECT * FROM EMP E INNER JOIN DEPT

ON D WHERE E.DEPTNO=D.DEPTNO;

Example2: Suppose there are two tables category and product.Both table contains
category_id. We want to fetch the records where both tables contain same category_id .
?
1SELECT * FROM CATEGORIES C ,PRODUCTS P where P.CATEGORYID = C.CATEGORYID;

Another way to write it,like
?
1SELECT * FROM CATEGORIES C INNER JOIN PRODUCTS P ON P.CATEGORYID = C.CATEGORYID

Example3: Suppose there are two table Employee and Bonus. We want to fetch records
where both tables contain same empno.
?
1 SELECT * FROM EMPLOYEE E,BONUS B WHERE E.EMPNO=B.EMPNO;

Another way to write it,like
?
1SELECT * FROM EMPLOYEE INNER JOIN EBONUS B ON E.EMPNO=B.EMPNO;

Page 2 of 5
Non-Equi Join:
A Non- Equi Join is a SQL Join where condition is established between table using all
comparison operators (>=, <=, <, >) can used except the equal (=) .

Examples
Example1: Suppose there are two tables Employee and Salary_Grade.Salary_Grade
contains lowsal,Hisal.We want to fetch all records where sal of employees less than lowsal.
?
1
2 SELECT * FROM EMPLOYEE E, SALARY_GRADE SD WHERE E.SAL<=SD.LOWSAL.
3
Example2: There are two table emp and dept. We want to fetch records of emp where
deptno between 10 and 20.

?
1
2
3 SELECT * FROM EMP E, DEPT D WHERE D.DEPTNO BETWEEN 10 AND 20;
4
5
Example3:There are two table Emp and Emp_details. Emp_details contains
emp_no,f_name,L_name,City,Pin,Dob. Fetch the empno,f_name,sal,city where sal>=4000.
?
1SELECT E.EMPNO,ED.SAL,ED.F_NAME,ED.CITY,ED.PIN,ED.DOB FROM EMP E,EMP_DETAILS
2ED WHERE E.SAL>=4000;
Example4: From the last examle fetch the records from Emp table whose city in between
DELHI,BANGALORE,PUNE.
?
1 SELECT * FROM EMP WHERE EMP_DETAILS.CITY IN("DELHI","BANGALORE","PUNE");
2
Page 3 of 5
Self Joins:
A self means joining columns of a table to itself. It fetches record from same table only
and for that we have to mention table alias name twice times.

Example1: In Emp table there are two columns empno and mgr. Fetch the records where
empno and mgr are same.
?
1 SELECT * FROM EMP E1, EMP E2 WHERE E1.EMPNO=E2.MGR
2
Example2: In Emp_SAL table there are two columns gross_pay and net_pay. Fetch the
records where gross_pay and net_pay are same.
?
1 SELECT * FROM EMP_SAL E1,EMP_SAL E2 WHERE E1.GROSS_PAY=E2.NET_PAY
2
Example3:In Employee_details table retrieve the record whose city are same.
?
1SELECT * FROM EMPLOYEE_DETAILS E1,EMPLOYEE_DETAILS E2 WHERE E1.CITY=E2.CITY
2
Example4:Retrieve the records from Emp table whose jobs are same
?
1 SELECT * FROM EMP E1,EMP E2 WHERE E1.JOB=E2.JOB;
2
Page 4 of 5
Outer-Join
Outer join returns all records from one table and those records from another table where
meets joining condition.
There are three types of outer joins
=>Left Outer-join
=>Right outer-join
=>Full outer-join
Left Outer-join

In Left Outer-Join retrieves the unmatched rows and matched from the left (1st)table and
only matched rows from right(2nd) table.
The result of a left outer join for table A and B always contains all records of the Left table (A),
even if the condition does not match with record in the Right table (B). This means that a left
outer join returns all the values from the left table, plus matched values from the Right table or
returns NULL in case of no matching join condition satisfied.

Example Select an employee's department where they have not been assigned to a
department
?
1
2
3 SELECT * FROM EMP LEFT OUTER JOIN DEPT ON EMP.DEPTNO=DEPT.DEPTNO;
4
5
or
?
1 SELECT * FROM EMP,DEPT WHERE EMP.DEPTNO=DEPT.DEPTNO(+);
2
Right Outer-join

In Right Outer-Join retrieves the unmatched rows and matched from the Right table and
only matched rows from Left table.
The result of a Right outer join for table A and B always contains all records of the Right table
(B), even if the condition does not match with record in the Left table (A). This means that a
Right outer join returns all the values from the Right table, plus matched values from the Left
table or returns NULL in case of no matching join condition satisfied.
Example List dept no., Dept name for all the departments in which there are no employees
in the department.
?
1 SELECT * FROM EMP RIGHT OUTER JOIN DEPT ON EMP.DEPTNO=DEPT.DEPTNO
2
OR
?
1 SELECT * FROM EMP,DEPT EMP.DEPTNO(+)=DEPT.DEPTNO
Full Outer-join

Full Outer-join is combination of left and right outer join.It returns both match and
unmatched row from both tables.

Example Retrieve each employee who is in a department and each department that has an
employee and also each employee who is not part of a department and each department
which doesn't have an employee.
?
1 SELECT * FROM EMP FULL OUTER JOIN DEPT ON EMP.DEPTNO=DEPT.DEPTNO
2
OR
?
1 SELECT * FROM EMP,DEPT EMP.DEPTNO(+)=DEPT.DEPTNO(+)

Page 5 of 5
Anti Join Suppose there are two tables A and B Anti-join between two tables A AND B
returns rows from the table A, for which there are no corresponding rows in the Table B.
Anti-join is also a sub-query in which parent query doesn't depend upon child query.
Example1:List deptno. Dept name for all the departments in which there are no employees
in the department.
?
1SELECT * FROM DEPT D WHERE NOT EXIST (SELECT * FROM EMP E WHERE D.DEPTNO =
2E.DEPTNO)
Example2:There are two tables Emp1 and Emp2. Fetch the record those are present in
Emp1 not in Emp2
?
1 SELECT * FROM EMP1 MINUS SELECT * FROM EMP2
2
Semi Join
Semi-join between two tables returns rows from table A ,where one or more matches are
found in table B.It is kown as Co-Related-Sub-query, Where parent query depents upon
Child query.
Example1:There are two tables Emp1 and Emp2. Fetch the record common in Emp1 and
emp2.
?
1 SELECT * FROM EMP1 INTERSECT SELECT * FROM EMP2

2
Example2:Select records from emp and Dept where Deptno of Emp matches Deptno in
Dept
?
1 SELECT * FROM EMP WHERE EMP.DEPTNO IN(SELECT DEPTNO FROM DEPT)
2
Cross Join

Cross join jenerally generate cross product between two table. Each row of Table1
,combined with each rows of Table2.
Example Generate cross join between Emp and Dept
?
1 SELECT * FROM EMP CROSS JOIN DEPT;
or
?
1

SELECT * FROM EMP,DEPT;

Sponsor Documents

Or use your account on DocShare.tips

Hide

Forgot your password?

Or register your new account on DocShare.tips

Hide

Lost your password? Please enter your email address. You will receive a link to create a new password.

Back to log-in

Close