Вы находитесь на странице: 1из 67

SQL

 DATA: Data is a useful information and we store all the


data in centralize location called Database.
 DBMS: It is responsible for all type of operations such as
retrieving an information, fetching, modifying, insertion
and removal of data.
DBMS acts like intermediate.

 TYPES OF DBMS:
1. HDBMS: In HDBMS all the data are stored in the tree
structure, in this HDBMS retrieving a data is difficult.
2. NDBMS: In NDBMS all the data are stored in tree
structure as well as all the data are interconnected in
network fashion. In NDBMS insertion of data is
difficult.
3. RDBMS: In RDBMS all the data are stored in tables
and tables may have some relation.
 SQL: It is a language where we can interact with the
database in the form of queries.
SQL is a language and my-sql is a database.
We have many database in market like Oracle, my-sql, ms-
sql, Derby, Mongo DB, IBM2.
We are using Oracle 10G but latest versions are 11G and
12C
 DATA MODEL:

Database creation process


Collect all the requirements from a customer.
While collecting specific entity and attribute
Entity might be living or non-living things and attributes
are features are of those entity.
 SUB LANGUAGES OF SQL:
1. DQL
2. DDL
3. DML
4. DTL
5. DCL
 COMPOSITE ATTRIBUTE: If the attributes are composite,
they are further divided in a tree like structure. Every node
connected to its attributes.

 MULTIVALUED ATTRIBUTE: Multivalued attribute are


depicted by double ellipse.
 Derived Attribute: Derived attribute are depicted by
dashed ellipse
It is an attribute whose value is calculated from other
attributes.

 DATA QUERY LANGUAGE:


In DQL language we will be retrieving information from a
database in different form.
We will be using clause to retrieve a formation.
1. SELECT CLAUSE: It is a clause by using we can retrieve
information.
2. FROM CLAUSE: It is used to tell from where we should
retrieve an information.
Select * from tab;
'*' in the sense retrieve everything.
'tab' is a keyword to retrieve existing table information.
Once we execute the above query we will be getting inbuilt
table information(select * from tab;)
Query to retrieve information from EMP table.--> select *
from emp;

 SQL is not a case-sensitive language.


Q: Write a query to retrieve information from department
table?
Ans: select * from dept;

 By using SELECT clause we can perform projection,


selection, and joins.

To see the page size  show pagesize;


To see the line size  show linesize;
To set the page size  set pagesize 150;
To set the line size  set linesize 150;

 Setting a page size and line size is temporary. Once if we


close our sql editor the page size and line size will set back
to default values.
 PROJECTION:
Projection means selecting column wise.
By using SELECT clause we can achieve projection and can
decide which column to select.
Query to retrieve employee name from a table.--> select
ename from emp;
Q: Write a query to retrieve employee name and salary from
emp table?
Ans: SELECT ename, salary from emp;

 While retrieving more than one column all the column


name should be separated by ','.
 ALIASING THE COLUMN NAME:
We can Alias a column name and Alias is done only
for that particular output.
'As' is a keyword for Aliasing the column name.
Q: Write a query to retrieve emp name and salary
while retrieving ename as Emp_name and sal as
salary?
Ans: SELECT ENAME AS Emp_name, sal as salary
from emp;
Q: Write a query to retrieve ename as Emp name?
Ans: Error select ename= "Emp NAME" from
emp;

Note: While Aliasing if 'AS' keyword is missed out


then immediate next work is considered as Alias
name.
Note: Alias names should be enclosed within(" ")
in two cases:
1. When we want to maintain same case.
2. When our alias names are more than one word.
Q: Write a query to retrieve all jobs are there in
company?
Ans: SELECT JOB FROM EMP;
SELECT DISTINCT JOB FROM EMP;
 'DISTINCT':DISTINCT is a keyword we can use within
select clause to retrieve each value only once.
 ARTHEMETIC OPERATIONS : +, -, /, *
Arthemetic operator used in SELECT clause but not in from
clause.
Q: Write a query to retrieve ename and salary while retrieve
increment salary by 100?
Ans: SELECT ENAME, SAL+100 FROM EMP;
Q: Write a query to retrieve all the ename and salary while
retrieving detect salary by 300?
Ans: SELECT ENAME, SAL -300 FROM EMP;
Q: Write a query to retrieve ename monthly salary and
annual salary for all the employee?
Ans: SELECT ENAME, SAL * 12 AS ANNUAL_SALARY FROM
EMP;
Q: Write a query to retrieve montly salary and annual salary
with half year bonus of 600 rupees?
Ans: SELECT SAL, (SAL * 12) + (600*2) as Monthly_Salary
FROM EMP;

 ORDER BY CLAUSE: It is used to order the output I


ascending order, if we want to make it in descending
order we will use 'DESC'.
e.g: SELECT * FROM EMP ORDER BY SAL;
Q: Write a query to retrieve all the employee while
retrieving order according to descending order?
Ans: select * from emp order by sal desc;
Q: Write a query to retrieve ename and salary and order by
with respect to salary and while retrieving ename as name
and salary as income?
Ans: SELECT ENAME AS NAME, SAL AS INCOME FROM EMP
ORDER BY SAL;

 we can use Alias names in order by clause.


 We can use more than one column name in order by
clause in that case first order according to first column
name within that order according to second column
name.
e.g: SELECT * FROM EMP ORDER BY DEPTNO, SAL;
Q: To retrieve all the employee while retrieving order
according to dept number in descending order as well as
salary in ascending order?
Ans: SELECT * FROM EMP ORDER BY DEPTNO DESC, SAL;
Q: To retrieve all the employees while retrieving order
according to dept number in descending order as well as
salary in descending order?
Ans: SELECT * FROM EMP ORDER BY DEPTNO DESC, SAL
DESC;

 SELECTION: It means selecting row wise, by using


WHERE clause or WHERE condition we can achieve
selection.
e.g: SELECT * FROM EMP WHERE DEPTNO= 10;
WHERE condition will execute for each and every row, if
the condition satisfy select the row or else reject the row.
Q: To retrieve all the detail of employee ADAMS?
Ans: Select * from emp where ename= 'ADAMS';
Q: Write a query to retrieve ename, job and salary for all the
clerk?
Ans: Select ename, job, salary from emp where job= 'CLERK';
Q: Write a query to retrieve all the employee who joined on
19-APR-87?
Ans: Select * from emp where HIREDATE= '19-APR-87';

31/1/2o18
Relational Operators:
 >
 <
 >=
 <=
 =
 !=
All the relational operators can be used in where condition but
not select clause.
Q: To retrieve all the employee whose salary is less than 2000?
Ans: SELECT * FROM EMP WHERE SAL< 2000;
Q: To retrieve employee name and salary for all the employee
who earns atleast 1600?
Ans: SELECT ENAME, SAL FROM EMP WHERE SAL >= 1600;
Q: To retrieve all the employee who doesn't belongs to dept.
20;
Ans: SELECT * FROM EMP WHERE DEPTNO!= 20;

LOGICAL OPERATORS:
1. AND
2. OR
3. NOT
Logical operators can be used in where condition but we can
not used within select clause.
Q: To retrieve all employee whose job is manager and works for
department 20?
Ans: SELECT * FROM EMP WHERE JOB= 'MANAGER' AND DEPT=
20;
Q: To retrieve all the analysts who earns more than 1600?
Ans: SELECT * FROM EMP WHERE JOB= 'ANALYSTS' AND SAL >
1600;
Q: To retrieve all the employee who belongs to dept. 20 or 30
respectively?
And: SELECT * FORM EMP WHERE DEPTNO = 20 OR 3O;
Q: To retrieve all the employee who joined in year 81?
Ans: SELECT * FROM EMP WHERE HIREDATE > = '01-JAN-81'
AND HIREDATE <= '31-DEC-81';
Q: To retrieve all the employee whose employee numbers are
7900, 7902, 7788 and 7698?
Ans: SELECT * FROM EMP WHERE EMPNO= 7900 OR EMPNO=
7902 OR EMPNO= 7788 OR EMPNO= 7698;

SPECIAL OPERATORS:
 IN OR OPERATOR: Whenever we having one or more
operation we can go for in operator to simplify the query.
eg: SELECT * FROM EMP WHERE EMPNO IN(7900, 7902,
7788, 7698);
Q: To retrieve all the employee whose job is clerk and
analyst?
Ans: SELECT * FROM EMP WHERE JOB IN(CLERK,
ANALYST);
Q: To retrieve all the employee whose salary is in a range
of 1000 - 2500?
Ans: SELECT * FROM EMP WHERE SAL >= 1000 AND SAL <=
2500;
 BETWEEN AND OPERATOR: Whenever we are getting
range of values we can go for AND operator.
eg: SELECT * FROM EMP WHERE SAL >= 1000 AND
SAL <= 2500;

Between and operator is inclusive operator.


Q: To retrieve all the employee whose name start with 's';
Ans: SELECT * FORM EMP WHERE ENAME LIKE 'S%'

 LIKE OPERATOR: LIKE operator is also know as patern


matching operator or wild card operator.
We go for like operator whenever we know some part of values
'_' -> one character
'%' -> 0-n characters
Q: To retrieve all the names whose name ends with 'n'?
Ans: SELECT * FROM EMP WHERE ENAME LIKE '%N';
Q: To retrieve all the employee name whose name second
character is 'A'?
Ans: SELECT * FROM EMP WHERE ENAME LIKE '_A%';
Q: Write a query to retrieve all the name whose name is having
consecutive "LL"?
Ans: SELECT ENAME FROM EMP WHERE ENAME LIKE '%LL%';
Q: Write a query to retrieve all the employee name and job
whose job contains MAN in it?
Ans: SELECT ENAME, JOB FROM EMP WHERE JOB LIKE
'%MAN%';
Q: Write a query to retrieve all the employee name where
name is last but one character 'I' berfore?
Ans: SELECT ENAME FROM EMP WHERE ENAME LIKE '%I_';
Q: Write a query to retrieve all the employee name whose
name 3rd character is A?
Ans: SELECT ENAME FROM EMP WHERE ENAME LIKE '__A%';
 IS NULL OPERATOR: Whenever we are dealing with values
we have to go for IS NULL OPERATOR because we have
some conditions with respect to null values.
1. NULL!= NULL
2.NULL!= ZERO
3. NULL!= SPACE
NULL is unpredictable value.
eg: SELECT * FROM EMP WHERE COMM IS NULL;
 NOT OPERATOR:
It is use in :
in, between and , like, is null, not in, not between and, not
like, is not null.
NOT OPERATOR can not be used directly we have to use
NOT OPERATOR with special operator.
Q: To retrieve all the employee whose job is not manager
and analyst?
Ans: SELECT * FROM EMP WHERE JOB NOT IN
('MANAGER', 'ANALYST');
Q: To retrieve all the employee whose salary in a range of
2500 to 3500?
Ans: SELECT * FROM EMP WHERE SAL NOT BETWEEN 2500
AND 3500;
Q: To retrieve all the employee name whose name does
not start does not start with M?
Ans: SELECT * FROM EMP WHERE ENAME NOT LIKE 'M%';
Q: To retrieve all the employee who are getting some
commission?
Ans: SELECT * FROM EMP WHERE COMM IS NOT NULL;
Q: Write a query to retrieve all the employee whose job is
analyst and name does not start with S?
Ans: SELECT * FROM EMP WHERE JOB = 'ANALYST' AND
ENAME NOT LIKE 'S%';
Q: Write a query to retrieve all the employee who are
getting some commission with their designation neither
manager nor analyst?
Ans: SELECT * FROM EMP WHERE COMM IS NOT NULL
AND JOB NOT IN ('MANAGER', 'ANALYST');
Q: Write a query to retrieve all the employee whose total
salary is greater than 2000?
Ans: SELECT * FROM EMP WHERE (SAL+COMM)>2000 OR
SAL>2000;
Q: Write a query to retrieve all employee whose job is
manager and name does not start with A and S?
Ans: SELECT * FROM EMP WHERE JOB= 'MANAGER' AND
(ENAME NOT LIKE 'B%' AND ENAME NOT LIKE 'C%');
Q: Write a query to retrieve all the employee whose
annual salary is ending with zero?
Ans: SELECT * FROM EMP WHERE (SAL*12) LIKE '%0';
Q: Write a query to retrieve odd salary?
Ans: SELECT * FROM EMP WHERE (SAL/2) LIKE '%.%';
Q: Write a query to retrieve all the employees who are
salesman having E as last but one character in their names
but with salary having exactly four character in it?
Ans: SELECT * FROM EMP WHERE JOB= 'SALESMAN' AND
ENAME LIKE '%E_' AND SAL LIKE ('____');
Q: Write a query to retrieve all the employee who joined
in February?
Ans: SELECT * FROM EMP WHERE HIREDATE LIKE '%FEB%';
Function : Function are predefine function.
we have two types of functions namely:
1.Single row function
2.Multi row function
Single row function: It execute for each and every row of
given table and produces corresponding output for each
and every row.
The inputs is equal to number of output.
Multi row function: It takes multiple function but produces
only output.
Single row Function:
 Lower(lit/column)
 upper(lit/column)
 initcap(lit/column)
SELECT LOWER('GOOD'), UPPER('good'), INITCAP('GOOD
evening ') form dual.
SELECT LOWER(ENAME), UPPER(ENAME),
INITCAP(ENAME) FROM EMP;
initcap convert each first character in uppercase.

 length(lit/column):
eg: select length(ename) from emp;
select ename, length(ename) from emp;
Q: Write a query to retrieve all the employee name whose
name have exactly four characters in it don't use like
operator?
Ans: select ename from emp where length(ename)=4;

 Concate(arg1, arg2): where arg1 and arg2 are


literals/ column
eg: select concat(5, 8) from dual;
select concat(ename, sal) from emp;
Note: For concat function if we have to use more than
two arguments we have to go for nested functions.
Nested Function: It means using one function within
another function. In that case first inner function is
executed then outer function will be executed.
eg: select concat(ename, concat('earns', sal))from emp;
Q: Write a query to retrieve as below using functions?
SMITH WORKS AS CLERK
Ans: select concat(ename, concat(' WORKS AS ', job)) from
emp;
Q: Write a query to retrieve as below using functions?
Smith works as clerk and earns 800 Rs Salary.
Ans: select concat(initcap(ename), concat(' work as ',
concat(lower(job), concat(' and earns ' , concat(sal, ' Rs
salary.'))))) from emp;

 Replace(arg1, arg2, arg3)


arg1 literal/column.
arg2 old char/string to be replaced.
arg3 new char/string.
eg: select replace('java', 'j', 'm') from dual;
select replace('java', 'a', 'c') from dual;
select replace('c developer', 'c', 'java') from dual;
select replace('java', 'a') from dual;
Note: In replace() function if the argument is missed out
then old character is completely remove from a string.
eg: select replace('java', 'c', 'k') from dual;
Q: Write a query to retrieve employee name and job while
retrieving replace all the salesman to saleswomen?
Ans: select ename, replace(job, 'salesman', 'saleswoman')
from emp;
Q: Write a query all the employee names while retrieving
replace 's' to '#' symbol?
Ans: select ename replace(ename, 'S', '#') from emp;
Q: write a query all the employee name while retriving
replace s to # symbol and a to @ symbol?
Ans: select ename, replace(replace(ename, 'S', '#'), 'A',
'@');
Q: Write a query to retrieve employee name, department
number while retrieving replace department number 20 to
30 as well 30 to 20?
Ans: select ename, deptno,
replace(replace(replace(deptno, 20, '*'), 30, 20), '*', 30)
from emp;

 SubStr(arg1, arg2, arg3)


arg1->literal/column
arg2->start position
arg3->Number of char to fetch from start position
eg: select substr('developer', 1, 5) from dual;
select substr('developer', 3, 5) from dual;
select substr('developer', 3, 1) from dual;
select substr('developer', 5) from dual; loper
Note: In substr() function if the third argument is missed
out then fetch till the end.
eg: select substr('developer', -4, 2) from emp;
Note: Second argument might be positive value or
negative value but third argument should be positive
always( because number of character).
Q:Write a query to retrieve first and last character of all
the employee names?
Ans: select substr(ename, 1,1), substr(ename, -1, 1),
ename from emp;
Q: Write a query to retrieve all the employee names
whose name ends with S note don't like operator?
Ans: select ename from emp where substr(ename, -1, 1) =
'S';

 instr(arg1, arg2, arg3, arg4)


arg1literal/column
arg2char/string to search
arg3start position
arg4 which occurrence
eg:
SELECT INSTR('DEVELOPER', 'E', 1, 1) FROM DUAL;
SELECT INSTR('DEVELOPER', 'E', 4, 8) FROM DUAL;
SELECT INSTR('DEVELOPER', 'S', 1, 1) FROM DUAL;
SELECT INSTR('DEVELOPER', 'E', 1, 3) FROM DUAL;
eg: SELECT INSTR('DEVELOPER', 'S', 1, 1) FROM DUAL;
Note: instr() function the searching character or
searching occurance is not found then the output will be
zero.
eg: select instr('developer', 'e') from dual;
Note: In instr() function if third and fourth arg is missed
out by default it will consider it as 1,1;
eg: select instr('developer', 'e', -4, -1) from dual;
Note: If start position is negative value in case of
substring function evaluation happen from left to right
but in case of instr() evaluation happen form right to
left.

SOLVE USING FUNCITONS:


Q: To retrieve all the employee whose job contains MAN
in it?
Ans: select * from emp where substr(job, -3, 3)= 'MAN'
or substr(job, 1, 3)= 'MAN';
OR
select * from emp where instr(job, 'MAN', 1,1)> 0;
Q: Write a query to retrieve all the employee names
while retrieve first there should be in lower case
remaining character in uppercase?
Ans: select concat(lower(substr(ename, 1, 3),
upper(substr(ename, 4))) from emp;
Q: Write a query to retrieve all the employee names
who joined in february month?
Ans: select * from emp where substr(hiredate, 4,
3)='FEB';
Q: Write a query to retrieve number of 'L' in each name?
Ans: select ename length(ename)-
length(replace(ename,'L')) from emp;
Q: Write a query to retrieve all the employee names
whose contains exactly two 'L' in it?
Ans: select ename from emp where length(ename)-
length(replace(ename, 'L'))=2;
Q: Write a query to retrieve all the employee name
while retrieving first and last character of the name
should be in uppercase, remaining should be in lower
case?
Ans: select concat(initcap(substr(ename, 1,
length(ename)-1)), substr(upper(ename), -1, 1)) from
emp;

 reverse: select reverse(ename) from emp;


Q: Write a query to find the word is palindrom or not?
Ans: select * from emp where ename= reverse(ename);

 round function: round function is to round of the


decimal value if the value is from .1 to .4 it will
consider it as previous number. If the value is from .5
to .9 it will consider as next number.
eg: select round(4.2), round(4.5), round(4.9) from dual;

 trunc: trunc function is to elimate the decimal value.


eg: select trunc(4.2), trunc(4.5), trunc(4.9) from dual;
 nvl function: nvl function is used to replace null
value with actual values.
eg: select comm, nvl(comm, 800) from emp;
In nvl function if the argument one is null then provide
argument wo.
In nvl function if the argument one is not null then
provide same value.

 nvl2(arg1, arg2, arg3): nvl2 function is used to


replace null value as well as actual values.
If argument one is not null then provide argument two.
if argument one is null then provide argument three.
eg: select comm, nvl2(comm, 800, 1000) from emp;
eg: select comm, nvl(comm, 'some comm') from emp;
eg: select comm, nvl2(comm, 'some comm', 'no comm')
from emp;
 mod function: mod function always gives us
remainder.
eg: select mod(12, 2) from dual;
for even salary
eg: select * from emp where mod(sal, 2)= 0;
for odd salary
eg: select * from emp where mod(sal, 2)!= 0;
 date function:
sysdate function: It provides a system date.
eg: select sysdate from dual;
Arithmetic operator with sysdate function.
next five days date
eg: select sysdate+5 from dual;
eg: select sysdate+50 from dual;
eg: select sysdate-5 from dual
multiplication and division is not possible
eg: select sysdate*5 from dual;  error
eg: select sysdate/5 from dual;  error
Q: Write a query to retrieve employee name and
experienced of a employee1?
Ans: experienced in days:
select ename, (sysdate-hiredate) from emp;
experienced in years:
select ename, round((sysdate-hiredate)/365) from
emp;
Q: Write a query to retrieve all the employees who are
having more than 36 years of experienced?
Ans: select * from emp where round((sysdate-
hiredate)/365)> 36;

 systimeStamp: It gives system date, time details.


eg: select systimestamp from dual;
 to_char: By usign to_char function we can change
any dates in required format.
eg: select to_char(sysdate, 'dd-mm-yyy') from dual;
13-02-018
select to_char(sysdate, 'day month year') from
dual; tuesday february twenty eighteen
select to_char(sysdate, 'ddth-mm-yyy') from
dual; 13th-02-018
select to_char(sysdate, 'dd-mm') from dual;
13-02
Q: Write a query to retrieve all the employees who
joined in april?
Ans: select * from emp where to_char(hiredate,
'mon')='apr';
Q: Write a query to retrieve all the employees who joined
between 1982 to 1988?
Ans: select * from emp where to_char(hiredate, 'yyyy')
between 1982 and 1988;
Q: Write a query to retrieve all the employees who joined
between feb-1981 to sep-1981?
Ans: select * from emp where to_char(hiredate, 'yyyy-
mon') between '1981-feb' and '1981-sep';
 months_between function: It will give months
between the two dates.

e.g: select months_between('30-mar-2017', '08-jan-2015')


from dual;
Q: Write a query to display employee name and experience
of all the employee in months?
Ans: select ename, months_between(sysdate, hiredate) from
emp;
Q: Write a query to retrieve all the employees who are
having experience more than 420 months?
Ans: select * from emp where months_between(sysdate,
hiredate)>420;

 add_months(date, number): select


add_months(sysdate, 5) from dual;
 last_day(date): select last_day('05-apr-2012') from dual;
Q: Write a query to retrieve all the employees who joined on
the last day of the months?
Ans: select * from emp where hiredate= last_day(hiredate);

 next_day(date, day): select next_day(sysdate,


'friday') from dual;
 rowid and rownum function: rowid is a 18 digits
sequence address and rownum is sequence number for
all the rows.
eg: select rowid, rownum from emp;
Q: Retrieve first 5 records from a table?
Ans: select * from emp where rownum<= 5;
Q: Retrieve first record from table?
Ans: select * from emp where rownum= 1;

 MULTI ROW FUNCTION:


Multi row function takes multi input and produces
single output.
Multi row function takes multi group as input and
provides for output for each group.

Multi row function is also known as aggregate


function.
1. COUNT FUNCTION:
eg: SELECT COUNT(EMPNO) FROM EMP;
SELECT COUNT(HIREDATE) FROM EMP;
SELECT COUNT(JOB) FROM EMP;
SELECT COUNT(ENAME) FROM EMP;
SELECT COUNT(COMM) FROM EMP;

Note: multi row functions consider duplicate value but


null values are not considered.
count function works for number, string, as well as
date kind of data.
2. MAX(COLUMN) AND MIN(COLUMN):
eg: SELECT MAX(SAL), MIN(SAL) FROM EMP;
SELECT MAX(ENAME), MIN(ENAME) FROM EMP;
SELECT MAX(HIREDATE), MIN(HIREDATE) FROM EMP;
max() and min() function works for number, string as well as
date kind of data.

3. SUM(COLUMN) AND AVG(COLUMN):


eg: select sum(sal), avg(sal) from emp;
select sum(ename), avg(ename) from emp; invalid
number
select sum(hiredate), avg(hiredate) from emp;-->
inconsistent datatypes: expected NUMBER got DATE
sum() and avg() function only works for number type of data.
Note: '*' is a special operator and we can use only with
count() function.
eg: select count(*) from emp;
Q: Write a query to retrieve number of analyst in company?
Ans: select count(*) form emp where job='ANALYST';
Q: Write a query to retrieve maximum salary with respect to
manager?
Ans: Select max(sal) from emp where job='MANAGER';
Q: Write a query to retrieve number of salesman in dept 30?
Ans: select count(*) form emp where job='salesman' and
deptno=30;
Q: Write a query to retrieve lowest salary among salesman?
Ans: select min(sal), from emp where job='SALESMAN';
eg: SELECT MIN(SAL), ENAME FROM EMP WHERE
JOB='SALESMAN'; not a single-group group function
Note: We can not use combination of multi row function and
column name in select clause because number of outputs
from multi row functions and column name does not match.
Q: Write a query to retrieve average salary of clerk?
Ans: select avg(sal) from emp where job='CLERK';
Q: Write a query to find average salary of department 20?
Ans: select avg(sal) from emp where deptno=20;
GROUP BY CLAUSE: By using group by clause we can divide
table into multiple groups.
Q: Write a query to retrieve average salary of each
department?
Ans: select avg(sal) from emp group by deptno;
select avg(sal), deptno from emp group by deptno;
Note: We can use a combination of multi row function and
column name in select clause if and only if the column name
is member of group by clause.
Q: Write a query to count number of employees in each
department?
Ans: select count(*), deptno from emp group by deptno;
Q: Write a query to find average salary in each job?
Ans: select avg(sal), job from emp group by job;
Q: To retrieve least salary in each job except department 20?
Ans: select min(sal), job from emp where deptno!= 10 group
by job;
Q: Write a query to count each job in each department?
Ans: select count(job), job, deptno from emp group by
deptno, job;
Q: Write a query to count number of employees in each
department and select only those departments which
number count is more than 3?
Ans: select count(*), deptno from emp where count(*)> 3
group by deptno; group function is not allowed here
Note: Multi row functions can not be used in where
condition.

HAVING CLAUSE: Having clause used to tell which group to


select which group not to select.
We use having clause whenever we have group by clause.
eg: select count(*), deptno from emp group by deptno
having count(*)> 3;
Q: Write a query to find maximum salary among each job
except analyst?
Ans: select max(sal), job from emp where job!= 'ANALYST'
group by job;
OR
select max(sal), job from emp group by job having
job!='ANALYST';
Q: Write a query to find average salary in each job expect
President and average should be more than 1500?
Ans: select avg(sal), job from emp where job!= 'PRESIDENT'
group by job having avg(sal)> 1500 order by job;

CLAUSE ORDER OF EXECUTION

SELECT 5

FROM 1

WHERE 2

GROUP BY 3
HAVING 4
ORDER BY 6

Q: Write a query retrieve all the employee who belongs to


dept no 30?
Ans: SELECT * FROM EMP WHERE DEPT= 30;
Q: Write a query to retrieve all the employees who belongs
to the same dept as ADAMS?
Ans: SELECT * FROM EMP WHERE DEPTNO= (SELECT DEPTNO
FROM EMP WHERE ENAME= 'ADAMS');

SUB QUERY:
 We go for sub query whenever we want to retrieve
some information based on other unknown information.
 sub query in the sense one query within another query
in that case inner query executed first and outer query
executed based on the output of inner query.
Q: Write a query to retrieve all employee who's job is
same as 'FORD' job?
Ans: SELECT * FROM EMP WHERE JOB= (SELECT JOB FROM
EMP WHERE ENAME= 'FORD');
Q: Write a query to retrieve all the employee who's salary
is more than SMITH salary?
Ans: SELECT * FROM EMP WHERE SALARY > (SELECT SAL
FROM EMP WHERE ENAME= 'SMITH');
Q: Write to retrieve all the employee who's salary is more
than miller salary and whose job is same as 'ALLEN' job?
Ans: SELECT * FROM EMP WHERE SALARY > (SALARY SAL
FROM EMP WHERE ENAME = 'MILLER') AND JOB= (SELECT
JOB FROM EMP WHERE ENAME = 'ALLEN');
Q: Write a query to retrieve employee name and salary
whose salary is more than average salary of dept 10?
Ans: SELECT ENAME, SAL WHERE SAL > (SELECT AVG(SAL)
FROM EMP WHERE DEPTNO= 10);
Q: Write a query to retrieve all the employee names who
belongs to new york?
Ans: SELECT ENAME FROM EMP WEHRE DEPTNO= (SELECT
DEPTNO FROM DEPT WHERE LOC= 'NEW YORK');
Q: Write to retrieve department information of scott?
Ans: SELECT * FROM DEPT WHERE DEPTNO= (SELECT
DEPTNO FROM EMP WHERE ENAME= 'SCOTT');

Q: Write a query to retrieve all the employees whose is more


than average salary of all the departments?
Ans: select * from emp where sal> ALL(select avg(sal) from
emp group by deptno);
Note: Whenever inner query returns more than one output
those are known as multi row sub query, in that case we
have to use multi row operators "all, any, in" based on
requirement.
Note: Whenever inner query returns only one output whose
are known as single row sub query, in that case we have to
use single row operators such as:
Single row: =, !=, >, >=, <, <=
Multi row: ALL, ANY, IN
When we use all, any then it will do operation on >, >=, <, <=
and in we use = and !=
Q: Write a query to retrieve all the employees whose salary is
more than any one SALESMAN salary?
Ans: SELECT * FROM EMP WHERE SAL> ANY(SELECT SAL
FROM EMP WHERE JOB= 'SALESMAN');
Q: Write a query to retrieve department information of clerk
and salesman?
Ans: SELECT * FROM DEPT WHERE DEPTNO IN(SELECT
DEPTNO FROM EMP WHERE JOB IN('CLERK', 'SALESMAN'));
Q: Write a query to retrieve all the employee names who
works for research and sells department?
Ans: select ename from emp where deptno IN(select deptno
from dept where DNAME in('RESEARCH', 'SALES'));

 JOINS(oracle joins):
We go for joins whenever we want to retrieve information
form one or more table.

SELECT * FROM EMP e, DEPT d WHERE e.DEPTNO=


d.DEPTNO;

TYPES OF JOINS:
 INNER JOINS
1.EQUI JOIN
2,NON-EQUI JOIN
3. SELF JOIN
 CARTITION JOIN
 OUTER JOINS
1. LEFT OUTER JOIN
2.RIGHT OUTER JOIN
3.FULL OUTER JOIN
 INNER JOIN: Only the rows will displayed in output
which ever satisfies the join condition. Those are known
as Innner join rows.
1. Equi join: Whenever we are joing two tables using
equal symbol are known as equi joins.

Q: Write a query to retrieve employee name and


department name of all the employees?
Ans: SELECT ENAME, DNAME, FROM EMP E, DEPT D WHERE
E.DEPTNO= D.DEPTNO;
Q: Write a query to retrieve employee and department
information of 'SMITH'?
Ans: SELECT ENAME, DNAME FROM EMP E, DEPT D WHERE
E.DEPTNO= D.DEPTNO;
Q: Write a query to retrieve only department information of
all the salesman?
Ans: SELECT D.DEPTNO, DNAME LOC FROM EMP E, DEPT D
WHERE E.DEPTNO= D.DEPTNO AND JOB= 'SALESMAN';
or
select * from emp e, dept d where e.deptno= d.deptno and
job= 'SALESMAN';
or
select d.* from emp e, dept d where e.deptno= d.deptno and
job= 'SALESMAN';
Q: To retrieve ename, dname, salary for all the employees
whose salary is more than 2000?
Ans: select ename, dname, salary from emp e, dept d where
e.deptno= d.deptno and sal>2000;

2. NON-EQUI JOIN: Non-equi join means joining one or


more table without using equal sign.
eg: select ename, sal, grade from emp, salgrade where sal
between losal and hisal;

3. SELF-JOIN: Self-join means joing same table with another


copy of same table.
eg: select e.ename, m.ename mname from emp e, emp m
where e.mgr= m.mgr;
Q: Write a query to retrieve employee name, manager name
and employee department number?
Ans: select e.ename, m.ename mname, e.deptno from emp
e, emp m where e.mgr= m.empno;
Q: To retrieve ename, mgr name and employee department
name?
Ans: select e.ename, m.ename, d.dname from emp e, emp
m, dept d where e.mgr= m.empno and e.deptno= m.empno
and e.deptno= d.deptno;
Note: When we are retrieving 'n' tables while joining we
should have(n-1) joining condition is compulsory.
Q: Write a query to retrieve ename, manager name,
employee department name as well as manager department
name?
Ans: select e.ename, m.ename, d1.dname, d2.dname from
emp e, emp m, dept d1, dept d2 where e.mgr=m.empno and
e.deptno= d1.deptno and m.deptno= d2.deptno;

CARTITION JOIN:
Cartition join means each and every row of one table will be
join with each and every row of another table
We can achieve cartition join wherever the joining condition
is missed out.
eg: select * from emp,dept;

OUTER JOIN:
Outer join means will be retrieving the rows which are satisfy
the condition as well as whichever doesn't satisfy condition
based on the type of outer join.
Left-Outer Join:
Inner join rows + left out rows from left table
eg: select * from emp e, dept d where e.deptno=
d.deptno(+);
Right-Outer Join:
eg: select * from emp e, dept d where e.deptno(+)=
d.deptno;
Full-Outer Join:
Inner join rows + left out rows from left as well as right table.
eg: select * from emp e, dept d where e.deptno(+)=
d.deptno(+);
Note: We can not achieve full outer join using oracle joins
If we want to achieve we have to go for ANSI Joins
ANSI(American National Standard Institute) Join:
Oracle joins only works in oracle database but ANSI Join
works in all database.
eg: select * from emp e full outer join dept d on e.deptno=
d.deptno;
Q: Write a query to retrieve all the managers and clerks who
works in Account and Marketing department?
Ans: select * from emp e, dept d where e.deptno= d.deptno
and job in('MANAGER', 'CLERK') and dname in('ACCOUNTIN',
'MARKETING');
Q: Write a query to retrieve all the salesman who are not
located as DALLAS?
Ans: select * from emp e, dept d where e.deptno= d.deptno
and job= 'SALESMAN' and loc!= 'DALAS';
Q: Write a query to retrieve department name and location
for all the employees who are working for 'CLARK'?(using
join)
Ans: Select dname, loc from emp e, emp m, dept d where
e.mgr= m.empno and e.deptno= d.deptno and m.ename=
'CLARK';
Q: Write a query to display all the employees who works in
same dept has SCOTT but don't retrieve SCOTT
information?(using join)
Ans: select * from emp e1, emp e2 where e1.deptno=
e2.deptno and e1.ename= 'SCOTT' and e2.ename!= 'SCOTT';
CORELATED SUB-QUERIES:
Q: Write a query to retrieve first highest salary?
Ans: select max(sal) from emp;
Q: Write a query to find second highest salary?
Ans: select max(sal) from emp where sal<(select max(sal)
from emp);
Q: Write a query to retrieve third highest salary?
Ans: select * from emp x where 3= (select count(distinct sal)
from emp y where y.sal>= x.sal);
Q: Write a query to retrieve eighth highest salary?
Ans: select * from emp x where 8= (select count(distinct sal)
from emp y where y.sal>= x.sal);
Q: Write a query to retrieve nth highest salary?
Ans: select * from emp x where &n= (select count(distinct
sal) from emp y where y.sal>=x.sal);
Q: Write a query to retrieve third least salary?
Ans: select * from emp x where 3= (select count(distinct sal)
from emp y where y.sal<=x.sal);
Q: Write a query to retrieve second and sixth highest salary?
Ans: select * from emp x where 2= (select count(distinct sal)
from emp y where y.sal<= x.sal) or 6=( select count(distinct
sal) from emp y where y.sal>= x.sal);
Q: Write a query to retrieve first three highest salaries?
Ans: select * from emp x where 3>= (select count(distinct sal)
from emp y where y.sal >= x.sal) order by sal;
Q: Write a query to retrieve five least salaries?
Ans: select * from emp x where 5>= (select count(distinct sal)
from emp y where y.sal<= x.sal) order by sal;
Q: Write a query to retrieve fifth employee who joined the
company?
Ans: select * from emp x where 5= (select count(distinct sal)
from emp y where y.hiredate<= x.hiredate);
Q: Write a query to retrieve all the employee whose salary is
more than average salary of the own department?
Ans: select * from emp x where sal> (select avg(sal) from
emp y wehre y.deptno= x.deptno);
Q: Write a query to retrieve all the employee whose salary is
more than average of salary of their job?
Ans: select * from emp x where sal> (select avg(sal) from
emp y where y.job= x.job);
Q: Write a query to retrieve all the employee whose salary is
greater than the salary of the manager?
Ans: select * from emp x where sal> (select avg(sal) from
emp y where x.mgr= y.empno);

CONSTRAINTS:
Whenever data is being inserted in a table that time if we
want to restrict the data we should create column with
costraints.
1.) NOT NULL:
If we declare any column as not null in that column null
values are not allowed but duplicate values are allowed.
2.) UNIQUE:
If we declare any column as unique in that column null
values are allowed but duplicate values are not allowed.
eg: phone number.
3.) PRIMARY KEY:
It is a combination of both unique as well as not null
constraints i.e. in that column we can not have null values
as well as duplicate values.
4.) CANDIDATE KEY:
Columns that are eligible to become primary key are know
as candidate key.
ALTERNATE KEY:
Columns that are eligible to become primary key but not
selected as primary key.
eg:

5.) FOREIGN KEY:


For joining two tables we need a help of foreign key.
Using this key we can form relationship between two
tables, and we can provide a referential integrity between
tables.
Foreign key applied on a column that current table
become child table and referring table become parent
table or master table.
We can have one or more foreign key in a table.
Note: Any data i.e. inserted in child key column that should
be present in parent key column. i.e. before inserting any
data in child key first we should check data is available in
parent key.
6.) CHECK: It is used to provide extra restriction on a column.
eg: Age column.
7.) COMPOSITE PRIMARY KEY:
Primary key combines of more than one column is
known as composite primary key.

DATA TYPE:
1. number: number(8, 2)
here 8 -> is total and 2 ->is decimal value
2.String: char(4) suppose we take SQL to store in that case
one block of memory wasted fixed.
varchar()
varchar2(4)no waste of memory
3.Date: date

DDL(DATA DEFINATION LANGUAGE):


Syntax: create table table_name(colname datatype(size)
constraints, col2…., col3,,,);
Course table:
create table course(cid number(2) primary key, cname
varchar2(20) not null);
Student table:
create table student(sid number(4) primary key, sname
varchar2(20) not null, smarks number(2, 4), age number(2)
check(age>=16), cid number(2) references course(cid));
TO COPY ONE TO ANOTHER NEW TABLE:
create table emp2 as select * from emp;full table including
data
TO CREATE ONLY STRUCTURE:
create table emp3 as select * from emp where 1=2;
desc emp3;
ALTER COMMAND:
#)By using alter command we can add a new column.
syntax:
alter table table_name add colname datatype(size)
constraints;
e.g:
alter table emp3 add remarks varchar2(40);
#)By using alter command we can modify column name new
datatype(size)
eg:
alter table emp3 modify remarks number(1);
#)By using alter command we can rename column name.
alter table table_name rename column old_colname to
new_colname;
eg:
alter table emp3 rename column remarks to rating;
#)By using alter command we can drop a column;
alter table table_name drop column col_name
eg:
alter table emp3 drop column comm;
RENAME COMMAND:
rename old_tablename to new_tablename;
eg:
rename emp3 to emp4;
TRUNCATE COMMAND:
It removes only the contains of a table but structure remains
same.
eg:
truncate table emp4;
DROP COMMAND:
Drop command removes both structure as well as contain of
a table
eg:
drop table emp2;

Data Manipulation Language(DML):


insert into table_name(col1, col2, ….., coln)
values(val1, val2, ….., valn);
insert into course table:
insert into course(cid, cname values(2, 'development');
insert into course(cid, cname) values(1, 'testing');
insert into student table:
insert into studentst(sid, sname, smarks, age, cid) values(111,
'deepti', null, 24, 1);
insert into studentst(sid, sname, smarks, age, cid) values(112,
'surya', 0, 20, 2);
insert into studentst(sid, sname, smarks, age, cid)
values(&sid, &name,&smarks, &age, &cid);

Udate ccommand:
update table_name set col1= val1, col2= val2 where
condition;
update studentst set smarks= 80, age= 18, where sid= 111;
Delete command:
delect table_name where condition;
e.g: delete emp2 where job= 'CLERK';
Note: All DML commands are temporary once if we close our
SQL editor whatever DML command is executed will be
reverse.
If we want to make it permanent we have to use a commit
statement.

DATA TRANSLATION LANGUAGE(DTL):


commit, rollback and savepoint
commit statement is used to make a permanent changes
done by DML command.
rollback is used to take back us to previous commit
statement.
savepoint is used to create a multiple savepoints.
Note : rollback statement always used after the commit
statement, if commit statement is not present then it can
rollback the data.
Note: savepoint command will not save DML command
permanently only commit statement will permanent save of
DML commands.
 DCL(DATA CONTROL LANGUAGE):
Grant, Revoke
By using grant command we can give a permission to other
users
Revoke command is used to take back those permission
eg: SCOTT grant select on emp to abc;
abc select * from scott.emp;
scott revoke select on emp from abc;
syntax to creating user: create user user_name identified
by password.
eg: create user robin identified by 123;
grant connect to robin;
conn robin/123;
See the image below to understand:
NORMALIZATION:
It is just a guidelines if we follow the guidelines we can
create a efficient database table.
We use normalization to avoid repetitive data and to avoid
insertion, updation and deletion abnomally.
1.) 1st Normal Form(1NF):
Duplicate columns are not allowed.
Create a primary key.
No multi valued attributes.
2.) 2nd Normal Form:
Table should be in 1st normal form.
Split the table and create a foreign key.
3.) 3rd Normal Form:
Table should be in 2nd normal form.
Remove all the columns that are not dependent on
primary key.
4.) BOYCEE CODD NORMAL FORM(BCNF):
All the columns in a table should be a candidate key.
5.) 4th Normal Form:
Table should be 3rd normal form.
No composite primary key.
6.) 5th Normal Form:
Table should be in 4th Normal Form
For joining two tables use candidate key.
Q: Write a query to retrieve unique records?
Ans: Select * from emp A where rowid= (select max(rowid)
from emp B where A.empno= B.empno);
Q: Write query to retrieve duplicate records?
Ans: Select * from emp A where rowid!= (select max(rowid)
from emp B where A.empno= B.empno);
Q: Write a query to delete duplicate records?
Ans: Delete from emp A where record!= (select max(rowid)
from emp B where A.empno= B.empno);
Q: Write a query to retrieve first n record?
Ans: select * from emp where rownum<=&n;
Q: Write a query to retrieve last n records?
Ans: select * from emp MINUS select * from emp where
rownum <= (select count(*)-&n from emp);

VIEWS:
views is just a virtual table.
By using views we can achieve two things
1. We can increase a database performance.
2. We can provide security to our data.

The same process will be happening all the time whenever


we execute query as number of hits to the database
increased, the database performance will be decrease.
To overcome this problem we have to go for views.

Security:
Creating view:
create view view_name
as
select …..
from…..
where…..
order by…..

conn system/tiger;
grant create view to scott;

create view vw_emp


as
select * from emp
order by sal;

select * from vw_emp;


create view vw_salesman
as
select * from emp where job= 'SALESMAN'
order by sal;

select * from vw_salesman;

PL/SQL:
FUNCTION:
Q: Write a PL/SQL command to create a view for tall the
employees and give access to only to the ename, empno, job
and salary?
Ans: create view vw_analyst
as
select ename, empno, job, sal
from emp
where job= 'ANALYST'
order by sal;
syntax:
create or replace function f_name(arguments)
return datatype
as
variable declaration;
begin
executable statement;
end f_name;
/

Q: Query to multiplication of two number?


Ans: create or replace function f_mul(x int, y int)
return int
as
m int ;
begin
m: x*y;
return(m);
end f_mul;
/
(to check error use command: show errors;)
STORE PROCEDURE:
Syntax:
create or replace procedure p_name(argument)
is/as
variable declaration;
begin
executable statement;
end p_name;
/
eg: create or replace procedure p_emp_10
is
ecount int;
begin
select count(*) into ecount
from emp
where deptno= 10;
dbms_output.put_line('No. of emp in dept 10 is: ' ||ecount);
end p_emp_10;
/
set serveroutput on;
exec p_emp_10;

create or replace procedure p_emp_all(dno int)


is
ecount int;
begin
select count(*) into ecount
from emp where deptno= dno;
dbms_output.put_line('No. of emp in dept' || dno || 'is:' ||
ecount);
end p_emp_all;
/
exec p_emp_all(20);

Вам также может понравиться