SQL
SQL
Information:---
-->Collection of data becomes information.
====================================
Note::--now simply storing the data is not important ,how fast we can retreieve
it is very important.
DataBase:---
---A medium to store data/infomation in an organized manner and
systematic manner is known as database.
---Every Database will havs some functionalities::---
1.inserting the data
2.Reading the data/Retrieving the data.
3.Modify the data
4.Delete the data.
5.Manage the data..............etc...
=========================================================================
DBMS:--(Data Base Management System):----
--->A software (set of program) which is used to create,manage and maniuplate the database.
===========
Ex of DBMS are:--
1.Oracle RDBMS.
2.Mongo DB.
3.Sql Server.
4.MySql
5.Postgre
6.DB2 etc...............
===================
Query Language:--
--It is usted to Communicate with the DBMS system software..
or
A medium which helps user/programmer to Communicate with DBMS
is known as Query lang...
==================
A DBMS s/w may have any of the following model for Storing the data::---
--Hieararchial Model
--Network Model
***(Sql)--Relational Model
--Object Model
**(MONGO DB)--Documnet model etc................
======================================================================================
==========
Hiearchical Model::--
This types of DBMS employs the parent child relationship of Storing data.
This type of DBMS is rarely used because of:--
1.Complexity Increase
2.Maintaince cost will be high
3.It will not have good perf..while retrieving
==========================
Network Model::--
--It supports many-many relations which leads to complex structure of DBMS.
====================================================================================
Relational Model::---
--This Model was given By E.F Codd.In this type of Model data will be stored data in the
form of
row and COl...(i.e Table)
===================================================
RDBMS:--(Relational Data BAse Management System)::---
-->A type of DBMS system software which stores and organises the data in the using
relational model,
such DBMS is known as RDBMS.
insert,update,delete..
========
**** what is diff b/w truncate,delete and drop.
Ans:--
Trucate will delete entire row of a table where drop will delete rowas well as table
structure
and delete is used to delete only specific data.
================================================================
TCL:-Transcation Control Langauge):--
commit,rollback,savepoint.
commit::-It is used to save a transaction in Database.
Rollback:--Rollback is used to undo a transaction which is not saved.
Savepoint:--It is used to mark a position of a transaction.
=================================================================
DCL(Data Control Langauge)---
grant,revoke
grant:--it is used to give permission to another user to access the table.
revoke:--It is used to take back the permission to another user.
==================================================================
DQL(Data Query Language):
--Fetching a data from data base.
====================================================================
2.varchar:--
--varchar datatype is used to store character
such as :--
A-Z,a-z,0-9,and special
character(@,#,*,%,$...)
--For varchar data type we can pass an arg as Size.
--Tha maximum size of varchar datatypes is 4000bytes
syntax:--
varchar(size)
where size specifies the max. no of
characters that can be stored.
---Varchar data is a variable length data type,
therfore there will be no-memory wastage.
---in varchar memory will be allocated at the
time of storing the value.
======================================================================================
========
number:
--this data type is used to store int value as well as double value
--this data types cab accept upto 2 arg(precision,[scale]),where 2nd arg is optional.
--if we want to store only int then no need to pass scale arg.
number:--
number(precision,scale(optional))
i.e:
precision:--it represnts total no of digit that can be stored in single cell
notes:--
1.null value does not require any memory.
2.null does not represents zero or space.
3.in oracle-RDBMS two null are unique
ie. null1 != null2;
1.select:---The retrival of data from the table in the database is done using select stmt.
syntax:-
select */(Distinct)Colm_Name/expression[Alias]
from table_Name;
Order Of execution:--
1.from clause
-->From clause will execute 1st and it used to search the table present
in database under execution.
2.select clause
--After the execution of from clause we will get some table and from the
table we are going to select the colm..which is required
Query:--
1.WATD deatils of all employe.
--->>select * from emp;
2.WATD name,sal,deptno of employe.
-->>select ename,sal,deptno from emp;
-------------------------------------------------------------------------
Expression::---
====================
1.WATD Annual Sal of all employe..
---->
select sal*12
from emp;
note:--
select sal*12 ANNUAL SALARY
from emp;
-
Error:--
FROM keyword not found where expected
****If user want to Give 2 string as Alias name then we need to use " "
ex:--
WAQTD unique job from employe table
--->select distinct job from emp;
======================================================================================
========
Selection:--
-->The retrival of data by selecting either columns and rows is known as Selection.
syantx:--
select */(Distinct)Colm_Name/expression[Alias]
from table_Name;
where<filter_Condition.
Where Clause:--
Order of EXecution:---
1.from clause :--brings the req..table under execution.
2.where clause:--filters the unwanted record.
3.select clause:--selects the wanted record.
-->WAQTD name of employee and his job if and only if he is working as president
>>>
-->WAQTD name,sal with 10% hike if his sal less than 2000
-->WAQTD name and hiredate of employee only if they are working as MANAGER.
select ename,mgr,deptno
from emp
where deptno=20 and job='MANAGER'
-->WAQTD all the details of employe and annual sal if he works as anaylst..
==============================================================================
Order by Clause:--
---Order by Clause is used to sort/arrange the records either in
ascending or or in dec.. order
---By default Order by Clasue sorts the record in ascending order.
synatx:--
select */(Distinct)Colm_Name/expression[Alias]
from table_Name;
where<filter_Condition.
order by colm_name/expression asc/desc;
order of execution:--
1.from clause
2.where by Clause---row by row
3.select Clause-----row by row
4.order by Clause.--row by row
=========================================================
waqtd sort sal in desc order.
--->
select *
from emp
order by sal desc
=======================================================>>>
Can be pass more than one column for Order by clause??
--->Yes,we can pass more than one column for Order by clause.
--->But First prority will be given to first.
==================================================================
WAQTD and sort table emp based on sal,deptno.
->In this case complier will give priority for
sal column because it is the first col name we passed in order by,
then complier will even check deptno colm also
and if we have any duplicate sal in sal colm then that duplicate sal will
be sorted based on deptno.
SAL COMM DEPTNO
---- ---------- ----------
800 20
950 30
1100 20
1250 1400 20
1250 500 30
1300 10
1500 0 30
1600 300 30
2450 10
2850 30
2975 20
3000 20
3000 30
5000 10
=============================================================================
Operators:
--it is used to perform some operation.
-Operators IN SQL:--
a.Arithmetic Operator
b.Concatination Operator
c.Logical Operator
d.Comparision operator
e.Relational operator.
f.Special operator
1.In
2.not In
3.between
4.not between
5.is
6.not IS
7.Like
8.not Like
g.Sub query operator
1.All
2.ANY
3.exists
4.not exists.
=============================================================
b.Concatination Operator:-(||)(Pipe Operator)
--This operator is used to join the given two String.
SO it eanbles usto display output in sentence formate.
ex:---
HI SMITH
WAQTD HI repsective name your sal has been hiked by 10% (hiked sal should be printed)
and you are working in repsective deptno.
=========================================================
Logical Operator:--
AND :It will check both/Multiple cond..
if all cond..is true we wll get output as true otherwise false
0 0 -------0
0 1 -------0
1 0 -------0
1 1 -------1
OR :It will check all the condition and if either of
cond..is true we wll get output as true.
0 0 -------0
0 1 -------1
1 0 -------1
1 1 -------1
===================================================================
Special operator:---
1.In operator:--
--In operator is a multi valued opertor which can accept single value(COl_name) at LHS
and multiple value at RHS.
--In operator returns true if any of the value present on RHS satifies the condition,
otherwise it returns false
sntax:--
col_name/expression in(va,v2,v3.............vn);
2.Not In operator:--
--It performs reverse operation of in opertor
=======================================================================
Like Operator:----
======================================================
what should be done if i want to select a name which contains specail character.
ex:--Bahu_Bali
==========================================================================
Function:---
--Functions are the named block of code or list of instructions which are
used to perform a particular operation
--Function conatins/Consists of 3 major componenets:--
1.Function name
2.No of argu.. or input
3.Return types.
--There are 2 types of function present in SQl namely:
1.Single Row Function.(SRF)
2.Multi Row Function.(MRF)
syntax:- abs(10)
o/p:10
abs(-240)
o/p:240
===============================
4.SQRT():--this function is used to obtain square root of a number.
--I will take only one arg
syntax:--sqrt(number)
ex:--sqrt(81)
ex::-9
sqrt(2)
ex:-1.414
============================
0.0-0.4::--0
0.5-0.9::--1.0
5.round()::--
--Round funct is used to round-off the given number to the nearest number.
--It can accept upto 2 arg..where 2 and arg..is optional;
syn::-- round(number,[scale])
scale is optional,it can be -ve as well as +ve
-ve scale::---means before the decimal point and the count starts from 1
+ve scale:--means after the the decimal point and count starts frm 0.
==========================================
===========================================
0.0-0.4=0
0.5-0.9=1
Trunc():--
--This function is used to round off the given number always to a lower value.
--Trunc(number,[scale])
scale is optional,it can be -ve as well as +ve
-ve scale::---means before the decimal point and the count starts from 1
+ve scale:--means after the the decimal point and count starts frm 0.
round(5.5)
--6
trunc(5.5)
5
round(56.96,-1):--
==================================================================
Character SRF::--
Case Manipulation Function
--upper()
--lower()
--initcap()
Character Manipulation Function
---length()
---concat()
---reverse()
---substr()
---instr()
---replace()
---trim()
====================================================================
1.Upper():--Converts given String to upper case.
synax:-- upper('String')
ex:-- upper('jspiders')
---JSPIDERS
2.lower():--converts given String to lower case.
syn:-- lower('String')
ex:-- lower('JSPIDERS')
--- jspiders
3.initcap():--It converts the first character of each word of the sentence into uppercase.
syntx:--initcap('String')
===================================================================
1.length():--
--This function is used to obtain length of the given String,even space will be counted.
synx:--length('String')
ex:-- length('JSPIDERS')
---8
length('India Is Great')
--
WAQTD name of employees having 4 characters in their name.
select ename
from emp
where length(ename)=4;
select *
from emp
where length(sal)=4;
=======================================
2.reverse():--Used to reverse the given String..
Syntax:--reverse('String')
ex:--reverse('MADAM')
reverse('RAM'):---MAR
select reverse(ename)
from emp;
=========================================
3.Concat():--
--This function is used to merge the given two String.
syn:--
concat('Str1','Str2')
========================================
-WAQTD HI repsective name your sal has been hiked by 10% (hiked sal should be printed)
and you are working in repsective deptno(print the deptno of each employe)
======================================================
Substr():---
-this function is used to obtain substring(part of a string) from a given origianl String.
-This function can accept 3 arg..
syntax:--
substr('Original String','Position',[Length])
Arg1:--Original String
--This is the String from which subString will be extracted.
Arg2::-Position
--It specifies from where to begin the extraction.
Arg3:Length:--
--Length arg is not manadtory arg..
--If the lenght is not mentioned we have to consider the complete length of the String after
the starting position
--It specifies the number of character to be extracted.
====
Position::starts from 1
here position can be positive and it can be negative.
But ,length can be only +ve.
ex:---- ------------------>+ve
1 2 3 4 5 6 7 8
J S P I D E R S
-8 -7..........-1
-ve <-------------------
ex:---
J S P I D E R S
S P I
substr('JSPIDERS',2,3)
substr('JSPIDERS',2)
JSPIDERS:---ERS.....
1.WAT to extract first 3 char of employe name.
select substr(ename,1,3)
from emp;
2.WATD first 3 char of employe working as CLERK;
select substr(ename,1,3)
from emp
where job='CLERK';
select ename
from emp
where substr(ename,1,1) in ('A','E','I','O','U');
-------->>>
substr(ename,round(lenght(ename)/2),1)
SMITH
5-3==3
6-2=4...............................
MIT
select substr(ename,round(length(ename)-2))
from emp.
6.
QSPIDERS:----qspiDers
concat(lower(substr(ename,1,length(ename)/2)) ,initcap(substr(ename,length(ename)/2)+1)
)
select concat(lower(substr(ename,1,length(ename)/2)),
initcap(substr(ename((length(ename)/2)+1))))
======================================================================
instr():--
--instr function is used to obtain the index value if the sub string is present in the
original.
1.Orgiginal String:--
--This is the String in which substring to be searched
2.substr:---
--it is the String whose occurence is to be searched in the Original String.
3.position:-
--It specifies from where to begin the search
4.nth occurence:--
--it is not the manda... arg..
-If the nth occurence is not mentioned ,the deafult value given to is is 1st occurence
-It is to indicate the no of times a susbtr occurs in the original String..
ex:-- JSPIDERS
S:--1 occurence
instr('JSPIDERS','S',1)
select instr('JSPIDERSAFFGS','S',2,3)
from dual
13..
============================================
replace:---
this function is used to overwrite substring with new String in the original String..
syn:---
replace('Original String','SUBSTR',['New String to replaced']).
ex:-- DINGA
---PINGA
replace('DINGA','D','P')
replace('DINGA', 'DINGA')
======================================================================================
========
trim():--
--Trim function is used to remove characters from the begining or from the end or from both
the ends but not from middle.
syntax:--
trim(leading/trailing/both 'CHAR' from 'String')
1.ADD_MONTHS():--
syntax:-- add_months('DATE',no_of_months)
ex:--
select add_months(sysdate,24)
from dual;
o/p:--ADD_MONTH
---------
21-JUL-22
2.MONTHS_BETWEEN():--
--This function is used to obtain the number of months
between the given two date.
syntax:-- months_between('DATE1','DATE2')
ex:--
select months_between('21-JUL-22',sysdate)
from dual;
o/p:---
MONTHS_BETWEEN('21-JUL-22',SYSDATE)
-----------------------------------
24
==================================
WAQ to fetch expre....of all employess in years from emp date.
===========================================================
extract():--
ex:--
select extract(day from sysdate)
from dual;
EXTRACT(DAYFROMSYSDATE)
-----------------------
21
select extract(month from sysdate)
from dual
EXTRACT(MONTHFROMSYSDATE)
-------------------------
7
select extract(year from sysdate
from dual
EXTRACT(YEARFROMSYSDATE)
------------------------
2020
Note:--Userdefined date can not be passed directly
if user wants to pass then 1st date string should be converted
to date formate.
===========================================
waqtd ename a
nd hiredate of employee hired in may month.
===================================================================
last_day():--
--This function is used to obtain the last day of the
given month in the given date.
syntax:--
last_day('date')
select last_day(sysdate)
from dual;
290-161-029
======================================================================================
=====
General SRF:--
1.nvl()
2.nvl2()
syntax:--nvl(arg1,arg2)
Arg1:--
--In arg1 we can write the column namewhich has null value
-If the value present in column is null then the value present in arg2 is returned.
-If the value present in column is not null then the same value of arg1 will be returned
Arg2:
Here we write any value which has be to substituted if the value present in arg1 is null
======================================================================================
====
nvl2()::---
--The oracle nvl2() function is an extension of nvl() function with diff option based on
whether a null value exists.
syntax:-- nvl2(arg1,arg2,arg3)
--in nvl2() function we can pass upto 3 arg.If the 1st arg.. is not null,then it returns
the 2nd arg.In case the second arg..is null then it returns third arg.
======================================================================================
======
Conversion SRF:---
1.ascii()
2.to_date()
3.to_char()
syntax:-- to_char(date,'FORMAT-MODEL').
FORMAT-MODELS are:--
1.Year:---twenty twenty
2.YYYY :--2020
3.YY :--20
4.MONTH :--JULY
5.MON :--JUL
6.MM :--07
7.DAY :--MONDAY
8.DY :--MON
9.DD :--19
10 D :-- 9......
===================================================================
Multi Row Function:----
1.max():--
--this function is used to obtain the maximum value present in
a column.
syn:
max(column_name/exp).
2.min():--
--this function is used to obtain the min value present
in a column.
syn:
min(column_name/exp).
3.sum():--
--This func.. is used to obtain the summation of all the values
present in a given column.
synx:--sum(column_name/exp).
4. avg():--
--this function is used to obtain the average of all the
values present in the column.
synx:--avg(column_name/exp).
5.count:
---it is used to count the no of records present in the result table.
--Count() is the only funct....for which we can pass *
or column name or exp as an arg..
synx:--count(*/column_name/exp).
note:--
1.for sum() and avg() function we can pass only those
column which contains number data type.
2.MRF() will ignore all the null values.
3.we cannot pass MRF() in where clause.
===========================================================================
note:-
1.For MRF we can pass only single arg i.ecolm_name/exp
2.MRF() will ignore all the null values.
3.we cannot pass MRF() in where clause.
--------------------------------------------------------------------------------------
--------------------------
1.WAQTD max sal,min sal, and total sal needed to pay for the
all the employess
2.WAQTD number of employess getting sal less than 2000 in detno 20,10
3.waqtd average sal needed to pay for employes working as "SALESMAN";
4.WAQTD no. of employees working as clerk;
5.WAQTD no.. of employees having A as their first char.. in ename;
6.WAQTD total sal needed to pay for the employees hired in the
month of FEB.
7.WAQTD no..of employees earning comm in deptno 20
8.WAQTD avg sal,total sal,number of employees and max..
sal given to employees working as PRESIDENT
--------------------------------------------------------------------------------------
--------------
*** in case of MRF only one column name should be passed in select clasue.
==============================
waqtd name and max sal of the employees who are working as clerk.
waqtd max(sal),min(sal) and total sal needed to pay fro all employees.
===========================================
waqtd no of employees getting sal less than 2000 in deptno 20
---
waqtd average sal needed to pay all the employees.
---
WAQTD no of employees having 'A' as their first character.
Waqtd no of employees working as clerk or manager...
WAQTD total sal needed to pay employess hired in FEB... month
-->
=============================================================
Group by Clause:---
--Group by clause is used to group the record based on certian
attribute.
--Group by clause executes 'ROW-BY-ROW'.
--For group by clause we can pass column_name as an arg..
--After the execution of group by clause we will get some
groups.
--Any clause which executes after group by clause will exceute
'GROUP-BY- GROUP'.
--we can pass group by clause without using where clause.
=============================================================
WAQTD no of employees working in each dept..except president.
-->
WAQTD total salary needed to pay to all the employees in each dept.
============================================================================
waqtd atleast 4 employees working in each dept except president.
waqtd total sal needed to pay all the employees in each job if the
total sal of each exceeds 3450
waqtd avg sal needed to pay all the employees in each dept
exculding the employee of deptno 20.If there are atleast
3 employees working in each dept.
waqtd the hiredate which appears more than once in employee table.
2.Unique Constraint:--
--this Constraint will not allow any duplicate value for a column.
-->Which Column should be decl..as unique.
----The attributes which are supposed to be different for each
and every enitity must be defined as Unique Constraint
ex:--empid,usn,pancard etc.................
3.check() Constraint:---
--check() Constraint is used to provide additional validation
for a column.
ex:-- The phone number should conatin exactly 10 digit.
check(length(phone)=10).
4.Primary Key:---
--For each table having Primary Key is highly recom....,
which helps to access a record in a table without having
any confusion(Ambiguity)
--It is a combination of not null and unique.
--A table should have one primary key.
Candidate Key:--
--The columns which are eligi... for PK is known Candidate Key
ex:--USN+PHONE NUM.
ALternate Key:--
--The column which is eligi.. for PK but not selected as PK,
it is knwon as Alternate Key
5.Foregin key:---
--It is used to build a relationship between the tables.
--in a table we can have any no of foregin key..
--A table in which foreign key is present is known as child table and table to which foreign
key belongs is known as
Parent table.
--A foreign key must and should be defined as primary key in its parent table.
--A column defined as foregin key can accept the null and duplicate vlues in child table.
--A column defiend as foreign key cannot accept a value which is not present in its parent
table column.
===========================================================
***SUB-QUERY:--
--An query written inside another query is known as SUB-QUERY.
WHEN/WHY do we use sub-query::?
case 1:--whenever we have unknown values .we will use sub-query.
ex:--waqtd name of the employees who are earning more than SMITH.
select ename
from emp
where sal >(select sal
from emp
where ename='SMITH')
WATD name of the employees who are working in same dept as TURNER.
select dname
from dept
where deptno=(select deptno
from emp
where ename='JONES');
notes:--
--we can pass only 1 column from inner query(because
we cannot compare with multiple values)
--Tha data types on the conditions must be
exacatly same ,irrespective of column..name
===============================================
WATQD name and sal of employees earning less than jones.
-->
waqtd number of employess working for king.
--------------------------------------------------------------
waqtd name and 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='CLARK');
waqtd name and job of the employees who earns comm and getting
sal less than SCOTT
-->
select ename,job
from emp
where comm is not null and sal < (select sal from emp where ename='SCOTT');
WAqtd name and deptno of the employees who works in ACCOUNTING dept;
select ename,sal
from emp
where job='CLERK' and deptno =(select deptno from dept where loc='CHICAGO')
select ename
from emp
where job=(select job from emp where ename='SCOTT') and sal>
(select sal from emp where ename='ADAMS') and
deptno=(select deptno from emp where ename='MARTIN');
---------------
WAQTD details of dept if all the deptno has managers:
======================================
ERROR at line 3:
ORA-01427: single-row subquery returns more than one row
========================================
Types of SUB-QUERY..
1.Single Row Subquery.
2.Multi Row Subquery.
3.Nested Subquery.
4.Correalted Subquery.
ex:--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');
----------------------------------------------------------------------
**3.Nested Sub-Query:--
--When we write more than one Sub-query then it is known
as Nested Sub-Query.
--we can nest upto 255 sub-queries.
WAQTD 2nd max sal
-----------------------------------------------------------------------
4.Correalted Subquery:--
--A Correalted Subquery is a sub query which uses values from outer query.
======================
**3.Nested Sub-Query:--
--When we write more than one Sub-query then it is known
as Nested Sub-Query.
--we can nest upto 255 sub-queries.
note:--
========================================
IN :-- Equal to any member in the list.
=====================================
select *
from dept
where deptno <Any(select deptno
from emp
where job='MANAGER')
/
(select deptno
from emp
where job='MANAGER');
DEPTNO
------
20
30
10
=====
<Any (20 30 10) :-- 20 10 O/P
=========================================
>Any
select *
from dept
where deptno >Any(select deptno
from emp
where job='MANAGER')
/
=============================================================
<All
select *
from dept//10 20 30 40 < 10,20,30
where deptno <All(select deptno
from emp
where job='MANAGER')
/
======================================================================================
=====================================
Co-related SubQuery:---
--In SQL database a correalted sub-query is a subquery that uses values from the outer
query.
--Because the subquery may be evaluated once for each row processed by the outer query,it
can show as:--
}
}
=============================================================
waqtd to display 4th min sal from emp;
=============================================================
watd 11th min sal from emp;
=========
waqtd 3rd and 5th max sal from emp;
select e1.ename,e1.deptno,e1.hiredate
from emp e1
where 1>(select count(distinct e2.hiredate) from emp e2 where e1.deptno=e2.deptno and
e1.hiredate=e2.hiredate);
select *
from emp a
where 1=(select count(hiredate) from emp b where a.deptno=b.deptno and
a.hiredate<=b.hiredate)
select *
from emp a
where a.hiredate=(select min(hiredate) from emp b where a.deptno=b.deptno)
-----------------------------------------------------------
write a co-related subquery to display the employees who are getting min com`-`1ahj m in
each dept.
write a co-related subquery to display the employees who are getting min comm in each
dept and comm should be greater than 500
------------------------------------------------------------
select *
from emp a
where a.comm=(select min(comm) from emp b where a.deptno=b.deptno)
write a co-related subquery to display the employees who are getting min comm in each
dept and comm should be greater than 500
select *
from emp a
where a.comm=(select min(comm) from emp b where a.deptno=b.deptno and comm>500);
============================
Write a query to display the employees details who are earning less than their manager
sal.
Waqtd details of employess if they are getting sal greater than 2000,3000,4000.
note:
=============================
select *
from emp
where deptno in (select deptno from dept where dname in('ACCOUNTING','RESEARCH'))
=============================
waqtd to display all the details of an employees addition we need to display deptno column
again.
================================================
In-Line Sub-query:--
--If the subqueries are written in from clause then it is known as inline subquery.
synatx:--
select column_Name/*
from(Inner Query To be executed)
select *
from (select sal,comm,deptno from emp);
======================================================
Pseudo Column:--
--Pseudo Column are the columns which are present in each and every database object in
the
RDBMS but it is not visible until we explictily display these column.
Rownum::-
--Rownum is a column with sequence of numbers given to every record in the table from
1 to n int value.
--using Rownum we can display first or all the record in the table.
ex:--
Display 1st record from emp table;
select *
from emp
where rownum=1
select *
from emp
where rownum<=10;
==========================
select *
from emp
where rownum not in(3,4,5)//it returns 1 and 2nd records.
/
==========================================
Rowid:--
--Rowid is a unique random set of characters,or it is a address given for each and every
record.
--Using rowid we can display first,intermediate or all the record from the table
ex:--
SQL> select rowid
2 from emp;
ROWID
------------------
AAAMfPAAEAAAAAgAAA
AAAMfPAAEAAAAAgAAB
AAAMfPAAEAAAAAgAAC
AAAMfPAAEAAAAAgAAD
AAAMfPAAEAAAAAgAAE
AAAMfPAAEAAAAAgAAF
AAAMfPAAEAAAAAgAAG
AAAMfPAAEAAAAAgAAH
AAAMfPAAEAAAAAgAAI
AAAMfPAAEAAAAAgAAJ
AAAMfPAAEAAAAAgAAK
AAAMfPAAEAAAAAgAAL
AAAMfPAAEAAAAAgAAM
AAAMfPAAEAAAAAgAAN
=====================================================
Display the 12th record from emp table.
=====================================================
Write a inline sub-query to display top 25% sal employee records.
select *
from (select *
from emp
order by sal) where rownum <=(select round(count(*)/4) from emp)
===========================================================================
Dis-davantage Of Sub-Query:---
--The query becomes lengthy and complicated.
--in case of Sub query first inner query executes
follwed by outer query,so if we are going to write
multiple inner query the time complexity of Queries
will increase which leads in decrease in performance.
--By using Sub-Query data can be fetched from
one table at a time.
===========================================================================
Joins:--
--The retrival of data from multiple table simula.. is known as JOINS.
--Types 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
=================================
================================
note:
--In industry we are not using Cartesian join/Cross
Join becuase it returns unmatching records too.
--We Will use cross join only if there is no
relaio....b/w the tables.
======================================================================================
===============
2.Inner join:--
--This join will return only the matching records
from mutliple the table,to filter un-matching
record here we can use where clause.
--To use Inner join common column(Foregin key)
should be their.
Syntax:--
ANSI :--
select *
from table_name1 inner join table_name2 inner join table_name..n
on<Join_condition>
Oracle:--
select *
from table_name1,table_name2,table_name..n
where<Join_condition>
=========================================================
WAQTD ename,sal,dname,deptno for all the meployees.
select ename,sal,dname,deptno
from emp,dept
where emp.deptno=dept.deptno;
select ename,sal,dname,deptno
*
ERROR at line 1:
ORA-00918: column ambiguously defined
-----------------------------------------
select ename,dname,sal,e.deptno,d.deptno
from emp e,dept d
where e.deptno=d.deptno
select ename,dname,sal,dept.deptno
from emp ,dept
where emp.deptno=dept.deptno
-------------------------
=========
This column ambiguously defined can be
prevented by using 2 ways:
--->
select ename,sal,dname,e.deptno,d.deptno
from emp e,dept d
where e.deptno=d.deptno
=============================================
----------------------------------------------------
WAQTD employees name,dept name if the employee gets max
sal
-->
=======================================================
3. OUTER JOIN:--(NON-EQUI JOIN)
1.Left outer join::--
--Left outer join is used to obtain unmatch records
of left table along with matched record.
(But from right table Only matching record will
be fetched).
synatx:--
ANSI:-
select *
from table_name1 left join table_name2
on<Join_condiiton>
Oracle:--
select *
from table_name1,table_name2
where table_name1.col_name=table_name2.col_name(+);
========================
2.Right Outer Join:--
--Right outer join is used to obtain unmatch records
from Right table along with matched record.
(But from Left table Only matching record will
be fetched).
synatx:--
ANSI:-
select *
from table_name1 right join table_name2
on<Join_condiiton>
Oracle:--
select *
from table_name1,table_name2
where table_name1.col_name(+)=table_name2.col_name;
-------------------------------------------------
3.Full outer join:--
--Full outer join is used to obtain unmatching
record records from both the tables.
syntx:--
ANSI :-
select *
from table_name1 full join table_name2.....
on<JOIN_COND..>
Oracle:-- No syntax
-----------
SQL> select *
2 from student full join department
3 on student.branchid=department.branchid;
===
WAQTD only the name of student who got their guide from student table
and even display the name of all the guides
select sname,department.guide
from student right join department
on student.branchid=department.branchid
o/p:--SNAME GUIDE
--------------- -----------
DINGA PUSHPA
CHINKI NISHA
PINKI
SAHANA
REVITHA
WAQTD name of student who does not belong to any branch and display all the guide names.
=======================
CROSS JOIN:---
-->Cross Product:---Matching and unmatching record
-->Relationshi... b/w table are not required.
INNER JOIN:----
-->Matching Records
-->Relationshi... b/w tables are required.
OUTER JOIN:--
=========================
Natural Join:--
--Natural join is similar to inner join,but we wont
write any join condition.
--It automatically combines the common column,
returns inner join output
else(if there is no common column) then it
will return Cross join output.
syntax:--
Ansi:-
select *
from table_name1 natural join table_name2;
========================
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
=======================
*****inner Join::-
===========
*****Self Join::--
--Joining the same two tables is known as self join
--It is used to display the data present in same table
but different record.
syntax:--
ANSI:--
select */column_Name/ex..
from table_name1 join table_name1.......
on<Join_Condition>
Oracle:--
select */column_Name/ex..
from table_name1,table_name1.......
where<Join_Condition>
--------------------------------------------------------------------------------------
-------
WAQTD the name of employee and their manager name.
--
select e1.ename EMPNAME,e2.ename MGRNAME
from emp e1 join emp e2
on e1.mgr=e2.empno;
------------------------------------------------
WAQTD the manager name of SMITH.
---------------------
WAQTD all the details of employees who are working under manager 'KING'.
-----------------------------------------------------------
WAQTD name of the employees and their managers name if the employees are working as 'CLERK';
---------------------------------------------
WAQTD name of the employees and manager desig.. if manager works in deptno 10 or 20.
--------------------------------------------
WAQTD all the details of employees if employees who are
getting more sal than their respective manager.
---------------------------------------------
WAQTD name of the employees and manger's name if sal of employees and manager both are
earning more than 2300.
-------------------------------------------
WAQTD the employees name,mgr name,managers manager name,managers mangers manager name.
-->
===================================================
Assignment:--
1.WAQTD emp name and manager hiredate if employee hired before 1982
2.WAQD emp name and managers commisiison if employee works
as salesman and manager works in deptno 30
3.WAQTD emp name,hiredate,manager name and hiredate if manager has been hired before
employee
4.WAQTD empname and mgr name if both are working in same job.
5.WAQTD empname and mgrname along with their annual salary if the employees is working in
deptno 10,20 and mgr sal is greater than employee sal.
6.WAQTD emp name and mgr name if mgr is working as actual manager.
====================================================
7.List the emps whose mgr name is jones and also list their manager name.
8. List the emps whose sal is equal to the average of max and minimum
9. List the managers whose sal is more than his employess avg salary.
10. List the emp whose sal<his manager but more than any other manager.
11.List the employee names and his average salary department wise.
12. Find out least 5 earners of the company.
13. List the Enames who are retiring after 31-Dec-89 the max Job period is 20Y.
14. List those Emps whose Salary is odd value.
15. List the emps whose first 2 chars from Hiredate=last 2 characters of Salary.
16. List first 50% of chars of Ename in Lower Case and remaining are upper Case.
17. List the Dname whose No. of Emps is =to number of chars in the Dname.
18. List THE Name of dept where highest no.of emps are working.
19. List the name of the dept where more than average no. of emps are working.
20. List the Managers name who is having max no.of emps working under him.
21. List the emps whose Mgr name is 慗 ones?and also with his Manager name.
22. Find out how may Managers are their in the company.
23. Check whether all the emps numbers are indeed unique.
24. Find out the emps who joined in the company before their Managers.
25. List all the emps by name and number along with their Manager 抯 name and number. Also
List KING who has no 慚 anager?
26. List the employee name,Salary and Deptno for each employee who earns a salary greater
than the average for their department order by Deptno.
27. List the Deptno where there are no emps.
28. List the Name, Job and Salary of the emps who are not belonging to the department 10
but who have the same job and Salary as the emps of dept 10.
29. List the Deptno, Name, Job, Salary and Sal+Comm of the SALESMAN who are earning maximum
salary and commission in descending order.
30. List the Deptno and their average salaries for dept with the average salary less than
the averages for all department
31. List out the Name, Job, Salary of the emps in the department with the highest average
salary.
32. List the empno,ename,annsal,dailysal of all the salesmen in the asc ann sal
33. List the emps whose exp is more than 10 years.
34. List the emp who are clerks who have exp more than 8ys.
35. List the emps along with exp of those working under the mgr whose number is starting
with 7 but should not have a 9 joined before 1983.
36. List the emps who are working for dept 10 or 20 with desgs as clerk or analyst with
a sal is either 3 or 4 digits with an exp>8ys but does not belong to mons of mar,apr,sep
and working for mgrs &no is not ending with 88 and 56.
37. List the emps who are belonging dallas or Chicago with the grade same as adams or exp
more than smith.
38. List the details of most recently hired emp of dept 30.
39. List the highest paid emp working under king.
40. List the emps Whose 10% of Salary is equal to year of joining.
======================================================================================
===========
DDL:--(Data Definition Language)--
-This Query Lanaguage is used to define the properties of table.
-The stmt of DDL are:--
1.create
2.rename
3.alter
4.Truncate
5.drop
-----------------------
1.create :--This stmt is used to create a table in DATABASE.
syntax:--
create table table_name
(Column_name-1 data_type not null/null,
Column_name-2 data_type not null/null,
..
..
..
Column_name-n data_type not null/null,
Constraints constraints_ref_name primary key(Column_name),
Constraints constraints_ref_name foregin key(Column_name),
Constraints constraints_ref_name check(condition),
Constraints constraints_ref_name unique(Column_name),
References parent_table_name(Column_name)
);
------------------------------------------------
create table STUDENT
(
USN varchar(15) not null,
NAME varchar(10) not null,
MARKS number(6,3) not null,
PHONENUM number(10) not null,
EMAIL varchar(20) null,
constraints u_sn primary key(USN),
constraints p_hn check(length(PHONENUM)=10)
);
---------------------
select *
from STUDENT
note:will get no row selected becuase there is no record prsent in the table.
=============================================================================
Query to clone the data and column name of already created table.
syntax:--
create table new_TableName as(select * from table_name);
-------------------------------------------
2.Rename:--
--This Stmt is used to change the name of table.
syntax:--
rename current_table_name to new_table_name;
-------------------------------------------
3.Alter:--
----
a. To add A column in exis..table:--
syntax:-- alter table table_name
add column_name data_type[not null/null];
ex:--
alter table student
add BRANCHNAME varchar(10) not null;
--------------
b.To drop/remove a column from exis..table:--
syntax:--
alter table table_name
drop column column_name;
ex:--
alter table student
drop column BRANCHNAME;
----------------
c.To change the data type:--
syntax:-
alter table table_name
modify column_name new_data;
ex:--
alter table student
modify EMAIL number(10);
-----------------
d.To change the name of column:--
syntax:--
alter table table_name
rename column current_Column_name to new_column_name
ex:--
alter table student
rename column NAME to SNAME;
-----------------
e.To ADD the constraints:--
syntax:--
----------------
4.Turncate:--
--It is used to delete all the records without affecting the table structure.
syntax: -
truncate table table_name;
5.Drop:--
--This stmt is used to delete all records and even table structure from database.
synatx:--
drop table table_name;
Note:--The table deleted from database wont be deleted perman...,it will be present in
recycle bin
of Data Base.
syntax:--
Flashback table table_name
to before drop;
1.insert:--
--This stmt is used to insert the record in the table.
syntax 1:--
--This syntax is used whenever we have to insert miniu.. number of record in table.
(Because remeb.. the colu_name and data types is little difficult)..
=====================
syntax 2:--
Rules:-
1.Both the table should have same number of column.
2.Both the columns table should have same data type;
syntax:--
ex:--
insert into DUPSTUDENT
select * from student;
-->
insert into DUPSTUDENT
select * from student
where usn='1st';
=====================================================
2.Update:--
sntax:--
update table_name
set colu_name1=v1,colu_name2=v2.......
where <filter-condition>;
ex:--
update student
set PHONENUM=8877599869
where usn='1st13ec123';
=====================================================
3.Delete stmt:--
--This stmt is used to delete the specific record from the table.
syntax:--
delete
from table_name
where<Filter-Condition>
ex:--
delete from student
where name='RAM';
====================================
TCL:--
--TCL commands is used to manage the tran... in the database.
--These are used to manage the changes made to the data in table by DML stmts.
1.Commit.
2.rollback.
3.savepoint.
1.Commit:--
--This stmt is used to save the changeg perman...done by DML commands.
--Commit stmt..will always be enabled in DBMS.
syntax:-commit;
ex:--
3.rollback:--
--this stmt is used to undo the operation which has been saved in database.
syntax:--roolback to savepoint_name;
---------------------------------------------------------------------------------
ex:--SQL> savepoint a;
Savepoint created.
SQL> rollback to a;
Rollback complete.
Grant:--
--It is used to give permission to other user to access the table created by them.
syntax:--
grant sql_stmt(select/insert...)
on table_name
to user_name;
Revoke:--
--It is used to get back the permission from another user.
syntax:--
revoke sql_stmt(select/insert...)
on table_name
to user_name;
===================================================================
ex:--
----------------------
GRANT:--
user:--scott
grant select
on emp
to hr
Grant succeeded.
user:---HR
select *
from scott.emp
----------------------------------
Revoke:--
SQL> show user;
USER is "HR"
SQL> connect scott
Enter password: *****
Connected.
SQL> show user;
USER is "SCOTT"
SQL> revoke select
2 on emp
3 from hr;
----Revoke succeeded.
------------------------------------
SQL> connect hr;
Enter password: *****
Connected.
SQL> show user;
USER is "HR"
SQL> select *
2 from scott.emp;
from scott.emp
*
ERROR at line 2:
ORA-01031: insufficient privileges
--------------------------------------------------------------------------------------
----------------------------------------
Set oprators in SQL:--
--SQl supports few set operators,which is used to get the meaningful result from table.
--4 types of SET operator:--
1.Union.
2.Union All.
3.Intersect
4.Minus.
1.Union:--
-->Union is used to combine the result of two or more select stmt.However it will eleminate
duplicate rows
in result table.
ex:--
A ={1,2,3,4,5};
B ={4,5,6,7};
A U B :--{1,2,3,4,5,6,7};
2.Union All:--
--This operator is same as UNION ,but it also inculeds the duplicate rows.
3.Intersect:--
--Intersect operator is used to combine two select stmt,but it only returns the record
which are common for both select stmt.
4.Minus:--
--The minus opertor cobines result of two select stmt and returns only the non-duplicate
record from 1st select stmt.
note:--->In case of set operators no of columns and data types must be same for both tables.
----------------------------------------------------------------
ex:--
union:--
select * from emp
union
select * from emp2;
Union All:-
select * from emp
union all
select * from emp2;
Intersect:-
select * from emp
intersect
select * from emp2;
Minus:--
select * from emp2
minus
select * from emp;
======================================================================================
==================
Attributes:--
-->It will define the characte...of DB or attribute refers to database component.
1.Key Attribute/Candidate key
2.Non-Key Attribute.
3.Prime Key Attribute.
4.Non-Prime Key Attribute.
5.Composite key Attribute.
6.Super key Attribute.
7.Foreign key Attribute.
=============================================
1.Key Attribute:--
--It is an Attribute using which we can identify a record Uniquely from the table.
It is also known as Candidate key.
ex:--PhoneNumber,AadharCard,voterId etc..
2.Non-Key Attribute:--
--All the other Attribute except key Attribute is known as Non-Key Attribute.
ex:--Name,DOB,Gender,Religion etc...
ex:--Phone number
-The left side FD is known as determinant(it helps user of fetch the unique record)
,right side of arrow mark we can say as Dependent.
---------------------------------------------------------------------
Types of Functional Depedencies are:--
1.Total Functional Depedency
2.Partial Functional Depedency
3.Transitive Functional Depedency.
-----------------
1.Total Functional Depedency:--
--If all the attributes of a relation are determined by single key attribute then it
is known as Total Functional Depedency
ex:--Let us consider ,a relation with the 4 attributes A,B,C,D in which A is key attribute.
R ->{A,B,C,D}
where A is Key attribute.
A -->B
A -->C
A -->D
i.e:::: A -->{B,C,D};
R :--- {(A,B),C,D}
(A,B) ----> D
B ----> C
A ---->(C,D).
Name Marks
Ram 68.36
Ram 89.36
Sohan 32.36
-----------------------------------------------------------
3.Transitive Functional Depedency:--
--There exists a depedency that an attribute is determined by a non-key attributes
which is determined by a key attribute,this type of depedency is known as Transitive
Functional. Depedency
R3 = {(A),B,C,D}
A -> B
D -> C
A -> D
--------------------------------------------------------------------------------------
------------
Redundency:--
--Repeatation of unwanted data.
=============================
Normalization:--
--Normalization is the process of reducing the table into smaller table in order to remove
the
Redundency and anamolies by identifying the depedncies.
--Decomposing a lager table into its normal form is known as Normalization.
Normal Form:--
--A table without redundencies and anamolies is knwon as Normal Form.
--Levels of Normal Forms are:--
**1.The table should consits of single value data in a single cell(i.e one particular cell
should have 1 value only).
2.A table should not have any duplicate value.
======================================================================================
=======================
2. 2NF
3. 3NF
--the table should be in 2NF
--there should be any transitive Depe.....
transitive Depe...::--