0% found this document useful (0 votes)
8 views88 pages

SQL Notes

Uploaded by

f6khvmjkm7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views88 pages

SQL Notes

Uploaded by

f6khvmjkm7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 88

Data::-----

--->The Raw Facts which describes the attribute(pr) of an Enitity(Object)


or a transcation is known as Data.
------>Data can be valid or inValid..
--->A data can be valid or invalid based on situation/Sceniro

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.

Table:--Table is a logical Structure which contains column,row and cell

column:-- A column represents an attribute of an entity.


column is also know as Field or Attribute

Row:-- A row represnts all the attributes of one entity.


Row is also known as tuple or record.

Cell:--cell is the smallest unit of table ,which represnts data.

or Cell is a building block of table.


==============================================================
Types of Stmt/Query Language:---
1.DDL
2.DML
3.TCL
4.DCL
5.DQL
===============================================================
DDL:--Data Definition Language---
create,rename,alter,truncate,drop

create:-- It is used to create a table in data Base.


rename:-Rename is used to change the table/object name in DataBase.
alter:--it is used to modify(Adding col,delete colm...) the definition of a table
Truncate:--Truncate is used to delete all/entire the rows present in a table but
table structure remains same.
drop:--drop is used to delete all the rows and even table structure will be deleted.

===============================================================
DML:--Data MAnipulation Language:--

insert,update,delete..

insert::--it is used to insert a data into the table.


update::--update stmt is used to modify the data present in the table
delete::--delete is used to eraise/data of specified row.

========
**** 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.

select :--reterieve the data from table.


=============================================================================
Data Type:--
Data type is the one which will specifiy what type
of value column is goining to store.

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(@,#,*,%,$...)

For char data type we can pass an arg as Size.


Tha maximum size of char datatype is 2000
syntax:--
char(size)
where size specifies the max. no of characters that can be stored.
ex:--
char(10)......10 blocks will be allocated
Dis-advanatge:--
- In char data types there will be fixed length memory
allocation.

ex:--Let us assume we are going to store "SMITH",only 5 blocks


of memory will be used
remaining 5 blocks are not used.these unused memory is
known as Memory Leakage.

====================================================================
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

scale:--it represnts the no of numeric/digit values to stored after decimal point

ex:-- number(5):--we can store upto 5 int value.(12345)


356.36855 number(8,5)::--we can store upto 3 int and 5 decimal value
0.2589 number(4,4):: it will store only dec..value
number(3,5)--wrong
number(5,0)--5 int value.
number(5,5) :--double value
can scale value be greater than precision??-
--Always precision >= scale
--But scale cannot be greater than precision.
===========================================================================
null:--
--in sql null is a keyword which is which represnts an empty cell
--when an entitiy does not have any value,it will be represnted by null.

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;

4.Any operation perfome don null results in null value.


5+null==>null
5*null==>null...........etc...
============================================================================
DQL(Data Query Language):---

1.select:---The retrival of data from the table in the database is done using select stmt.

2.Projection:--the retrival of data by selecting only column name is known as Projection

3.Selection::-the retrival of data by selecting either column or by selecting row


is known as Selection.

4.join::-- the retrival of data by selecting mutiple tables is known as join.

===========================================================================
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

--varchar is an external data type and varchar2 is an internal data type.

Query:--
1.WATD deatils of all employe.
--->>select * from emp;
2.WATD name,sal,deptno of employe.
-->>select ename,sal,deptno from emp;
-------------------------------------------------------------------------
Expression::---

--Anything which yields(Gives) a result is known as Expression.


--An Expression consists of :--
1.operand:-the resources/variable on which any opertions can be performed.
2.operators:-it is used to perform some operation(+,-,*...........)
--In sql operand are of 2 types:--
1.colun_Name(sal,ename........)
2.Direct value/Immediate value.

====================
1.WATD Annual Sal of all employe..
---->
select sal*12
from emp;

2.WATQD employe sal with hike of 10%..


>--
select sal+(sal*10/100)
from emp;
=================================
ALIAS:--
--It is an alternate name give to a column in result table.
--ALIASING can be done in 2 ways:--
1.By using AS operator.
---
syntax:-- select old_ColmNAme as New_ColName
from tableName;

2.Without using AS operator.

syntax:-- select old_ColmNAme New_ColName


from tableName;
=========================

===================================
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;

WAQTD unique deptno,job from employe table.

--->select distinct job,deptno 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:--

--where clause is used to filter the records.


--It executes row-by-row
--For where clause we can pass filter condition as an argum...
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.

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:--

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

Not:it will give just compliment


0----1
1----0
=====================================================================

===================================================================
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);

ex:-- WAQTD all the managers either working in dept 10 or 20 or 30.

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

Ans:-we need to make use Escape character.

==========================================================================
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)

1.Single Row Function.(SRF):::--


--SRF takes 1 input,processes and generates o/p for single i/p.
--If we pass n-no of i/p to a single row function then we will get n-no of o/p.
--Types of SRF are:--
1.Number SRF/Math SRF
2.Character SRF
3.Date SRF
4.conversion SRF
5.General SRF.

2.Multi Row Function.(MRF):::---


--MRF will aggregate or combines all the input at once,processes it and generates a Single output.
--If we pass n-no of i/p to MRF then we will get single o/p.
--Types of MRF are:--
1.max()
2.min()
3.sum()
4.avg()
5.count()
==================================================================================
Note:-Dual is a dummy table,which is used to output the result.

1.Number SRF/Math SRF:--


--It is used to perform Math.......operation
--Types:--
1.mod()
2.power()
3.abs()
4.sqrt()
5.round()
6.trunc()
============================================
1.mod():--This function is used to obtain the remainder(modules)
--It can accept 2 argu...
synax:-- mod(m,n)
m=divident
n=divisor.

ex:-- select mod(10,3)


from dual;
o/p:--1
================================
2.power():--Power function is used to obtain exponential value for a given number.
--It can accept 2 arg::
syntax:--power(x,n)
x=is the base
n=power
ex:--- select power(2,4)
from dual;
o/p:-16
=============================
3.abs():--It is used to obtain magnitude of the given number.
--it will take only one arg.

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.
==========================================

select round(66.967888,-1) from dual;

===========================================

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;

WAQTD details of employee who getting sal in 4digit.

select *
from emp
where length(sal)=4;
=======================================
2.reverse():--Used to reverse the given String..

Syntax:--reverse('String')

ex:--reverse('MADAM')

reverse('RAM'):---MAR

..WAQ to reverse the character present in the name of each employee.

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';

3.WATD name of employee whose name starts by vowel.

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

-------->>>
substr(ename,round(lenght(ename)/2),1)

4.WAQTD 2nd half of all the employee name.


--->
select substr(ename,(round(length(ename)/2)+1))
from emp.
5.WAQTD name of employee from 2nd char to last but one char.

SMITH
5-3==3

6-2=4...............................

MIT

select substr(ename,round(length(ename)-2))
from emp.

6.
QSPIDERS:----qspiDers

o/p:--select lower(substr('JSPIDERS', 1, 4))||initcap(substr('JSPIDERS', 5, 8)) from dual

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.

-This function can accept 4 arg:--


syn:--
instr('Original String','SUBSTR',position to start checking,[n th occurence])
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')

WAT replace A with @ in ename column of emp table.

WAT replace A with @ and S with # in ename column of emp table.

replace('DINGA', 'D') how INGA


INGA

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')

leading:--then char will be removed from begining


trailing:--then char will be removed from end
both:--then char will be removed from begining as well as from end

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():--

--This function is used to add the no of months to a given date.

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

syntax:--- extract(day/month/year from Given_Date)

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()

1.nvl():--Null value logic

-NVL function is used to overcome the drawbacks of opertions perfomed on null.


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:---

1.Ascii()
2.to_date()
3.to_char()

1.Ascii():--It returns ascii value of specified character.

syn:-- ascii('Char')

ex:-- ascii('A'):--65
ascii('ABC'):--65-->here date of 1st char will be returned.

2.to_date():--this function is used to convert the date String


to date format.

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 no of employees earning comm in deptno 20


-->
select count(*)
from emp
where deptno=20 and comm is not null;

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:---

--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.

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;

WAQTD no of employees working as manager in each dept..


select count(*),deptno
from emp
where job='MANAGER'
group by deptno;

=======================================================================
Having clause:--

--Having clause is used to filter the groups.


--This means having clause executes group by group.
--Since having clause executes after the group by clause we can write MRF in it as a condition.
--In having clause we can passs the expression used in group by clause.
--Multiple condit.. can be passed in 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;

waqtd the salries which are repeated or duplicate.


--> select count(*),sal
from emp
group by sal
having count(*)>1

===========================================================
***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')

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.

select ename from emp


where deptno =(
select deptno
from emp where ename='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..
======================================================

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.

ex:--Waqtd the dept name of jones.

select dname
from dept
where deptno=(select deptno
from emp
where ename='JONES');

===============================================
waqtd dept name of adams.

waqtd loc in which SMITH works.

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');

----->WAQTD details of dept if all the deptno has managers:

(WIPRO)
****Watd name of employees working in same job as SCOTT ,getting sal more than ADAMS and working in dept 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.

1.Single Row Subquery:--


--If the subquery returns exactly 1 record then it is knwon as Single Row Subquery.
--If it returns 1 record,we can use normal operators i.e: = ,!=,>=,<= etc..

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');

2.Multi Row Subquery:--


--If the subquery returns more than 1 record then it is known as Multi Row Subquery.
--In case of Multi Row Subquery we can not use noraml operators.
--So need to use Operators Such as in,All,Any..etc.

**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:-

--WAQTD 2 min sal from emp;


>>--
select min(sal)
from emp
where sal>(select min(sal)
from emp);
--Waqtd 5 max sal from emp;
=====================
2.Multi Row Subquery:--
WAQTD details of dept if all the deptno has managers.
---
select *
from dept
where deptno in(select deptno
from emp
where job='MANAGER')
Get employee details working under either accounting or research.
ex:--
select *
from emp
where deptno in(select deptno
from dept
where dname in('ACCOUNTING','RESEARCH'))
Get sal,ename details of employees working under either in CHICAGO or BOSTON
--------->>>
list the emps whose job same as SMITH or ALLEN.
select job
from emp
where ename in('SMITH','ALLEN');

ANY and ALL operator::---------------------


--These operator are used in where or having clause.
--The ANY Operator returns true if any of the sub-Query
values meet the condition.
--The ALL opertaors returns true if all of the subquery
values meet the condition.
ANY Syntax:--
select column_name
from table_name
where column_name operator ANY
(select column_name from table_name where condition).
ALL Syntax:--
select column_name
from table_name
where column_name operator ALL
(select column_name from table_name where condition).

note:--operator must be used here are all the comparision


opertor i.e =,<=,>=,!=.....

========================================
IN :-- Equal to any member in the list.

ANY :--Compare(=,<=,>=) value to each value in the list.

ALL:--Compare(=,<=,>=) value to every value in the list.

=====================================
note:--

<ANY :--Less than Maximum.


>ANY :--Greater than Minumum

=ANY :--Equivalent to IN operator

>ALL :--Greater than Maximum value

<All :--Lesser Than Minumum.


====================================
select *
from dept
where deptno <Any(select deptno
from emp
where job='MANAGER')
/

DEPTNO DNAME LOC


------ -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS

(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')
/

DEPTNO DNAME LOC


------ -------------- -------------
40 OPERATIONS BOSTON
30 SALES CHICAGO
20 RESEARCH DALLAS
=============================================================
select *
from dept
where deptno >All(select deptno
from emp
where job='MANAGER')
/

DEPTNO DNAME LOC


------ -------------- -------------
40 OPERATIONS BOSTON

=============================================================
<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:--

i.e :--for(int i=1;i<=10;i++)//t


{
for(int j=1;j<=10;j++)
{

}
}

=============================================================
waqtd to display 4th min sal from emp;

select * from emp a


where 4 =(select count(distinct b.sal) from emp b where(a.sal>=b.sal));

=============================================================
watd 11th min sal from emp;

select * from emp a


where 11=(select count(distinct b.sal) from emp b where(a.sal>=b.sal));

=========
waqtd 3rd and 5th max sal from emp;

select * from emp a


where (select count(distinct b.sal) from emp b where(a.sal<=b.sal)) in (3,5);
===================================================================================
==
Write a co-realted query to display 1st employee(Who has been hired 1st) from each dept.

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.

select * from emp a


where a.sal<(select b.sal from emp b where a.mgr=b.empno);

=========================

Waqtd details of employess if they are getting sal greater than 2000,3000,4000.

note:

Or logical === Any special Operator

And Logical == All special Operator.

=============================

<ANY :--Less than Maximum.


>ANY :--Greater than Minumum

=ANY :--Equivalent to IN operator

>ALL :--Greater than Maximum value

<All :--Lesser Than Minumum.

Get employee details working under either accounting or research.

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

Display the first 10 reecord from emp.

select *
from emp
where rownum<=10;
==========================
select *
from emp
where rownum not in(3,4,5)//it returns 1 and 2nd records.
/

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


----- ---------- --------- ---------- --------- ---------- ---------- ----------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30

==========================================

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)

Write a inline sub-query to display least 25% sal employee records.


select *
from (select *
from emp
order by sal) where rownum <=(select round(count(*)/4) from emp);

****display middle 50% sal employees record.

===========================================================================
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:--

ANSI::(American National standards institute):--

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.

select dname,sal*12 "annual salary" from emp inner join dept


on emp.deptno=dept.deptno
where sal>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'.

select dname,ename from emp,dept


where emp.deptno=dept.deptno and job like 'S%'
and dname
like 'S%';

========================================================

=====================
WAQTD employees name,dept name if the employee gets max sal

--> select ename,dname


from emp inner join dept
on emp.deptno=dept.deptno
where sal =(select max(sal)
from emp)

WAQTD name,dname of SMITHS manager.


--> select ename,dname
from emp inner join dept
on emp.deptno=dept.deptno
where empno=(select mgr
from emp
where ename='SMITH')

=======================================================
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..>

Oracle:-- Not syntax

-----------
SQL> select *
2 from student full join department
3 on student.branchid=department.branchid;

BRANCHID SNAME GUIDE BRANC BRANCHID GUIDE


---------- --------------- --------------- ----- ---------- ---------------
10 DINGA PUSPHA CSE 10 PUSHPA
40 CHINKI NISHA MEC 40 NISHA
30 DINGI
90 MINKI
ECE 20 REVITHA
EEE 50 PINKI
CIVIL 60 SAHANA
===============================================================================

=======================
SQL> select *
2 from student;

BRANCHID SNAME GUIDE


---------- --------------- ---------------
10 DINGA PUSPHA
30 DINGI
40 CHINKI NISHA
90 MINKI
=======
1 select *
2* from department
SQL> /
BRANC BRANCHID GUIDE
----- ---------- ---------------
ECE 20 REVITHA
CSE 10 PUSHPA
MEC 40 NISHA
EEE 50 PINKI
CIVIL 60 SAHANA

===
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:--

-->Relationshi... b/w tables are required.

LOJ :-- left table: Matching and Unmatching record


Right Table:Matching Records

ROJ:-- left table: Matching


Right Table:Matching Record and Unmatching records

FOJ:--- it will return unmatching record from both the table.

=========================
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;

Oracle:-- there is not oracle sntax for Natural join.

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;
--------------

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 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:--

alter table table_name


add constraints cont_ref_name constraint_name(Column_name);
ex:--
alter table sqlstudents
add constraint s_name check(length(NAME)=15);

f.TO drop/enable/disable the constraints:--

syntax:--

alter table table_name


drop/enable/disable constraint const_ref;

----------------
4.Turncate:--
--It is used to delete all the records without affecting the table structure.

syntax: -
truncate table table_name;

ex:--truncate table dinga;

5.Drop:--
--This stmt is used to delete all records and even table structure from database.
synatx:--
drop table table_name;

ex:--drop table dingi;

Note:--The table deleted from database wont be deleted perman...,it will be present in recycle bin
of Data Base.

a.To recover the table From recycle Bin:--

syntax:--
Flashback table table_name
to before drop;

ex:-- Flashback table dingi


to before drop;

b.To delete the table Parm......

--1st drop the table From DB.

ex:--drop table dingi;


--Then to delete the table from recycle bin make use of command:---

synatx:-- purge table table_name;

ex:--purge table dingi;


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

DML(Data Manipulation Lanaguage):-


1.insert.
2.update.
3.delete.

1.insert:--
--This stmt is used to insert the record in the table.

syntax 1:--
insert into table_name values(v1,v2,v3.....vn);

--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:--
insert into table_name (column_name1,column_name2....column_name.n)
values(v1,v2,v3.....vn);

i.e:--insert into sqlstudents (name,usn,CONTACTNUMBER,marks,email)


values('KIRAN',23,888888888,96.36,'kk@gmail')

===================
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:--

insert into table_name


select statement;

ex:--
insert into DUPSTUDENT
select * from student;

-->
insert into DUPSTUDENT
select * from student
where usn='1st';
=====================================================
2.Update:--

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

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:--

1.Using from clause in Delete stmt is optional


2.Even delete stmt can delete all the record from table...but it results in
decrease in performance of Query(since it will be executed Row by Row)

====================================
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.

SQL> insert into student values('567','DINGI',36.36,1234567897,'di@123',98);

1 row created.

SQL> select * from student;

USN NAME MARKS PHONENUM EMAIL AGE


---------- ---------- ---------- ---------- -------------------- ----------
1st13ec125 AVINASH 96.36 8298212510 aci@123 28
1st13ec126 AKHILESH 69.36 8877599869 aki@123 30
1234 DINGA 96.36 9066581587 a@123 32
567 DINGI 36.36 1234567897 di@123 98

SQL> rollback to a;

Rollback complete.

SQL> select * from student;

USN NAME MARKS PHONENUM EMAIL AGE


---------- ---------- ---------- ---------- -------------------- ----------
1st13ec125 AVINASH 96.36 8298212510 aci@123 28
1st13ec126 AKHILESH 69.36 8877599869 aki@123 30
1234 DINGA 96.36 9066581587 a@123 32
===================================================================================
==========
DCL:(DATA CONTROL LANGUAGE):--

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:--

--Intersect operator is used to combine two select stmt,but it only returns


the record which are common for both select stmt.

note:--MYSQL does not supports the Intersect operator.

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...

3.Prime Key Attribute:-


-- Prime Key Attribute is the attribute among the Key Attributes which is choosen to be the main attribute to
identify the table.
--In a table we can have only one Prime Key Attribute.

ex:--Phone number

4.Non-Prime Key Attribute:--


--All the attributes except prime key attribute are known as Non-Prime Key Attribute.

5.Composite key Attribute:-


--It is a combination of 2 or more non-key atribute using which we can uniquely identify the record from table.
ex:-- Name,YOP,Height etc.....

6.Super key Attribute:--


--It is the set of all the key attributes.
--We can use this to set a primary key attribute,we do not need to search which one need to make primary
key by looking at the table.
ex:--Phone number,Voter id etc..

7.Foreign key Attribute:--


--Foreign key Attribute is an attribute which behaves as an attribute to another entity to represent the
realtionship.
===================================================================================
======================
Functional Depedency:---
--The functional Depedency is a relationship
that exists
between two attributes.
--It typically exists between the prime key Attribute
and non-key Attribute within a table.

EMPNO(Prime Key Attribute) --> ENAME(non-key Attribute)

-The left side FD is known as determinant(it helps user


to 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.Tansitive Functional Depedency.
------------------>
===========================================
ex:--
800
1600
1250
2975
2850
2450
3000
5000
1500
1100
950
1300
-
============================================================================

You might also like