0% found this document useful (0 votes)
61 views

Dbms Notes

This document provides information on various SQL commands used for data definition, data manipulation, data control, and data retrieval in a database. It defines commands like CREATE, ALTER, DROP, TRUNCATE, RENAME, INSERT, UPDATE, DELETE, COMMIT, ROLLBACK, GRANT, REVOKE, and SELECT and provides the syntax and usage of each command in 1-3 sentences. Examples are also given for some commands to demonstrate their usage.

Uploaded by

Abhijit Darade
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views

Dbms Notes

This document provides information on various SQL commands used for data definition, data manipulation, data control, and data retrieval in a database. It defines commands like CREATE, ALTER, DROP, TRUNCATE, RENAME, INSERT, UPDATE, DELETE, COMMIT, ROLLBACK, GRANT, REVOKE, and SELECT and provides the syntax and usage of each command in 1-3 sentences. Examples are also given for some commands to demonstrate their usage.

Uploaded by

Abhijit Darade
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Prinay keg (id ,name)

Key
accele
Cll rows
disp
select Promempiayee
drop
drop
si use to delete table fruncate
3yntax table tablename

eqdraptableemploy ee
heck sihng seleca adrom employee
Ls ulget emsr mugitablen or uied does nat extal
aTruncateF:Tis tned to delete all the data a
the tablebet the table billexistthe tab le
oll be em pty Gtab)e stracure. lem ain, datn will go)
3ytaxtruncotetabledable nam

dhancadetable emploube
Rendme Rename theltehle

rename oldablenme to ned teLble


Dendme Lemployeeta emp

Only tabBe fa present


ohichLACeropflan
is
Dithou employeedoe not ex1Std all cy
haoing the same gtrucUe
elechngstenmed
Create
and data
emp
reate tabe emp leyee
Select * ron emp
Data
Pune

on the Cols
alter: T TA Ched t pes om op
add ne couimn to the
i) add/: It is tNed to
existing tablY)
alter tabl e tablename
add col_namedato_type C3ze)
(which tab le to alter)
eg alter table em plo yee (ohich col to add tee)
Qdd age numbesle)
thec cols u haue
descrbe employ ec:tellsdll
Ltable ka shuctuse display karta ho
eCkaunsa o, daa type preaslon,Ien
desc e mplcye
Tt s uyed to delet cols no ns
alter tabletablename
Syntax drop cotumn columo-nme

alter table employee

I ia hed to.change data type f


3i~e2 a column
aten table table nne
Sytax Moddlyolumnname
dat type
Kyq change kana
atter table numbenC5)varch
mplayee. ar2C5)
modi?y id
Rendme is Ued totencm e the coumn name
sytax altertab letable name
otumn,
engme ald-csname to ned-tabehame

Clter tabletablengme
e enaztoe Column. jd toe_id

2) DML Commands
a insertu Tmert rod/reco rd tuple a table
8yntax mert roto ta6le _namelcoli cal2,-cl
valu es Cvou Nal

Vaniattoy the order


D ímertlnto employe e g 6

No esC9 Santosh , 3000 MkT, 32)

9) isnest nto eaployee Ceai d,aqme , salary,dept


Vales C2Santosh 3600 MT \aluy
æe doppeLawotdedthe last vadue sCnot enoush
speciying conamé isifmpi ot eslgning Yakny
3) chang ing ord er
imert into employee name ed, Baln,age,

b) delete IH is uaed to delete robs that


1Satis 2ie the concition
rollback = undo

delete rom tablename


Syrtax where condon ,
delete rern empleyee
Salary
twhere Salary 8000

we dont tonte condition e ros l be


Placenet
delete d
What Ta the dig b/,dop, truncte3 delete
Can't roll back t cant Tollback Can rotlbask

Data is Cto- com ijte


. Cann¡t votlbauk

’ DDL command, ahe cuto - commited but oML


Corm mcnnda re not auto - committe d S to scle
cue need to tune the commit cemmomo and to
cancel changes,rellbackco mmand can be uied.
Can
(n neuer chang the ordenpositn o the
coumno inthetable

tables pa ce is that kiFda sp lce whese al He


tablesill be stoye
Date std ormat iDD-MoN-I; Leq : 11- AUG -20
>Mertion logical op as it s like and/
fL39L related,
DBA

updatet
the condition
ie tubed b update data that stis lies
I2 we dont orite con dutic then (a the soss
tdill be updated

syntax, updotetablename
Set col1= Vai Cola = val,

update empleyee
set
salang
uhere salay<= 3000 con diiov
alowe)

DcL Com momds sed by DRA handlinq/ badup/


re couey handlle manaqedata

erid & pauwad

create Ujen santosa


ldentiied by 3antosh123 creLted

qYant Jt ís used to give permissioun to / mae uyelu


syntax
grant privilege t priV2, apiuNA
Dateo us e r t L e r 2 a a g e r

'ar dnt Creote tablepnv


to Santosh
grart un limited fablespace b aive permissiy
to Satosh on tablespace
case 2emitue
table ke andar ka data ls
but sL ormmands e not

Revolke : s t, ed cancel the perm+ssions.

Syntqx reuoke priv, priJ 2, faiUN


rom Useri, wser2 yuoer

Teuoke Createtable
tom Santosh

TCL
a) Cam mif : lo Sawe chane
g 6 ) DML camm cande)
+) Rsllba d lo cancel the changes made by DL comncad

Data Retrieual Comnomd


al cots

Synax select *
rom erap table_name auhere conai
Hott, o2,,otN seleted
enpreIOn
3el ect
*lcolicolN/expTemign
romtable-name
ohese conduticy
Guidelines
D Not case gensitive
gelecSELEC
3ELEC E
2)You cannot obbseulte COmmands exceptdescibe! desc

+ j
command
bettes t tâate each clae Line
Lotuniil sep
To com pcthe stsing date de neod t
wwrite in quotes 6 3
206

Vatiation& Salary (selecst golary


916 mptoy e
whete name A)
Disploy all the data o
select eempleyees
dous
rom employee nd claue select rom employee
) Displey id, name salay og emplayees
gelect d, name salag 3eleched cols /Can chane
}rom employee the order.

)DísploySelet
those* empleyees wh ose salay 3000
rom employee Display al colr
ohere galary>3000 or the Cond

4) Dia_leuthose emp. uho asehe cdoikinq


select
rom employee
besling in mkt dept

where dep-MkT
9horkiqiin
gelt*
mkt dept and galany > 3000
rom emplegee. andl
where dept MKI Sala ry > 3000
whose name startsith (Pla cemevt)
select*
rom
emplogee. baki aage anything
uhere name ke
Ts not aitoÛ ed ed or patten -
matchin
ohere ng me like 9/ or name Iike s . 9
Noo? undescores
>eprejenb no of chara
ctes.g csste
Date

where name ike a endscith o


where lower (name),ike
Yor compaison the name i8 towered
but the data in tabte is not changed lower
3econd etter ig a
selec * seond lettey.
rom empl oyee
where name 6

only ah ead
letteh no- o letters.
uhere nome a hends oith h

emplege houing
where name
6
a
fike
in name
ay.
% = 0 ya 0se
JYad d charactex
Kahtpe to name: me cata ha.
s)alag ts betoeen
where name
Iike a cd
ame Comtainina a,cd

ohere hame ike 6

matched
petfen b be

whese
8elect *
atog b/ 2000 56oÜ
11

2rom epleyee
2stCAIA
here Salary >= 2000 and
ery< =5000.
Dele

tuauta oP Gcomp op tuice incudtng


OR
wbene 2000 5000)
salary between 2000
2000and 60GO
)Saloxy is either 2000

Prom empleyee
whereSalary 2000or solary= 3000 or galary
to auoid multi ple orop
ohere salary Îh C2000, 3000, 4000)
whene
where salary
salarynot in (2000, 30o0
to 4000
ekdud e them
Displsy cnnual salary ag emplogees
select ld,name Saldy * 12 as
rono empleyee Annual shlarg
Put it in doubte quoty
qu
name Fist Na me o Tnctude space
alaing
2or display purpese, the table cos
narne· remaiwm the 2ame

ns 206 + 300 *4 460-l00/id

[dalis a dummy toble eol ger Kalc Etemp)


8olect 200+ 800 Ht 40lÛolo
torn dual

5Gil dis play


C4 clause in aelet statemet)
)arder by T daplays data in soted hder
diep
ip ehanacheisthen onted TnIo alphabetical
alphabetical ohdes
ohde
Select
displas in by detatE
Prom employee
order by Scalala yy as< dscending crdes «g saloy
order by salory desc (or au)
order by name /desc Prionity to capital lete
ord er by cupper Chame tthen sorts 3mall leh
5) ¿Youp byAggrgate /qroup
Punctfons
min C) diplay min -dal
: select min (salary) >max C) max datg
rom emplogee
geled oug (salary) countC) Necrods Satisyig
rom employ ec sn the gve oned

aroup bg or qraupi ng
Suppese we hawe3 Cunique) deptsanel
HKT, HR,Admin and ant to display
gaag or minimun.
each deptks
8clect dept, min (salary
troro
employee
gYoup hy dept
It wilt
will gvoup the vos and disploy
peh group
order bya ltbays comes ost Tn SQL

hoting It diaplay
the conditja
Those groups that satia ie
on aggreqote unctioshere clause is nGE
allowed hawing clausesg
Dig? b/0 ohee > hawing 2
sk where clauu e is esed to restáic ro hauing.
cluise s used fo testit re ps
add
e s e lselet
e dept), sum (salary) ottdeach
solarias
dept
rom employee
replaces here heuinq saldry o00 ke
cond MKT I25 Coo
Presemt in
gTOup by depti HR 6o00o
the group by cauuE

’Displos count /no-of employses in the compomy


Select counCid) ldisplcys totay
from employeeJno:ot enp

Diaploy e emp
nox e emp
no in edch dep! (each >qrep
>

MkI 3
select dept , colunt(Hepidl HR
Rrom employee ADMIN
by dept
e
order by coun(id)
Any ard ADMLN
MKt3
hauíng
group byS
order HR 3

orderb
In short
select
rom onty 6causey fn sgL
here
gveup by ordeh oesíortg
clauses
6
habing
order by

Subquesy A Hqvery Tmide anothe quey 's called


aubqlen Cmin 2quesies )
Syrtax:
Salect col-na tne
Subq uesy/
inner query
om table-name
where col_name op(select col_n mes
Guter qde gTom tablename
ta where condJo
2irst
2irst inner
inner guey dil) be exettéd ofp
qiven
fnner qu eryill to oteh
quey
24 nal o/p wt be prouided by cute quley
Q Display those employee hose Salany B000
select
Prom employee
uhere s adai > 3000Le
unknon dota
3alavy> Amit9 salany(unknotn dota iese subque
select t 2rom empla galarg
where salarg
(salary > 4000)
Tel ect 3 rom e mployee
where ngme = Amt
THpes o subquey
eturna-on

) Sfngle rot subquexy It Teums onuy aie valie


to the outes quey
Suses relational op > , = (e,=, /<>,
eg re~er preuieg single ro op
T} retuhns moe thon Gne
valles to the outea
ues all any
Inin,, allj (mutiple ot op
Qeg: Display thaseiemp Ghose salang is mohe
thowa emp toekins in mkt dept
select all mens gab ee
Jyada
2000, 3co,
rom emplayee alt Scoo
ecdhere sdlary 9 selett K6alary
rom emp loye
where cleptNk7
D, does not req d ny addition al op ila < e b
1Ssame cs Thos e emp
Display empcohöse salany
in mkt dept
working
Select *
Prem enployee select salay
Shere salarg
Jhere dept
tinclades dnd dept c
NKT)
data to excude MKT dept emp
/n means cqtiale fo AGta
You ust e uye rel op ith any and al
oR

Select
Brom emplogee (
uhere saly any Cselect SaloE
Can begreter than 2rom em ployee
either /ang ct the where dept(MKT)
ang (2 000, 3000, S000)

Using more than a Bubquelies :


Dispta emp hose salesq >> Amts salay and
those ¯erking ín MkT dept
3elect
rom empleyees
where salary >Cselect golay
2romnemploee
where name Ani9
13M and
salaty all (gelect Salasy
Arom employee
where dept KT?aL
Can ue di table, in Yhne and outer quesy
> Yes
sel e c t b t f MKT or tHR
2rom cke emplye dept
where dept in
Calect elept tocato
3rom dlepartment
where location Mumbt
isplay emp in mum dept salary > ad oin clept
Selec
Prom employee
ohere dep in selec dept
roms department
where locatin
locaton =Mum baj)
Qnd
Salary > all Csslect de solay
9romsn emp leyee
where dept Admio)
’ We can ado
Bubguey
(Nestes subqyueies
imide
Imide a Subquey

Diaplay top-10 employets hoting max 3alas


)Dispbi emplogee and his/ her nanag elsalony

Procos Cmeaning
Jngormation prsesed , otganI~ed datu)
4on delete casCad e
t o del ete nuL
elacae
Dete
Pags

(onstraints

Not nul Grced proetice


uniaue
onty Pk

Forelgn key t
Pk.rejeks Pk o2 othe table.
fore'gn ker Ceust id) regerences ustamer (Td)
a d he colin the table other table is pk
Cna me)

Oniaue:
Cieatetable tustemer(bhan
foatca
Ngme VARCH AR (255) ONIQUE

A) check
Create able acount
Falan ce int C1o)
CorvSTRAINTaccbalance _chk CHEck
balan ce > lo00J

Deault
Create table accrcunt

balance INT NOT NUtC Delo lt O


DML

ReplucesA0 Datals.alreay preset


1 data not
presentacs c inset
Replace Tnto ouwtamer Cid,crty)
Vaues lo51Colony
Repldce into Cutd mer Set ld =l 3o0 cty Utah
Replace into customer dcname city)
SE electçname,city
rom customerA
uhere d = 500 NULL
Yahape asign nahy hete Qre declcoed as
3oNielues
Jo
2 evcn ig they ye prUjouly asigned
-> update ill do nothing i the o is not preiet
the Tot
Date.
JoNS :

Treldions b/o tah les in ROBMa


Fetth clete tufngoins
kR
Pare nt child
toble 2
2 table
nner join Reultant table tht hos matching
values 2rorn both the sides
L
Re
matching 2
tablet
3 table
Data is merqed
Te oppy oin thele ghoulc be ommen attbube
b/o both the tables

Syntaz: 9elect lcotumn-tist)


rotn tablet
inner.icin table 2
On condition

20uejoin

OR

Kight j'oin
Data

ltioiD Will contain the merge d valy Pot


both the tabley
andthe entire lct teble
Let table
LLRight fable
key
RR2
2
3

key LILo Ru Ra

Merged
Remaining
botd Null Nt
4
vatuesstbsirute
table

Rightjoin wil Will gontein the merged vaues o the


com mon adtr'btes both table ans the entire nget
table and the rest s the Nales or the
Let table itL be gubshtute d nuu

key RI R2
2 Meqed dat e
3 Romauning
Dda ot he
Right tabie
elacGatA
Data
Page

Ie?t join 3yntex Right join


e3elect columns gelet column
rom tablel e t Prom tabte)
Teg4 oin table right join tdbe
On ondihon Porjob On oin. c¡ndito

teble able

L2 key Ro
1
2
3 3

key k,

2
FULL JomN Leydot
3
not waulable

NUL L
7
Nut
EalljojnLet join URigat sin
Syntdx

select rom let iable as l Le2L,j9in right able


oN -key akey
UNION
elect * rom let toble as kighk Toin ciglt table as
ON key key
Crossjoin > Carle.io psoduc
RT
5 xou
Reltnt 5Xo5O hos

LT R
A - R2
’2 B

SReltant
RI
A 3
A 4
B 3
B
cols ke
Join appljcable on coll mngCmaBching
Un'on pplicable on al sows just gnoing Yepea
valies

LE4 jion

eelect
Prom project as p
le2t join employee
9 onpd edd pempld

PreT oith ep nameg emoil d :


Selec e-tnme elnome,eemaillD , enpls
cobe greng emptoqee -praje ct
rom employee s e
Tght jein
jotn projed as p
eid sp-empld
6
6asoid jgin keywed , Carmma 9 ano inntead s
ON cUse 9
hehe claye

3 comists og unigue vales


Set op:(Vetical om) Conbt ne 2/more selec stms
Same tyne no°6
lnte selen colg ehout d he thete
ins
hote hai
HerzeA fat Rows pe apply
tables
o contents o the
3elect rom table i
UNION
Gelet * rom table 2
elascae

ONloN INTE PSECb

T T2

Set op
matehtn coal combines salect stm
Cotumn- Wise c¡mbn row- ise comb n
Dote types can be digfa Data typ o as can be sare
there can be repetitive No cep Yos / cols
Tos cos
Noo cos moy not be No o cols has to be Same
Same
’ hornizontal Comb1. VeHcal comb^ o reults

B ThtersectTD T
Select rorg T Select DISTINCT id 2rom T
INTER9 ECT X. INNER JoIN T2
Select *ram Ta
A
2 A 2 8
9MINUsT l
A
2
3
select d FROM TL
LEFT JotN T2 LaingCid )
A A
8
3
4
Data

Al employees he comp
selec Jrorm Det 1
UNION
gelect * rom Dept 2
) a emp in all depts ho esk as 9ales mon
Select* rom debt
dept whererole sr 9 les ma 1
UNtON
select * rom denta ohere ole Sales man 29
both
3) emp workine in att depts
DZaat sel et rom dep depfi geg
INNER JoIN dept
sTng E-d emprd ) al cots o dept

4) emp. UAking n dept t but not dept2 t a


9eled dept1.* grom dept t
ohTALEFT Jo!N dept
T
ohere dept2. emp ld3 s NULL
elept
depi i empid name role
émpidid nam 3iYot e
A tHR A HR
2 2 B mgn
3 ad min 5 E emp
n4 D mkt

You might also like