SQL Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 74

Data:--

--The Raw facts which describes the attribute(properties) of an


enitity(object).
or a transaction is known as Data.
--Data Can be Valid or In-valid based on situation.

ex:--Student(Enitity)
---Usn
---Name >>>Atibutes
---Marks

Information:-
--Collection of data Becomes information.

-------------------------------------------------------------------------
--
note--Now simply storing the data/information is not important,we have to
store the data in an Oragnized
or Sysmetic Manner.So the based on requ.. we can retrieve the data
easily.

Database:--
-A medium to store the data/information in oraganized/systmetic manner
is knwon as Database.
-Functionalities of DB are:--
1.Inserting the data
2.Retrieveing the data
3.Modify the data
4.Delete the data
5.Manage the data ans so on..............
====================================================
DBMS(Data Base Management System)
:---A software(set of program) which is used to manage,maniuplate,create
the database.
-->Ex DBMS are:--
1.Oracle RDBMS
2. Mysql
3.Sql Server
4.Mongo DB
5.Postgre
6.DB2 etc......>
=========================================================================
==================
Query Language:--
--It is used to Comunnicate with the DBMS system software.
or A medium which helps user/programmer to interact with DBMS.

------------------------
A DBMS s/w may have any of the following model for Storing the data:--
1.Hierachial Model
2.Network Model
3.Relational Model **(SQL)
4.Object Model
5.Document Model(Mongo DB)
etc...............
1.Hierachial Model:--
-->This is the first model developed by DBMS developer.
-->It organises the data in hierachial tree structure.
The hierarchail tree starts from root
which has a root data and then it expands in the form of tree.

Avanatge:-
1.It is very simple and fast to traverse through a
tree-like structure.
2.Any change in the parent node is automatically reflected
in the child node,
so the interigity of data is maintained.

Dis-Adavntage:--
1.If a parent node is deleted the child node is automatically...
deleted or relationship will be destroyed.
2.Complex relationship are not supported.
------------------------------------------------------

2.Network Model:--
--This model is an extension of Hierachial Model,
in this model all the nodes are connected to each other.
--This model is the same as Hierachial Model,the only
diff.. is that a record can have more parent.
--It replaces the Hierachial Model i.e tree with graph.

Advantage:--
--The data can be accessed faster than Hierachial Model.
This is beacuse all the nodes are inter-connetected and
There can be more than one path or reach a particluar node.

Disadvantage:--
--As more and more realtionships need to be handled
the system might get complex.So user must have
detailed knowledge of the model to work with.
----------------------------------------
3.Relational Model:--
--This model was given by E.F codd.In this model
data will be stored in the form of row and column(i.e table)
---------------------------------------------------
RDBMS(Relational Data Base Management System):-
--A type of DBMS system software which stores the data
using relational model is known as
RDBMS.

1.Table:--Table is a logical Structure which contains


column,row and cell.

2.Column:--A column represents an attribute of an enitiy.


--Column is also knwon as Field or attributes.

3.Row :--A row represents all the attributes of one enitiy.


--Row is also known as tuple or record.

4.Cell:--cell is a smallest unit of table which represents data.


or cell is a building block of table.
---------------------------------------------------------------
SQL(Structured Query Language)--->>
-->Relational Model was Developed by EF Codd in 1969.
-->IBM developed relational model based DBMS which was
known as SYSTEM-R.
-->Then they developed a language to interact with SYSTEM-R which
is known as SEQUEL.
SEQUEL:--Structure English Query Langauge.
-->SEQUEL was developed in 1970 by IBM researchers and
their name is Raymond Boyce and
Donald Chamerlin.
-->Later SEQUEL was renamed to SQL by
ANSI(American Nantional Institute) in year 1986.
========================================================================
Type Of Statment/Query Language are:--
1.DDL(Data Definition Language)
2.DML(Data Manipulation Language)
3.TCL(Transaction Control Language)
4.DCL(Data Control Language)
5.DQL(Data Query Language)
---------------------------------------
1.DDL(Data Definition Language):--
--This Langauge is used to define the table.The stmt of DDL are:--
1.Create :--This stmt is used to create the table in database.
2.Rename :-This stmt is used to chnage the name of table(Some times it
is used to change column too)
3.Alter :-It is used to modify the def.. of the table in data base.
4.Truncate:It is used to delete all the records and data from the table
but table structure reamins same.
5.Drop :-It is used to delete all the records and data from the table
even table structure will be deleted or destroyed.
2.DML(Data Manipulation Language):-
--It is used to maniplate the table present in database.
--The stmts of DML are:-
1.insert :--it is used to insert the record into the table
2.update :--It is used to modify the data present in the database.
3.delete :--It is used to delete one specific record from table.
3.TCL(Transaction Control Language):--
--It controls the transaction in data-base/in table during DML operation.
--The stmts of TCL are:-
1.Commit :-It is used to save the transaction parma.. into the data
base.
2.Rollback. :- It is used undo all the unsaved tran... in data base.
3.Savepoint :- It is used to mark the position of transaction...
4.DCL(Data Control Language):--
-It protects and provide accessibilty for another user.
--The stmt of DCL are:--
1.Grant :--This stmt is used to provide permis.. to another user so
that they can access their databas/table
2.Revoke:--It is used to take back the given permission

5.DQL(Data Query Language):-


--it is used to access/retrieve the from data base.
--it has only one stmt in it:-- select

-->what is diff..b/w delete,drop and truncate???

-------------------------------------------------------------------------
------------------------------------------------
1.CLEAR SCREEN(cl scr)
--It is used to clearthe screen
2.set linesize value
--set line is used to set the no of caharcter that
can be displayed
in single line.

ex:-- set line 200


3.set pagesize value:--
--set pages is used to set the no of lines to consider a
single a page.
ex:-set page 200

4.connect :--it is used to switch from one user to another user.

ex:--connect username;

5.show user:--it tells which user has been logged in.

6.describe tablename(desc tablename)


--it returns columns
present in the current table and
for each column what data type has used.

7.select * from tab:--


-- it will return all the tables present in database.
-------------------------------------------------------------------------
---
Data Types:--
-In Sql data tpes define what type of value/data a column is going to
store.
-Data types are:-
1.char
2.varchar/varchar2
3.number
4.date
5.LOB

1.char:--
--char DT stores characters,such as A-Z,a-z,0-9,@,#,$,% etc.....
--Char DT will accept an argu.. as size

syntax:- char(size)
size=It speciifies the max number of char.. that can be
stored in a single cell.

Dis-advantage:--
Char data type is a fixed length memory allocation.

char(4) :--SMITH ->>>Compiler


--------------------------------------------
2.varchar:--
--varchar DT stores characters,such as A-Z,a-z,0-9,@,#,$,% etc.....
--varchar DT will accept an argu.. as size.

syntax:- varchar(size)
size=It speciifies the max number of char.. that can be
stored in a single cell.

-Both char and varchar is used to store characters,but in both diff.. is


that varchar is a varaible lenght
memory allocation.Hence there is no memory wastage.

---------------------------------------
3.number data type:-
--Number data type is used to store numeric values(int and double).
--For this data type we can pass upto 2 arg i.e precision and scale.

syntax:--
number(precision,scale)
--Where scale arg is optioanl is optional.

precision:-- It specfies the total number of numeric values that can be


stored in single cell
scale:--It specfies the number of digit can be stored after decimal point
.

Note:--

1.If scale arg.. not present then only int value can be stored.
2.Always precision >= Scale
3.if precision==scale ==> only Decmial

for example:--

1.1536.369 ==>>number(7,3)
2.55555555 ==>>number(8)
3. 0.2589 ==>>number(4,4)
4. number(3,5) ==>> wrong
5. number(2,2) ==>>yes

0.2680000:---number(7,7)
------------------------------------------------------------
Date Data Type:--
--It is used to store date
--Valid date formate(Oracle) to store date data type is
'DD-MM-YY' :---THen it will store date
of Current Century
'DD-MM-YYYY' :--It will store date of Any
century
--For date data type no-need to pass any arg..
--Date data tpe can accpet only the valid date formate otherwise compiler
will through an error.

ex:-- '01-JAN-20' ----Valid


'09-OCT-1996' ---valid
'2010-10-JAN' ---in-Valid in oracle.
----------------------------------------------------------------
LOB(Large Object)--
--This data can store text files ,video files and so on.
--In LOB data type we can store data/values upto 4gb
--LOB data types is broadily classified into 2 types:--
1.CLOB(Character Large Object) :--It stores text
files,pdf etc..
2.BLOB(Binary Large Object) :--It stores
picture,video, audio etc..
---------------------------------------------------------
Null :--
--Null is a keyword in sql which represents an empty
cell(null means nothing it does not mean a blank spcae/Zero)
--When an entity does not have any value,it will be represented by null.
--In RDBMS null does not requires any memory space.
--In RDBMS 2 nulls are not same:-- null1 != null2 (all the nulls are
unique)
-- Any operation perfomed on null results as null value itself.

i.e 5+0 =5
5+null = null
8/null = null
---------------------------
1.DQL(DATA QUERY LANGUAGE):--//10

a.select :--THe retrival of data from database can be


fetched by a statemnt that stmt is the select

-->Data Can be fetched from data base either by


selecting row,or by select row and column and by selecting multiple
tables.

-->Projection:--The retrival of data by selecting


only column name is known as Projection.
-->Selection :--The retrival of data either by
selecting row or column is knwon as Selection
-->joins:--The retrival of data by selecting
multiple simulat.. is known as JOINS.
-

-------------------------------------
Projection:--

syntax:--
select */Column_Name[Distinct]/Expression[Aliasing]
from table_name.

Order of Execution:-
1.From clause :-1st from clause will be executed and it
will check
whether the specified table is present in database or not.
(if spefic.. table is present then it will be selected
under execution)

2.Select clause :-
--After the execution of from clause we
will get some table and from that table
we are going to select the required column.

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

1.WAQ to fetch all the tables present in DB.


-->
2.WAQTD all the details of an employee from employees table.
--->
3.Waqtd employee number ,emp name,date of joining and their dept numbers.
-->
4.write to fetch column name and their data types present in emp table.
-->
5.WAQTD all the unique jobs from emp;

------------------------------------------------------------------------
---------
Distinct :--
--Distinct clause is used to remove duplicate records
present in result table,
which helps user to access only the unique records.

1.WAQTD unique job from employe table.

2.waqtd unique deptno,job from emp table.

note:--in 1 select clause only one distinct keyword can be used.

-------------------------------------------------------------------------
---------
Expression:--
--Anything which gives(Yields) a result is known as Expression.
--An Expression consits of:-
1.Operand:-The resources on which any operation is performed is knwon
as Operand.
--In SQL Operand can be 2 types:--
1.Column_name(sal,enmae..)
2.Direct value/Immediate value.

2.Operators:-It is used to perform an operation.


-----------------------------
-->WAQTD annual sal and comm for all the employees.
select sal*12,comm
from emp;

-->WAQTD sal of all the employees with deduction of 30%.


select sal*(70/100)
from emp;

or
select (sal-(sal*(30/100)))
from emp;
-----------------------------
ALIAS:-
-It is an alternate name given to a column in result table.
-ALIASING can be done in 2 ways:-
1.By using AS keyword:--

syntax:- select old_columnName as New_columnName


from table_Name.

2.Without using as keyword:--

syntax:- select old_columnName New_columnName


from table_Name.

----------------------------------------------
1.WAQTD name nad half term sal for all the employess
-->
select ename,sal*6 "Half Term Sal"
from emp

note:if we have more than one string as Alias name then we need to write
it in " ";

2.WAQTD name,deptno,sal with hike of rs 100 in their orignal sal fro all
the employess.
-->
select ename,deptno, (sal+100) "HIKED SAL"
from emp;

3.WAQTD name and annual sal with bonus of rs 2000


-->
select ename,(sal*12+2000) as salary
from emp;

4.WAQTD name,designation of all the employess along with deduction of 50%


in annual sal.
---
select ename,job,((sal*12)/2) "Annual Sal With Dedu Of 50%"
from emp;

5.WAQTD all the details of employes even retrieve the half term sal.
-->
select emp.* ,sal*6 "HALF TERM SAL"
from emp

=========================================================================
=======
Selection:--
--Retrival of data using both column and row is known as Selection.

syntax:-
select */Column_Name[Distinct]/Expression[Aliasing]
from table_name
where<Filter-Condition>

Where clause:--
--where clause is used to filter the records.
--It will execute row-by-row
--For where clause we can pass filter condition as an argumnet.
--Multiple filter condition can be passed in where clause.

Order of Excecution:--
1.From clause :--Brings the req.. table under execution
2.where clause :-Filters the wanted record to be feteched
3.select clause :-Selects the req..record from result table.

-------------------------------------------------------------------------
-
waqtd details of all the employees who are earning sal greater than 1500
-->
select *
from emp
where sal>1500;
Waqtd name of employees and his job if and only if he is working as
PRESIDENT
-->
select ename,job
from emp
where job='PRESIDENT';
Waqtd name,sal with hike of 10% if their sal is less tahn 2000
-->

WAQTD employee id and name of employees if their are working in deptno 10


-->

Waqtd all the details of employee hired before 1982.


-->select *
from emp
where hiredate<'01-JAN-1982';

waqtd name,job,sal and annual sal if their annual sal exceeds 14000.
-->
select ename,job,sal
from emp
where sal*12 >14000;

Waqtd all the details of employee and annual sal if he works as ANAYLST
select emp.*,sal*12 "ANNUAL SAL"
from emp where job='ANALYST';
-------------------------------------------------------------------------
--------
Order by clause:--
--Order by clause is used to sort/arrange the records either in ascending
or dec..order.
--BY defult order by clause will sort the records in ascending.
syntax:--
select */Column_Name[Distinct]/Expression[Aliasing]
from table_name
where<Filter-Condition>
order by column_name/expression asc/desc.
order of Exceution:--
1.from clause
2.where clause -->row-by-row
3.select clause -->row-by-row
4.order by clause -->row-by-row
------------------------------------------------------------
1.waqtd to sort the record in ascending order based on sal.
-->
select *
from emp
order by sal;
----->>>>>
-------------------------------------------------------------
Can be pass more than one column for order by clause?
--Yes,we can pass multiple columns in order by clause,
but always first priority will be given to first column.

--WAQTD and sort the emp table based on sal,deptno.

select *
from emp
order by sal,deptno;
note:--In this case complier will give priority for the sal column
because it is he first passed in order by clause
then comipler will check even the deptno column if there is any
duplicate sal in sal column then it wil be
sorted based on deptno.
==================================================
Operators:--
--It is used to perform some operations.
--Types of Operator are:--
1.Arithemtic Operator.
2.Concatination Operator.
3.Logical Operator
4.Comparision Operator
5.Relational Operator
6.Special Operator
a.In
b.not In
c.between
d.not between
e.is
f.not is
g.Like
h.not like
7.Sub query Operator.
------------------------------------
2.Concatination Operator:-(Pipe Operator)
--This operator is used to join the given two String.
So it enables us to display output in sentence formate.
--It is represented by a symbol ||
Ex:--

1. HI SMITH
--
select ' HI ' || ename
from emp
where ename='SMITH'

note:whatever string user is going to define in this case it will written


in single quotes.

2. Hi MR ..... Your sal is ....


:-- 4 String
--3 concat.. opera..

select ' Hi MR ' ||ename || ' Your SAL is ' || sal


from emp;

Note:--To join n number of String we need n-1 Concatination Operator.

---------------------------------------------------------------------
WAQTD HI Congrats to respective employee your sal has been hiked by
10%(print hiked sal)
and you are working in respective dept.
-->

select ' HI Congrats ' ||ename|| 'Your SAL has Been hiked by 10% '||
(sal+(sal*(10/100))) || ' and You are working in deptno: '|| deptno
from emp;

select ' HI Congrats ' ||ename|| 'Your SAL has Been hiked by 10% '||
(sal+(sal*(10/100))) ' 10% hiked in sal ' || ' and You are working in
deptno: '|| deptno
from emp;
-------------------------------------------------------------------------
--
Logical Operator:--
and ,or and not

And:--
OR:--
Not:--

WAQTD all the details of an employees whose mgr no is either 7839 ,7566

-->
select *
from emp
where mgr=7839 or mgr=7566;

WAQTD name of all the managers hired after april 81.

-->
select ename
from emp
where job='MANAGER' and hiredate>'30-APR-81';

WAQTD name of the clerk if he works in either in deptno 20,10,30

-->
select ename
from emp
where job='CLERK' and (deptno=10 or deptno=20 or deptno=30);

WAQTD all the details of en employee who are working either as manager,
Clerk and belongs to deptno 10,30
-->
select *
from emp
where (job='CLERK' or job='MANAGER') and (deptno=10 or deptno=30);

Waqtd details of the employess working as anaylst hired after 1985


getting sal greater than 2500 but less than 4000.
-->
select *
from emp
where (job='ANALYST') and (hiredate>'31-DEC-85') and (sal>2501 and
sal<3999);

Wqatd details of employees either getting annual sal between 9600 and
15000.
-->
select *
from emp
where (sal*12 >=9601 and sal*12 <=14999);

-------------------------------------------------------------------------
---------
Special Operator:--
--It is used to perform operations,if we are using special operator then
we can min... the number of operator used.

1.IN:--

--It is a multi-valued operator which can accepts single


value(Column_name/Expresiion) at LHS
and it will be take multiple value at RHS.
--In operator returns true if any of the value presnet in RHS satisfies
the condition otheriwse it will return false.

syntax:--

col_name/expression in (v1,v2,v3.....vn);

--------------------------------
WAQTD details of employees who are working in either deptno 10,20,30.
Waqtd details of employes who are working as Manager,Analyst,Clerk
--> select *
from emp
where job in('MANAGER','ANALYST','CLERK')

-------------------------------------------------------------------------
--
2.Not In:--
--Not in operator is a multivalued operator which can accept single value
at LHS and multi-vlaue at RHS.
--NOt in opertor returns true if the values present at RHS does not
satisfies the condition.
sntax:--
column_name/expression not in(V1,v2,v3.....Vn);
WAQTD the name of employess who are working as ANALYST or Manager and
they do not belongs to 20 or 30 dept.
select ename
from emp
where job in('ANALYST','MANAGER') and not in deptno(20,30);

Waqtd details of employess working in deptno 20 and not working under


7839,7566 manager.
--
select *
from emp
where deptno in(20) and mgr not in(7839,7566);
-----------------------------------------------------------------
3.Between:--
--Between operator is used whenver we have ranges of value(lower range
and higher range)

syntax:---

column_name/expression between lower_range and higher_range;

note:-- Between operator is a combination of >= and <=


..Interchanging of rangeg is not possible.

WATD name and salary of employees who earns more than 2000 but less than
3000

select ename,sal
from emp
where sal>=2001 and sal<=2999;//wrong

select ename,sal
from emp
where sal bewteen 2001 and 2999;

--------------------------------------------------
Note:Between Operator is applicable even for String values also,it will
work based on ASCII value of the String.

=========================================================================
4.Not between:--
--Not between operator is used whenever we have a ranges of values (lower
and higher range)
and this operator will exculde the given lower and higher rangeg.

syntax:--

column_name/expression not between lower_range and higher_range

WAQTD details of employees who are not getting sal in range 1000,3000;

--select *
from emp
where sal not between 1001 and 2999;

=========================================================================
============
5.IS operator:--
--Is operator is used check whether the avlues present in LHS is null or
not.
syntax:--
column_name/expression is null;

WAQTD name of employees who does not getting any commission.

select ename
from emp
where comm is null;

WAQTD details of employees who are not working under any manager.
select *
from emp
where mgr is null;

----------------------------------------------------------------------
6.IS not:--
--IS not operator is used to verfiy the value present at LHS is not null

syntax:--
column_name/expression is not null;

WAQTD all the datails of employees who are getting some comm.

select *
from emp where comm is not null;

WAQTD details of employess are reporting to some manager.

select *
from emp
where mgr is not null;
=========================================================================
==============
Like Operator(Pattern Matching Operator):--
--Like operator is used to perfom pattern matching opeartion.

syntax:--
colmn_name/expression like 'Pattern-To-Match';

--In like operator 2 special char.. will be used to perform pattern


matching
1. _ ::-- It accepts exactly one char at a time.

2. % ::-Percentile will accept any of char,any number of times or even


all the
characters at a time

note:--
1. To check whether the string is ending with specific char

'%Char name';

a.waqtd details of employess whoes name ends with 'S' char.


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

2. To check whether the string is starting with specific char


'char name%';

b.Watd details of employees whoes name Starts with 'A' char.

select *
from emp where ename like 'A%';
3.To check whether the name starts and ends with specific.. char or not

'startingChar%endingChar';

c.waqtd details of employes whoes name starts with S and ends H

select *
from emp
where ename like 'S%H';

d.WAQTD details of employees who has consecutive 'LL' in their


ename.
select *
from emp
where ename like '%LL%';
------------------------------------------------------------
Underscore:--

WAQTD name of employees who has 'A' at their second place of their
ename.

select *
from emp
where ename like '_A%'

WAQTD details of employees who are getting sal exactly in 4 digit.


select *
from emp
where sal like '____';

-------------------------------------------------------------------------
----------
WAQTD name of employees if his name conatins of 'A' char and ends with H
char.

select *
from emp where ename like '%A%H';

WAQTD details of employees who are hired in month of DEC


--
select *
from emp
where ename like '___DEC-__';

select *
from emp
where hiredate like '%DEC%'

waqtd name,sal and deptno if they have hired on 1st day of the month
--
select *
from emp
where hiredate like '01%';

select *
from emp
where hiredate like '01____-__'
---------------------------------------------------------------
What should be done if I want to select a name which itself has an
Underscore
i.e Bahuli_Bali

Escape Character:--
--Escape Character is used to remove the specail behaviour given to
special char and
it will act as an Ordinary character.
syntax:--
column_name/expression like 'Pattern-To-Match' escape 'char';
note:--we can pass any special char.. as Escape char except % .
WAQTD all the details of employee whoes name conatins underscore in it.
select *
from emp
where ename like '%@_% escape '@';
=========================================================================
============================
Not like:-

WAQTD details of employees who do not have underscore in their ename.

select *
from emp
where ename not like '%!_%' escape '!';

WAQTD details of employees whoes name contains _ at 2nd position

select *
from emp
where ename like '@_%' escape '@'
=========================================================================
=======
Function:--
--Functions are the named block of code which is used perform some
certain operation.
or List of instructions which are used to perform a paerticular is
known a Functions.
---Functions consists of 3 major compene....
1.Function name.
2.No of arguments or inputs
3.Return Type.

--There are 2 types of Function in sql We do have:--


1.Single Row Function(SRF)
2.Multiple Row FUnction(MRF)/Group Function/Aggregate Function

1.Single Row Function(SRF):--


--SRF take 1 input,process it and returns 1 output.
--If user will pass n-number of i/p's then user will get n-number of
o/p's
-- Diff.. types of SRF are:--
a.)Number SRF/Math SRF
b.)Character SRF
c.)Date SRF
d.)Conversion SRF
e.)General SRF

2.Multi Row Function(MRF):--


--MRF takes n-number of i/p's it aggrigates then produces a single
o/p's.
--IF user will pass n-number of i/p's then also user will get a single
o/p's
--Diff.. types of MRF:--
a.)max()
b.)min()
c.)sum()
d.)avg()
e.)count()
-------------------------------------------------------------------
a.)Number SRF/Math SRF:--
--It is used to perfom mathmath.. operations like modulus,square etc..
--Diff.. types of Number SRF are:--
1.mod()
2.Power()
3.abs()
4.sqrt()
** 5.Round()
** 6.Trunc()

1.mod():--
--Mod() function is used to obtain the remainder(modulus)
--mod() Function will accept 2 arg.
syntax:--
mod(m,n)

where m=Dividend
n=Divisor

ex:-- 1 select mod(10,5)


MOD(10,5)
---------
0

-- select mod(10,3)
from dual;
MOD(10,3)
----------
1
note:--TO perfom the operations we have a dummy table by name dual;
---------------------------------------
2.Power()
--Power() is used to obtain the exponential value of a given number.
--It will take 2 arg:-
syntax:--
power(x,n)

x:--base
n:--Power/Exponent
ex:--

select power(2,5) from dual;

----------------------------------------------
3.Absolute():--
--This function will obtain the maginitude of the given number.
--It will accept only one arg:--
syntax:--
abs(number)

select abs(-50) from dual;


-->50

select abs(15) from dual;


--->15
----------------------------------------------
4.Sqrt():--
--This function is used to obtain the SQRT of the given number
--It will accept only arg..

syntax:--sqrt(number)

ex:-- select sqrt(10)


from dual;
--->3.16227766

select sqrt(64)
from dual;
--->8
--------------------------------------------
5.Round():--

0-0.4 :--0
0.5-0.9 :--1.0 :--1

--Round() is used to round-off the given number to the nearest value.


--It will accept upto 2 arg:--

syntax:-- round(number,[Scale])

where scale arg.. is optional.But,Scale can be +ve as


well as -ve.
+ve scale:--After decimal and count starts from 0
-ve scale:--Before decimal and Counts starts from 1.

ex:--

1. 1 select round(55.356396,3)

ROUND(55.356396,3)
------------------
55.356
2. 1 select round(55.355883696396,6)

ROUND(55.355883696396,6)
------------------------
55.355884
3.select round(55.3946851465769,6)
from dual

ROUND(55.3946851465769,6)
-------------------------
55.394685
4. select round(55.39,-1)
from dual
ROUND(55.39,-1)
---------------
6
5. 1 select round(12359865.39,-4)

ROUND(12359865.39,-4)
---------------------
12360000
=========================================================================
======
6.Trunc():--
--Trunc () is used to round off the given no..always to lower value.
--This function will accept upto 2 arg:--

0.0-0.4 :--0.0
0.5-0.9 :--0.0
syntax:-- Trunc(number,[Scale])

where scale arg.. is optional.But,Scale can be +ve as


well as -ve.
+ve scale:--After decimal and count starts from 0
-ve scale:--Before decimal and Counts starts from 1.

ex:---
select trunc(523.36956,4)
from dual
----
TRUNC(523.36956,4)
------------------
523.3695

select trunc(523.3695656,5)

TRUNC(523.3695656,5)
--------------------
523.36956
====================================================
@@@ select trunc(523698.056852,5)
from dual;

TRUNC(523698.056852,5)
----------------------
523698.057
=========================================================================
==========================
2.Character SRF:--
--This function is used to perform operation on characters either for
case manipulation or
for char manipulation.
--It is broadily classified into 2 types:--

1.Case Manipulation
--Upper()
--Lower()
--Initcap
2.Character Manipulation
--Length()
--Concat()
--reverse()
***--substr()
***--instr()
***--replace
--trim

Upper():--Converts the Given String to upper case.

syntax:-- upper('String');
ex:--- select upper('jspiders')
from dual;
--JSPIDERS
select upper('JSpIdERS')
from dual;
--JSPIDERS;
Lower():--Converts the Given String to lower case.

syntax:-lower('String')

select lower('JSPIDERS')
from dual;

Initcap():--It converts the first char of each word of the sentence into
upper case.
syntax:- initcap('hi how are you');
-Hi How Are You

============================================
Length():--
--This function is used to return the size(Even Space b/w String will be
counted) of the given
string
syntax:-length('String')

ex:-- length('JAVA') -->4


length('JAVA J2EE') -->9
-->WAQTD name of employees having 4 char.. in their name.(Use function
only)

select ename
from emp
where length(ename)=4;

-->Waqtd details of employees getting sal in 3 didgit.(Use function only)


select *
from emp
where length(sal)=3;
--------------------------------
Reverse():--
-->used to reverse the given String.

syntax:-- reverse('String')

ex:- reverse('QSPIDERS');
--------------------------------
Concat():--
--This function is used to merge the given 2 String.

syntax:-- concat('String1','String2')
ex:--
Display HI SMITH.

-->select concat(' HI ',ename)


from emp
where ename='SMITH';

-->Display hi(str1) ename(str2) ...... your sal has been Hiked by 50%
(str3)and print everyones hiked sal.(Str4)
select concat(concat(concat(' HI ',ename),' Your Sal Has been Hiked
By 50% '),(sal+(50/100*sal)
from emp

-->WAQTD HI Congrats to respective employee your sal has been hiked by


10%(print hiked sal)
and you are working in respective dept(print respective depart).
-----------------------------------
substr():--
--This function is used to obtain substring(part of String) from a given
String.
--This function can accept upto 3 arg:--

syntax:- substr('Original String',Position,[Length]);

Original String:--
-->This is the String from which substring will be extracted.

Position:--
-->It specifies from where to begin the extraction

Length:--
-->This argu..is not mandatory argu..
When length is not mentioned we have to consider the complete
String after the Position.
-->It specifies the number of character to extracted.
note:--
--> position starts from 1 and it can be negative also.
whenevr we are moving from left to Right Position will be +ve
if we are terversing from right to left Position will be -ve
--> Length can not be -ve only +ve.
-------------------------------------------------------------

ex:--
-8-7-6-5-4-3-2-1
-------->+ve
J S P I D E R S
<---------ve
1 2 3 4 5 6 7 8

Extract JSP from JSPIDERS


substr('JSPIDERS',1,3)
Extract DERS from JSPIDERS

-->select substr('JSPIDERS',5)
from dual

-->select substr('JSPIDERS',-4)
from dual;
------------------------------------------------------------
-->WAQTD first 3 char of employees who are working as 'CLERK'
--
select substr(ename,1,3)
from emp
where job='CLERK';

-->WAQTD 2nd half of all the employees name.

select substr(ename,(round((length(ename)/2)+1)))
from emp;

-->WAQTD name of the employees from 2nd char to last but one list.

select substr(ename,2,(length(ename)-2))
from emp;

SMITH :-- MIT :--5-2 :--3


WARD :-- AR :--4-2 :--2

-->WAQTD name of employees whoes name starts with vowel.

select ename
from emp
where substr(ename,1,1) in('A','E','I','O','U');

--> i/p :-- QSPIDERS


o/p :-- qspiDers
-->

select concat
(lower(substr(ename,1,length(ename)/2)),(initcap(substr(ename,length(enam
e)/2)+1))
from emp;

-----------------------------------------------------------
instr() :--
--Instr function is used to obtain the index value if the sub string is
present in the original.
--it will accept upto 4 argum:--
instr('Original String','Substr',position to sart checking,[nth
occurence])

Original String:--This the srtring in which subtring is searched

substring:-- It is the string whoes occurence is to be searched

Position:--It specifies from where to beign the search.

nth occurance:--
--It is not tha manadtory argum..
--If this arg.. is not mentioned then by default value given to
this arg.. is 1
--Is is to indicate the no.. of times a susbtr ocuurs in the
original String
........................................

ex:-- instr('BANANA','A',1)
-->

INSTR('BANANA','A',1)
---------------------
2

INSTR('BANANA','A',2,3)
-----------------------
6
===============================================
replace:--
--replace function is used to overwrite the new String in the original
String

syntax:--
replace('Original String','Substr',['New String']);

ex:--
1. select replace('Bangalore','B','M')
from dual;

REPLACE('
---------
Mangalore

2. replace('Bangalore','A','____')

REPLACE('BANGAL
---------------
B____ng____lore
3. replace('Bangalore','Bangalore')

R
//it will print only space.
-----------------------------------------------------------
--WAQT replace 'T' with '*' in job column of emp table.

..>select replace(job,'T','*')
from emp;

--WAQT replace 'A' with '@','S' with '$' and 'H' with '^' in ename column
of emp table
..>
select replace(replace(replace(ename,'A','@'),'S','$'),'H','^')
from emp;
-----------------------------------------------------------
Trim:--
--Trim function is used to remove the charcater from starting or from
ending or from both the sides.
But,it will not remove the character from middle.

syntax:--
trim(Leading/trailing/both 'char' from 'String')

where Leading:--char will be removed from starting.


trailing :--char will be removed from end
Both:--char will be removed frm both the sides.
note:-- By default if none of the keyword is used then char will be
removed from
both the end.

ex:--
trim(leading 'E' from 'EWELCOME')

--->WELCOME

trim('E' from 'EEEWELCOME')


--->
TRIM('
------
WELCOM

----------------------------------------
Date Function:--
--This function is used to retrieve the date and is used to manipulte the
date.
--Date SRF are:--
1.Add_months()
2.months_between()
3.extract()
4.last_day()

note:--
1.sysdate :-- this command will obtain the current date of the system in
which
RDBSM has been installed.

ex:- select sysdate/current_date


from dual;
2.systemtimestamp:--This command will is used to obtain the date,time and
time zone
of the system.

ex:-- select systemtimestamp


from dual;

--------------------------
1.Add_months():--
--This function is used to add the number of months to a given date.

syntax:--
add_months('Date',no_of_months);

ex:--
select add_months(sysdate,24)
from dual;
--->17-OCT-22

select add_months('01-JAN-2020',24)
from dual;
--->01-JAN-22

--------------------------
2.months_between:--
--This function is used to obtain the number of months between the given
two dates.

syntax:---months_between('Date1','Date2');
1arg:--Higher date
2arg:--Lower date

ex:-- select months_between('17-OCT-2021',sysdate)


from dual;
---------
12
WAQ to fetch your age in year.
-->
select round((months_between(sysdate,'23-OCT-1997')/12))
from dual

WAQ to fetch experience of the employess in year


-->
select round((month_between(sysdate,hiredate)/12))
from emp;

-------------------------------------------------------------------------
--
3.Extract():--
--This fucntion is used to extract the day,month,year from the given date
in number formate.
syntax:--
extract(day/month/year from date)
ex:--
select extract(day from sysdate)
from dual;

SQL> select extract(day from sysdate)


2 from dual;
EXTRACT(DAYFROMSYSDATE)
-----------------------
17

1 select extract(month from sysdate)


2* from dual
SQL> /

EXTRACT(MONTHFROMSYSDATE)
-------------------------
10

select extract(year from sysdate)


2* from dual
SQL> /

EXTRACT(YEARFROMSYSDATE)
------------------------
2020
-------------------------------------------------------------------------
---
waqtd ename and hiredate of the employees hired in MAY month.
--> select ename,hiredate
from emp
where extract(month from hiredate)=5;

|| || || hired on 1st of the month

-->
select ename,hiredate
from emp
where extract(day from hiredate)=1;

|| || || hired in the year 1982.

--> select ename,hiredate


from emp
where extract(year from hiredate)=1982;

|| sal ,deptno of the employees hired in month of either


jan,march,april

---> select sal,deptno


from emp
where extract(month from hiredate) in (1,3,4);
-------------------------------------------------------------------------
--------------
4.last_day():--
-->this function is used to obtain the last day of the month.

syntax:-- last_day(date);

select last_day(sysdate)
from dual;

select last_day('01-FEB-2024')
from dual

=========================================================================
=====
WAQTD total sal(Sal+comm) for the indiv.. employee

General Srf:--
1.Nvl().
2.nvl2().

1.Nvl():--(null value logic)

-->NVL function is used to overcome the drawbacks of operations performed


on null.
syntax:--
nvl(arg1,arg2)

arg1:--
-->we can Write the column name which has null value
-->If the value present in column is null then the value
present in 2nd arg
will be used.
-->If the value prsent in column is not null then arg1
value will returned.

arg2:--
-->Here we write any value which has be to substituted
if the value present in
arg1 is null;
----------------------
WAQTD total sal(Sal+comm) for the indiv.. employee

select sal+nvl(comm,0)
from emp;
-------------------------------------------------------------------------
---------------
2.Nvl2:--
--In oracle nvl2() function is an extension of nvl() function,
with differ in number of arg...
--This function will accept 3 arg:--

syntax:-- nvl2(arg1,arg2,arg3)

--In nvl2() we can pass upto 3 arg...If the 1st arg.. is not
null,then it returns
2nd arg.In the case second 2nd arg is null then it will return
third arg..

---------------------------------------
MRF:-

1.Max():--

--This function is used to btain the max.. value present in the column..
syntax:--
max(column_name/exp)

=========================================================================
========================
Group clause:--

--Group by clause is used to group the records based on certain


attribute.
--Group by clause will execute row-by-row.
--For group by clause we can pass column name as an arg..even multiple
columns can be passed as arg..
--After the execution of group by clause we will get some groups.
--Any clause executed after group by clause it will execute group-by
group.
--We can pass group by clause without using where clause.

sntax:--
select */COlumn_name[Distinct]/Group by expression[Alaising]
from table_name
[where<Filter Condition>]
group by column_name/expression
order by column_name/expression.

Order Of execution:--
1.From
2.Where clause :--Row-By-row
3.Group by clause:--Row-By-row
4.select clause :--Group-by-Group
5.order by clause :--Group-by-Group

-------------------------------------------
Query:--
1.WAQTD no of employees working in each dep..except president.
--
select count(*)
from emp
where job!='PRESIDENT'
group by deptno;

2.WAQTD total salary needed to pay to all the employees in each dept.
-->
3.WAQTD no of employees working as manager in each dept..
4.waqtd avg sal needed to pay all the employees in each dept.. exculding
the employess of deptno 10
5.waqtd no of employees having charcater 'A' in their ename in each job.
-->
select count(*)
from emp
where ename like '%A%'
group by job;

6.waqtd no of employees and avg sal needed to pay the


employees whose sal is greater than 2000 in each dept.
7.watd total sal needed to pay and no of salesman in each job.
-->
8.waqtd no of employees hired on the same day into the same dept.
9.waqtd no of employees getting the same sal in same dept...

=========================================================================
===============
Having Clause:-
--Having clause is sued to filter the groups.
--This means having clause executes after group by clause.
--Since having clause executes after group by.So,having clause will be
executed by group by group
--It will accept MRF as an argument.
--In having clause we can pass the expression used in group by clause.
--Multiple argumm..can be passed.

sntax:--
select */COlumn_name[Distinct]/Group by expression[Alaising]
from table_name
[where<Filter Condition>]
group by column_name/expression
having <Group-By Filter Condition>
order by column_name/expression.

Order Of execution:--
1.From
2.Where clause :--Row-By-row
3.Group by clause:--Row-By-row
4.Having by clause:--Group-by-Group
5.select clause :--Group-by-Group
6.order by clause :--Group-by-Group

WAQTD deatails of employe if in the depart... atleast 2 employees are


working.

select count(*),deptno
from emp
group by deptno
having count(*)>=2
-------------------------------------------------------------
1.waqtd atleast 3 employees working in each dept except president.
select count(*)
from emp
where job!='PRESIDENT'
group by deptno
having count(*)>=3;

2.waqtd total sal needed to pay all the employees in each job if the
total sal of each exceeds 3450
3.waqtd no of employees working as manager in each dept if their average
sal is less than 200
4.waqtd avg sal needed to pay all the employees in each dept exculding
the employee of deptno 20.
If there are atleast 4 employees working in each dept.
5.waqtd no of employees of having char 'S' in their names in each job if
count of employees is equal to 2
-->
select count(*)
from emp
where ename like '%S%'
group by job
having count(*)=2;//no rows selected.

6.waqtd the hiredate and deptno if employees hired on the same day into
the same dept.
-->
select count(*), hiredate,deptno
from emp
group by hiredate,deptno
having count(*)>1
7.waqtd the sal and deptno if employees getting same sal in same dept....
-->
select sal,deptno
from emp
group by sal,deptno
having count(*)>1;

8.waqtd the hiredate which appears more than once in employee table.
9.waqtd the salries which are repeated or duplicate.
------------------------------------------------------------
=========================================================================
============================
Constraints:--
--Constraints are the rules provided to a column to validate the data
during insertion.
--Diff.. types of Constraints are:-
1.not null Constraint.
2.Unique Constraint.
3.check() Constraint.
4.Primary Key Constraint.
5.Foregin key Constraint.
----------------------------
1.not null Constraint:--
--This Constraint is used to restrict the null values into a column,in
other words if a column is defined
as not null,then it will not accept any null.
QQ.Which column will be declared as not null Constraint???
--The attributes or columns which is supposed to be mandatory for each
and every enitity then such
column should be declared as not null.
i.e :-- ename,empId,Usn etc......
2.Unique Constraint:-
--This Constraint will not allow any duplicate value for a column.
QQ>For which column unique Constraint should be used??
--The attributes which are supposed to different from entity to another
entity.
i.e empno,usn,phone number,aadhar card number etc....
3.Check() Constraint:--
--Check() Constraint is used to provide the additional validation for a
column.
ex:--The phone number should contain 10 digit.

check(length(phone num)=10)

---------------------------
Primary Key:--

--For each table Primar key is recomended which help us to access a


record from a table without
any confusion.
--It is combination of not null and unqiue.
--A table should have one primary key.
ex:--empno
--------------------------------
Foregin Key:--
--This Constraint is used to build a relation b/w multiple tables.
--In a table any number of foregin key is allowed.
=========================================================================
=============================
Sub Query:--
--A query written inside another query is known as SUB QUERY.

QQ.When/Why do we use SUB_QUERY.

case 1:-- Whenever value is unknown we will use Subquery.

Ex:-- WAQTD details of employees earning more sal than "ALLEN";

select *
from emp
where sal >
(Outer Query) select sal
from emp
where ename='ALLEN';//Innery Query :--- It
will return the
Sal
of ALLEN.
1250...

--Here the sal of ALLEN is unknown so we need to go for sub-query.

Case2:--Whenever Data to fetched/selected and condition to be excuted


belongs to diff.. table.
Then Suq-query will be used.

WAQTD ename,dname for employess.//Data to be fetched from multiple


tables
----Not Possible Using Sub-Query.
WAQTD ename of employess who is working under dname rese....

Ex:--WQATD the dept name of jones.

select dname
from dept
where deptno=( select deptno
from emp
where ename='JONES');
-------------------------------------------------------------------------
--------
WAQTD number of employees working for king.

select count(*)
from emp
where mgr = (select empno
from emp
where ename='KING');
----------------------
WAQTD name,hiredate of employees who are getting sal more than SMITH but
less than CLARK.
-->>
select ename,hiredate from emp
where sal>(select sal from emp where ename='SMITH') and sal<(select
sal from emp where ename='C
LARK');

WAQTD number of employees who are hired after MARTIN and getting sal less
than KING.
-->
select count(*)
from emp
where hiredate >(select hiredate from emp where ename='MARTIN') and
sal<(select sal from emp wh
ere ename='KING');

COUNT(*)
----------
5
----------------
WAQTD name and deptno of the employees who works in ACCOUNTING dept.
--> select ename,deptno
from emp
where deptno=(select deptno from dept where dname='ACCOUNTING');

WAQTD name and deptno of the employees who earns more than WARD and works
in Research dept.
-->
select ename,deptno
from emp
where sal>(select sal from emp where ename='WARD') and deptno=(select
deptno from dept where

dname='RESEARCH')

-------------------------------------------------------------------------
----------------
watd name and sal of the employees who are working as CLERK in CHICAGO

-->
select ename,sal
from emp
where job='CLERK' and deptno=(select deptno from dept where
loc='CHICAGO')
watd all the details of employees of the employees who are earning less
than
king and working in SMITH
WAQTD details of dept if all the deptno has managers

WIPRO(******)
Watd name of employees working in same job as SCOTT ,getting sal more
than ADAMS and working in dept in
which MARTIN works.
-------------------------------------------------------------------------
-----------------
Diff.. Types Of Subquery:--
1.Single Row Sub-Query.
2.Multi Row Subquery.
3.Nested Sub Query
4.Correlated sub Query

-----------
1.Single Row Sub-Query:--
--If the inner Query returns exactly one record,then it is known as
single row sub-query.
--Normal Operators can be used like =,>,< etc.

ex:--write a query to display deatils of employees working New York


location.

select *
from emp
where deptno=(select deptno from dept where loc='NEW YORK')

2.Multi Row Subquery:--


--If the inner query returns more than one record then such type of
Sub-Query is known as
MRS.
--In this case normal operator can not be used.
Hence opeartors like in,Any,All will be used.

--------------------------
Any And All :--
--These operators are used in where clause and having clause.
--The Any operator returns true if any of the sub-query values meet the
condition. (Or)
--The All operators returns true if all of the subquery values meet
the condition. (and)

syntax:--
(select columnn_name
from table_name
where column_name) ANY/ALL (select column_name from table where
condition)
------------------------
Note:--

1. <ANY :--- Less than Maximum Value. :---


2. >ANY :---Greater than minumn. value.
3. >ALL :---Greater than maxium value.
4. <ALL :---Lesser than minimum value.

----------------------------
WAQTD deatils of employees working in loc 'NEW YORK' and 'DALLAS'.

select *
from emp
where deptno in(select deptno
from dept
where loc in('NEW YORK','DALLAS'));
-------------
select *
from emp
where deptno >ANY(select deptno
from dept
where loc in('NEW YORK','DALLAS')) :--Greater than deptno 10
details i.e 20,30,40.

< ANY :------------------------------


10,20,30 <Any :--10,20.

>ALl
40,10,20,30 :--10,20 --> only details of deptno 30

<ALL
40,10,20,30 :--10,20 --> no rows selected.

=ANY
40,10,20,30 :--10,20 --->Details of employyes belongd to 10,20.
=========================================================================
=========
3.Nested Sub Query:--
--When we Write more than one sub-query then it is known as nested sub-
query.
--We can next upto 255 sub-queries.

WAQTD details of employees getting 2nd maxm.. sal.

select max(sal)
from emp
where sal <(select max(sal)
from emp);
=========================================================================
==================================================
Correlated SUbQuery:--------------------------
=======================================================================
Dis-Advantage of SUb-query:--

1.Data Can not be fetched from multiple tables at time.


2.In case of Sub-Query Complexity and length of Query will increase.
Hence,the performance of an application will be dec..

To overcome all these drawbacks we need to use Joins.


---------------------------------------------------------
Joins:--
--The retrival of data by selecting multiple columns at a time,is known
as JOINS.
--Diff.. tpes of JOINS:--
1.Cartesian Join/Cross Join
2.Inner Join/Equi Join
3.Outer join/Non-Equi Join
a.Left Outer join
b.Right Outer Join
c.Full Outer Join
4.Natural Join
5.Self Join
----------------------------
1.Cartesian Join/Cross Join:--
--In Cross join record from table1 are merged with all the records of
table2
(Here we are going to get o/p as Cross product of records)
--In this type of join user will get matched record as well as un-
matched record.

QQ.Why to use or what is need of Cross Join??


--Whenever there is no relation(Foregin Ke) b/w tables,so no other
types of joins will work.
So,we need to go for Cross Join manadatory.
Syntax:--
ANSI:--
select *
from table_name1 cross join Table_name2 ........cross join
table_n;

Oracle:--
select *
from table_name1,Table_name2,table_n;

ex:--
select *
from emp cross join dept cross join salgrade;

-----------------------------------------------------------
2.Inner join:--

--This Join will return only the matching record from mutiple tables.
To filter un-matching record here where clause will be used.
--To use ineer join relation(common column) between table is manadatory

ANSI:--
select */column_name/exres....
from table1 inner join table2.....inner join table_n
on <Join_Condition> ;

Oracle:--
select */column_name/exres....
from table1,table2,table_n
where <Join_Condition>;
------------------------------
-->Waqtd ename,sal,dname,deptno for all the employees.

SQL> select ename,sal,dname,deptno


2 from emp inner join dept
3 on emp.deptno=dept.deptno;
select ename,sal,dname,deptno
*
ERROR at line 1:
ORA-00918: column ambiguously defined

---This Problem can be solved in 2 ways:--


1.By providing Table Alias name
select ename,sal,dname,e.deptno,d.deptno
from emp e inner join dept d
on e.deptno=d.deptno

2.By using table_name.column_name for the column which is common.


-------------------------------------------------------------------------
-----------------------
1.WAQTD name of employees along with his location for all the employees.
2.WAQTD name of employees and his deptname if the employees works as
SALESMAN
3.WAQTD dname and annual sal for the employees who earns more tahn 1500.
4.WAQTD ename,dname,hiredate for all th employees who are hired during
87.

select ename,dname,hiredate
from emp e,dept d
where e.deptno=d.deptno and to_char(hiredate,'YY')=87;

select ename,dname,hiredate
from emp ,dept
where emp.deptno=dept.deptno and to_char(hiredate,'YY')=87;

5.WAQTD name,dname,sal fr the employees if the employees jobs and dname


starts with same character 'S'
--> select ename,dname,sal
from emp inner join dept
on emp.deptno=dept.deptno and job like 'S%'and dname like 'S%';

6.WAQTD dname,sal and sal with hike of 25% if the employees sal is less
than 2500 and works
in NEW YORk
--> select dname,sal,(sal*25/100) as "HIKED SAL"
from emp e inner join dept d
on e.deptno=d.deptno
where sal<2500 and loc='NEW YORK';
7.WAQTD ename,sal,deptno for all the employees if the are working as
MANAGER or CLERK with sal more tahn jones
--->
select ename,sal,deptno
from emp e inner join dept d
on e.deptno = d.deptno
where job in('MANAGER','CLERK') and sal>(select sal from emp where
ename='JONES');

8.WAQTD employees name,deptno ,dname if the employyes gets max..sal


-->
select ename,dept.deptno,dname from emp inner join dept on
sal=(select max(sal) from emp);

9.WAQTD name,deptno,comm,dname of SMITHS manager.


-->

select ename,dname,comm,e.deptno,d.deptno
from emp e,dept d
where e.deptno=d.deptno
and empno=(select mgr from emp where
ename='SMITH')
-------------------------------------------------------------------------
-------------------------
WAQTD max sal in each dept.

select max(sal)
from emp
group by dept;

=========================================================================
=================================
3.Outer Join:--
--Comm.. column b/w table is manadatory
1.Left Outer Join:--
--Left outer join is used to obtain unmatching record from left
table along
with matching record
But from right table only the matching record.

syntax:---

ANSI:--
select *
from table1 left join table2
on <JOIN_CONDIITON>

Oracle:--
select *
from table1,table2...tablen
where table1.column_name=table2.column(+);

2.Right outer Join:--


--Right outer join will return ::--Matching and unmatching record
from right table
---Only matching record from left
table.
syntax:---
ANSI:--
select *
from table1 right join table2
on <JOIN_CONDIITON>

Oracle:--
select *
from table1,table2...tablen
where table1.column_name(+)=table2.column;

-------------------------------------------------------------------------
-------
3.Full outer join:--

ANSI:-- select *
from table1 full join tabel2.........table_n
on<Join_Condition>.

Oracle :-- No Syntax.


=========================================================================
=================
4.Natural Join:--
-->Natural join is similar to inner join,but we will not write any
joining condition.
-->It automatically combines the common column ,returns inner join
output.
But if there is no common column b/w tables then it will return
cross join o/p.

If Realtion b/w table :---- Returns same o/p as of Inner join


If no relation b/w tables :---Returns o/p of Cross join..

ANSI:--
select *
from table_name1 natural join table_name2.......table_name_n.

Oracle:-- No Syntax.
---------------------------------------------
WAQTD name of employees and department name if the employees names first
character
is 'A' or 'S' and employees should be
earning more than 'SMITH' and also he
has to hired before the last employee and he may or might be reporting to
KING or JONES
=====
WAQTD employees name and department name if employees are working in
same location as his manger.
=========================================================================
================
SELF JOIN:---

---Joining the same table multiple number of times is known as Self


Join.
---It is used to display the data present in same table but diff..
record.

syntax:---

ANSI:--

select */col.......................
from table_name1 join table_name2
on<Join_Condition>

Oracle:--
select */column_name
from table_name1,table_name1...........
where<Join_Condition>
-----------------------------------------------------
WAQTD employees name and his manager's name;

select e1.ename EMPLOYEENAME,e2.ename MGRNAME


from emp e1 join emp e2
on e1.mgr=e2.empno;

WAQTD name of employees and his manager name if employees are working as
CLERK
select e1.ename EMPLOYEENAME,e2.ename MGRNAME
from emp e1 join emp e2
on e1.mgr=e2.empno
where e1.job='CLERK';

WAQTD name of the employees and manager deignation (job) if manager works
in deptno 10 ,20.

--
select e1.ename EMPLOYEENAME,e2.job MGRJOB
from emp e1 join emp e2
on e1.mgr=e2.empno
where e2.deptno in(10,20)
--------------------------------------------------------------
WAQTD all the details of employees if employees are earning more sal than
their manager.

EMPNO ENAME JOB MGR HIREDATE SAL


------ ---------- --------- ---------- --------- ---------- -
7369 SMITH CLERK 7902 17-DEC-80 800 ...no
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 ...no
7521 WARD SALESMAN 7698 22-FEB-81 1250 ...no
7566 JONES MANAGER 7839 02-APR-81 2975 ...no
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 ...no
7698 BLAKE MANAGER 7839 01-MAY-81 2850 ...no
7782 CLARK MANAGER 7839 09-JUN-81 2450 ...no
7788 SCOTT ANALYST 7566 19-APR-87 3000 ...yes
7839 KING PRESIDENT 17-NOV-81 5000
7844 TURNER SALESMAN 7698 08-SEP-81 1500
7876 ADAMS CLERK 7788 23-MAY-87 1100
7900 JAMES CLERK 7698 03-DEC-81 950
7902 FORD ANALYST 7566 03-DEC-81 3000 .....yes
7934 MILLER CLERK 7782 23-JAN-82 1300

7788 SCOTT ANALYST 7566 19-APR-87 3000 ...yes


7902 FORD ANALYST 7566 03-DEC-81 3000 .....yes

--
select *
from emp e1 join emp e2
on e1.mgr=e2.empno
where e1.sal>e2.sal
--------------------------------
WAQTD the employees name ,his manager name,manager's manager's name.
-->
select e1.ename EMPNAME,e2.ename MGRNAME,e3.ename "MANAGER MANAGERS
NAME"
from emp e1 join emp e2 join emp e3
where e1.mgr=e2.empno and e2.mgr=e3.empno;

=========================================
1.WAQTD name of the employees and managers sal if employees and manager
both erans more than 2300
2.WAQTD empn name and manager hiredate if emp.. was hired before 1982
3.WAQTD emp name and manager comm if employees works as SALESMAN and
manager works in deptno 30
4.WAQTD emp name,hiredate and hiredate of manager if managers hired
before employees
5.WAQTD ename and mgr name if both are working in same job

6.WAQTD emp name and mgr name along with their annual sal if
employees is working in deptno 10,20 and
mgr sal>employee sal;

select e1.ename EMPLOYEENAME,e2.ename MGRNAME,e1.sal*12 "EMPLOYEE ANNUAL


SAL",e2.sal*12 "MANAGER ANNUAL SAL"
from emp e1,emp e2
where e1.mgr=e2.empno and e1.deptno in(10,20) and e2.sal>e1.sal;

=========================================================================
==================================================
DDL(Data Defin.. Langauage):--
--It is used to define/create,drop the table into the DB.
or it Defines properties of a table in DB.
-->Stmt's of DDL are:--
1. create
2. Rename
3.Alter.
4.Truncate
5.Drop.
-----------------------
1.Create:--It is used to create a table into the DB.
syntax:--
create table table_name
(
Column_name-1 data_type(size) not null/null,
Column_name-2 data_type(size) not null/null,
Column_name-3 data_type(size) not null/null,
......
......
......
Column_name-n data_type(size) not null/null,
Constraint constraint_ref_name1 unique(Column_name),
Constraint constraint_ref_name2 primary key(Column_name),
Constraint constraint_ref_name check(Condition),
refernces parent_table_name(Column_name)
);

Employee

EMPID ENAME ESAL PHONENUM EMAIL DEPTNO

(Primary) (Check) (Unique)

-------------------
create table Employee
(
EMPID number(6) not null,
ENMAE varchar(15) not null,
ESAL number(6,3) null,
PHONENUM number(10) not null,
EMAIL varchar(15) not null,
DEPTNO number(3) not null,
constraint EMP_ID primary key(EMPID),
constraint PHO_NENUM check(length(PHONENUM)=10),
constraint EMA_IL unique(EMAIL)
);
--------------------
Write a Query to Create Duplicate table in DB.

create table table_name as select * from Original Table;


---> create table Dinga as select * from emp
------------------------------------------
2.Rename:--
--It is used to change the name of table,column etc...

Syntax:--
rename Current_Table_Name to New_Table_Name;

i.e rename dinga to dingi;

3.Alter:--

a.) To add a column to exisiting table:--

sntax:-- alter table table_name


add column_name data_type [Not null/null];

i.e:-- alter table dingi


add address varchar(20)

b.) To delete a column from table:--


syntax:-- alter table table_name
drop column column_name;
i.e :--
alter table dingi
drop column address;

c.)TO change The data type:--


syntax:--
alter table table_name
modify column_name new_dataType.

i.e:-- alter table employee


modify deptno varchar(4);
d.)To change the colum_name :--

syntax:-- alter table table_name


rename column current_columnName to New_COlumnName;

i.e:-- alter table employee


rename column empid to mgrid;

e.)To modify/Add the constraints:--

syntax:---
alter table table_name
add constraint constraint_ref_name
constraint_name(Column_name);

i.e:--
alter table employee
add constraint PH_NUM unique(PHONENUM);

f.)To Drop/Disable/Enable A constraint :--

synatx:--
ater table table_name
drop/disable/enable constraint constraint_ref_name;

i.e:--

alter table employee


drop constraint PH_NUM;
-------------------------------------------------------------------------
--------------------
4.Truncate:--
--It will delete all the record from table,but tabel Structure will
remain same.

syntax:-- truncate table table_name;

i.e:-
truncate table dingi;

Table truncated.

SQL> select *
2 from dingi;

no rows selected

5.Drop:--

--It will delete all the record from table,even table structure will be
deleted.

syntax:-- drop table table_name;

note:--
But table will not be dropped parman.. from database,it will be
present in recycle bin.

case 1:-- To recover the table:--

syntax:- flashback table table_name


to before drop;
i.e
flashback table company
to before drop;

Case 2:- Table to Be deleted Parm..


1. Table need to be dropped.
then use :--
purge table table_name;

i.e
SQL> purge table company;

Table purged.
-------------------------------------------------------------------------
----
create table students
(
USN varchar(10) not null,
NAME varchar(10) not null,
Marks number(4,3) not null,
PhoneNumber number(10) not null,
Email varchar(20) not null,
constraint UU_SN primary key(USN),
constraint P_honeNumber unique(PhoneNumber),
constraint PP_honeNumber check(length(PhoneNumber)=10),
constraint E_mail unique(Email)
)

DML(Data Manipulation Language):--

1.Insert
2.delete
3.update.
------------------------------------------------------------
1.Insert:--
--It is used to insert the record into the table.

Syntax 1:--

insert into table_name values(va1,v2,v3................vn);

note:--This sntax can be used whenever we have minum.. number of column


prsent in table.

Syntax 2:--
insert into table_name(column1,column2.....column_n)
values(v1,v2..............vn);

i.e -->SQL> insert into students(email,name,marks,usn,PHONENUMBER)


values('syed@123','SYED',3.6,'1st14cs12'
,1234567899);

note:--
1.This is applicable whenever we have maximumn number of record.
2.While inserting the value column name can be inter changed.

Syntax 3:--
--This Syntax is used to copy the records from another table to Current
table.

insert into table_name


select statement;
Rules:--
1.Both the table should have same number of column.
2.Both the columns table should have Same data types.

------------------------------------
write a query to copy records from emp table to minga table only if
employees
are working in deptno 20,30

insert into minga


select *
from emp
where deptno in(20,30);
=========================================================================
==========================
2.Update:--

--Used to update the specific data into the table.

syntax:--
update table_name
set column1=value1,column2=value2....
where <Filter-Condition>
i.e
update students
set PHONENUMBER=9999999999
where usn='st13071';

-------------------------------
3.Delete:--
--IT is used to delete the specific record from table.

syntax:--
delete from table_name
where <Filter_Condition>

i.e:--delete from students where usn='1st14cs12';


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

You might also like