SQL Notes
SQL Notes
Information:---
-->Collection of data becomes information.
====================================
Notes::--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::---
--Hiearchical 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.
===============================================================
DML:--Data MAnipulation Language:--
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.
1.char
2.varchar/varchar2
3.date
4.number
5.LOB(Large Object)
====================================================================
1.char:--
char datatype is used to store character such as :--
A-Z,a-z,0-9,and special character(@,#,*,%,$...)
====================================================================
2.varchar:--
--varchar datatype is used to store character such as :--
A-Z,a-z,0-9,and special character(@,#,*,%,$...)
--For char data type we can pass an arg as Size.
--Tha maximum size in char datatypes is 4000
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.
===========================================================================
Projection::--
---the retrival of data by selecting only column name is known as Projection.
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;
===================================
Assignm::---
1.WATD name and half term sal for all the employees.
2.Watd name,deptno,sal with hike of rs100 for all employees
3.watd name and annual sal with bnous of rs2000
4.watd name,deptno,empno and sal with deduction of 10%
5.Watd name,desgination of all employees along with deduction of 30% in aunnual sal.
==============================================================
Distinct:--
--Distinct clause is used to remove duplicate records present in the result table,
which reults in unique record in result table.
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:--
note:-- sql is a case insensitive.. language(i.e function,table,column) but data present in table is
case sensitive.
===================================================================================
==============================================================================
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:--
===================================================================
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
12345678
JSPIDERS
-8 -7..........-1
-ve <-------------------
ex:---
JSPIDERS
SPI
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.
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')
note:--if we missed leading/trailing/both then char will be trimmed from both the end.
=================================================================
SYSDATE:--this command is used to obtain the current date of the system in which RDBMS is installed.
ex:-- select sysdate
from dual;
SYSTIMESTAMP:--this command is used to obtain the date,time,and the time zone of the system.
ex:-- select systimestamp
from dual;
Date SRF:--
1.ADD_MONTHS();
2.MONTHS_BETWEEN();
3.EXTRACT()
4.LAST_DAY()
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 your age.
select round(months_between(sysdate,'02-NOV-1996')/12)
from dual;
==================================
WAQ to fetch expre....of all employess in years from emp date.
select round(months_between(sysdate,hiredate)/12)
from emp
===========================================================
extract():--
--This function is used to extract the day,the month or the year from the given date in number/int formate
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
===========================================
===================================================================
last_day():--
--This function is used to obtain the last day of the given month
in the gievn date.
syntax:--
last_day('date')
===================================================================================
========
General SRF:--
1.nvl()
2.nvl2()
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:---
1.Ascii()
2.to_date()
3.to_char()
syn:-- ascii('Char')
ex:-- ascii('A'):--65
ascii('ABC'):--65-->here date of 1st char will be returned.
syntax:--to_date('date');
3.to_char():--This function is used to convert the given date to String format
and it is used to formate the date model a/c user choice
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 i sused 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....fro which we can pass * or column name or exp as an arg..
synx:--count(*/column_name/exp).
note:--for sum() and avg() function we can pass only those column which contains number data type.
===========================================================================
notes:-
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.
*** 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.
------------------------error....>>>>>>>>
select ename,max(sal)
from emp
where job='CLERK';
waqtd max(sal),min(sal) and total sal needed to pay fro all employees.
ex:--
select max(sal),min(sal),sum(sal) as "TOTAL SAL NEED TO PAY"
from emp;
===========================================
w
-->
select count(*)
from emp
where mgr=7839;
waqtd avg sal,total sal,number of employees and maximum sal given to employees working as president
-->
select avg(sal),sum(sal),count(*),max(sal)
from emp
where job='PRESIDENT';
WAQTD no of emp.. and total sal needed to pay for the employees who have 2 consecutive L in their name.
-->
select count(*),sum(sal)
from emp
where ename like '%LL%';
=============================================================
Group by Clause:---
syntax:---
select group-by-expression/Group by function
from table_name
[where <Filter-Condition>]
group by col_name/expression
order by col_name/expression;
Order of execution:---
1.from clause
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....
=============================================================
WAQTD no of employees working in each dep..except president.
select count(*),deptno
from emp
where job != 'PRESIDENT'
group by deptno;
WAQTD total salary needed to pay to all the employees in each dept.
Select sum(sal),deptno
From emp
Group by deptno;
=======================================================================
Having clause:--
==============
syntax:--
select group-by-expression/Group by function
from table_name
[where <Filter-Condition>]
group by col_name/expression
having <group-Filter-Condition]
order by colm_name/expression.
syntax:--
1.From clause
2.where clause :---Row by Row
3.group by clause :---Row by Row
4.having clause :--Group by Group
5.Select clause:--Group by Group
6.order clause:--Group by Group.
============================================================================
waqtd atleast 4 employees working in each dept except president.
waqtd the hiredate which appears more than once in employee table.
--> select hiredate,count(*)
from emp
group by hiredate
having count(*)>1;
===========================================================
***SUB-QUERY:--
--An query written inside another query is known as 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')
note:--in the above query sal of SMITH was unknown .Therfore ,we wrote a subquery to find the unknown sal.
WATD name of the employees who are working in same dept as TURNER.
=========================================================
case 2:-- whenever the data to be fetched/selected and the
condition to be executed belongs to two different table,then we need to go for sub-query.
Constraints:--
--Constraints are the rules provoded to a column to validate a data during insertion or update
--Constraints in sql are:---
1.Not Null Constraint
2.Unique Constraint.
3.check() Constraint
4.Primary Key Constraint
5.Foreign key Constraint
1.Not null Constraint:--
--Not null Constraint is used to restrict null values into a cloumn,in other words if a cloumn is defined as not null the
n
it should not accept null value.
--Which Column should be decl..as not null.
--->The attributes or columns which is supposed to be manadatory for each and every enitiy
then such column should be decla... as not null.
ex:--name,usn,gender etc............
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 Constrain
t
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.
5.Foregin key:---
--It is used to build a relationship between the tables.
--in a table we can have any no of foregin key..
======================================================
select dname
from dept
where deptno=(select deptno
from emp
where ename='JONES');
===============================================
waqtd dept name of adams.
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..
==========================================
WATQD name and sal of employees earning less tahn jones.
-->
select ename,sal from emp
where sal<(select sal
from emp where ename='JONES');
waqtd all the details of th employess working in the same dept..as JAMES
select *
from emp
where deptno=(select deptno
from emp
where ename='JAMES');
==============================
waqtd number of employess working for king.
select count(*)
from emp where mgr=( select empno
from emp
where ename='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<(sel
ect sal from emp where ename='CLARK');
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 SMITHS dept.
--
SELECT * FROM EMP WHERE SAL<(SELECT SAL FROM EMP WHERE ENAME='KING')
AND DEPTNO IN (SELECT DEPTNO FROM EMP WHERE ENAME='SMITH');
(WIPRO)
****Watd name of employees working in same job as SCOTT ,getting sal more than ADAMS and working in dept i
n which MARTIN works.
======================================
note:---
WAQTD details of dept if all the deptno has managers:
select *
from dept
where deptno =(select deptno
from emp
where job='MANAGER');
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.
4.Correalted Subquery:--
--A Correalted Subquery is a sub query which uses values from outer query.
======================
3.Nested Sub-Query:-
========================================
IN :-- Equal to any member in the list.
=====================================
note:--
(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 *
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 comm in each dept.
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.
-There are 2 types of Pseudo Column present in every DB
1.Rownum.
2.Rowid.
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.
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:--
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.
/
==========================================
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-advantage 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 fetch the data 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
=================================
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 table1,table2.....table-n)
--In this type of joins we will get matching records as well as un-matching record.
--To apply Cartesian join/Cross Join relation(foregin key) b/w 2 tables are not mandatory.
syntax:--
select *
from table_name1 cross join table_name2 cross join.....table_name..n;
Oracle:-
select *
from table_name1,table_name2,.....table_name..n
================================
note:
--In industry we are not using Cartesian join/Cross Join becuase it returns unmatching records too.
--We Will use cross join whenever there is not 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
=========
This column ambiguously defined can be prevented by using 2 ways:
1.By providing table alisa.. name
--->
select ename,sal,dname,e.deptno,d.deptno
from emp e,dept d
where e.deptno=d.deptno
2.by using table_name.column_name for the column which ever is common b/w the tables.
--->
select ename,sal,dname,emp.deptno
from emp inner join dept
on emp.deptno=dept.deptno
=============================================
WAQTD employee name and his dept name for all the employees.
select ename,dname
from emp,dept
where emp.deptno=dept.deptno
==========================================================
WAQTD name of the employees along with his location for all the employes.
select ename,loc
from emp inner join dept
on emp.deptno=dept.deptno;
WAQTD name of employees and his deptname if the employees works as SALESMAN.
select ename,dname
from emp,dept
where emp.deptno=dept.deptno and job='SALESMAN';
select ename,dname
from emp inner join dept
on emp.deptno=dept.deptno
where job='SALESMAN'
WAQTD dname and annual sal for employees who earns more than 2450.
WAQTD dname,hiredate of all the employees who were hired during 81.
select dname,hiredate
from emp inner join dept
on emp.deptno=dept.deptno
where hiredate like '%81%';
=========================================================
WAQTD name and dname for the employees if name of employees job and dname starts with the same character 'S'.
========================================================
=====================
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.
(If not matching reocrd found then complier will assign null value)
syntx:--
ANSI :-
select *
from table_name1 full join table_name2.....
on<JOIN_COND..>
-----------
SQL> select *
2 from student full join department
3 on student.branchid=department.branchid;
=======================
SQL> select *
2 from student;
===
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;
ex:--select *
from emp natural join dept;
========================
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.
=======================
*****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.
--
select e1.ename EMPNAME,e2.ename MGRNAME
from emp e1 join emp e2
on e1.mgr=e2.empno;
--
-------------------------------------------
WAQTD the employees name,mgr name,managers manager name
select e1.ename EMPNAME,e2.ename MGRNAME,e3.ename MANAGERSNAME
from emp e1,emp e2,emp e3
where e1.mgr=e2.empno and
e2.mgr=e3.empno;
WAQTD the employees name,mgr name,managers manager name,managers mangers manager name.
-->
select e1.ename EMPNAME,e2.ename MGRNAME,e3.ename MANAGERSNAME,e4.ename MANAGERSSSSSS
SSSSSSSSSS
from emp e1,emp e2,emp e3,emp e4
where e1.mgr=e2.empno and
e2.mgr=e3.empno and
e3.mgr=e4.empno;
===================================================================================
==============
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;
--------------
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 name char(20);
-----------------
d.To change the name of column:--
syntax:--
alter table table_name
rename column current_Column_name to new_column_name
ex:--
alter table sqlstudent
rename column NAME to SNAME;
-----------------
e.To ADD the constraints:--
syntax:--
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:--
insert into table_name values(v1,v2,v3.....vn);
=====================
syntax 2:--
insert into table_name (column_name1,column_name2....column_name.n)
values(v1,v2,v3.....vn);
===================
syntax 3:--
--This syntax is used to copy the records from one table to another table;
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 sqlstudents
set CONTACTNUMBER=9999999999
where usn=12;
=====================================================
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';
Note:--
====================================
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 changes perman...done by DML commands.
--Commit stmt..will always be enabled in DBMS.
syntax:-commit;
ex:--
-----------------
2.savepoint:--
--This stmt is used to mark the transaction.
syntax:-- savepoint savepoint_name;
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.
1 row 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
from 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 includes the duplicate rows.
3.Intersect:--
4.Minus:--
--The minus opertor cobines result of two select stmt and returns only
the non-duplicate record from 1st select stmt.
----------------------------------------------------------------
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
---------------------------------------------------------------------
Types of Functional Depedencies are:--
1.Total Functional Depedency
2.Partial Functional Depedency
3.Tansitive Functional Depedency.
------------------>
===========================================
ex:--
800
1600
1250
2975
2850
2450
3000
5000
1500
1100
950
1300
-
============================================================================