SQL Notes
SQL Notes
SQL Notes
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.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:--connect username;
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.
syntax:- varchar(size)
size=It speciifies the max number of char.. that can be
stored in a single cell.
---------------------------------------
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.
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.
i.e 5+0 =5
5+null = null
8/null = null
---------------------------
1.DQL(DATA QUERY LANGUAGE):--//10
-------------------------------------
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.
-------------------------------------------------------------------------
-----------------------------------
------------------------------------------------------------------------
---------
Distinct :--
--Distinct clause is used to remove duplicate records
present in result table,
which helps user to access only the unique records.
-------------------------------------------------------------------------
---------
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.
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:--
----------------------------------------------
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;
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 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.
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'
---------------------------------------------------------------------
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;
-->
select ename
from emp
where job='MANAGER' and hiredate>'30-APR-81';
-->
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);
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:--
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);
syntax:---
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:--
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;
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;
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';
note:--
1. To check whether the string is ending with specific char
'%Char name';
select *
from emp where ename like 'A%';
3.To check whether the name starts and ends with specific.. char or not
'startingChar%endingChar';
select *
from emp
where ename like 'S%H';
WAQTD name of employees who has 'A' at their second place of their
ename.
select *
from emp
where ename like '_A%'
-------------------------------------------------------------------------
----------
WAQTD name of employees if his name conatins of 'A' char and ends with H
char.
select *
from emp where ename like '%A%H';
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:-
select *
from emp
where ename not like '%!_%' escape '!';
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.
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
-- 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:--
----------------------------------------------
3.Absolute():--
--This function will obtain the maginitude of the given number.
--It will accept only one arg:--
syntax:--
abs(number)
syntax:--sqrt(number)
select sqrt(64)
from dual;
--->8
--------------------------------------------
5.Round():--
0-0.4 :--0
0.5-0.9 :--1.0 :--1
syntax:-- round(number,[Scale])
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])
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
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')
select ename
from emp
where length(ename)=4;
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.
-->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
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
-->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';
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;
select ename
from emp
where substr(ename,1,1) in('A','E','I','O','U');
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])
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')
ex:--
trim(leading 'E' from 'EWELCOME')
--->WELCOME
----------------------------------------
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.
--------------------------
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
-------------------------------------------------------------------------
--
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;
EXTRACT(MONTHFROMSYSDATE)
-------------------------
10
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;
-->
select ename,hiredate
from emp
where extract(day from hiredate)=1;
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().
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:--
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;
=========================================================================
===============
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
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:--
select *
from emp
where sal >
(Outer Query) select sal
from emp
where ename='ALLEN';//Innery Query :--- It
will return the
Sal
of ALLEN.
1250...
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.
select *
from emp
where deptno=(select deptno from dept where loc='NEW YORK')
--------------------------
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:--
----------------------------
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.
>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.
select max(sal)
from emp
where sal <(select max(sal)
from emp);
=========================================================================
==================================================
Correlated SUbQuery:--------------------------
=======================================================================
Dis-Advantage of SUb-query:--
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.
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;
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');
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(+);
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>.
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:---
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;
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.
--
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;
=========================================================================
==================================================
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
-------------------
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.
Syntax:--
rename Current_Table_Name to New_Table_Name;
3.Alter:--
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);
synatx:--
ater table table_name
drop/disable/enable constraint constraint_ref_name;
i.e:--
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.
note:--
But table will not be dropped parman.. from database,it will be
present in recycle bin.
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)
)
1.Insert
2.delete
3.update.
------------------------------------------------------------
1.Insert:--
--It is used to insert the record into the table.
Syntax 1:--
Syntax 2:--
insert into table_name(column1,column2.....column_n)
values(v1,v2..............vn);
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.
------------------------------------
write a query to copy records from emp table to minga table only if
employees
are working in deptno 20,30
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>