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

SQL Notes

1. SQL is a language used to manage data in relational database management systems (RDBMS). It allows users to define, manipulate, and control data. 2. Common SQL statements include SELECT, INSERT, UPDATE, DELETE, and CREATE TABLE. The SELECT statement is used to retrieve data from one or more tables. 3. Keys like PRIMARY KEY and FOREIGN KEY are used to link records between tables and enforce integrity constraints. Transactions are used to group statements and ensure data integrity.

Uploaded by

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

SQL Notes

1. SQL is a language used to manage data in relational database management systems (RDBMS). It allows users to define, manipulate, and control data. 2. Common SQL statements include SELECT, INSERT, UPDATE, DELETE, and CREATE TABLE. The SELECT statement is used to retrieve data from one or more tables. 3. Keys like PRIMARY KEY and FOREIGN KEY are used to link records between tables and enforce integrity constraints. Transactions are used to group statements and ensure data integrity.

Uploaded by

Lokesh Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

DATABASE

ORganizd coaction of data, stotud an rebinel diaiskay


TMem a umeti e Necal combi sustem. t con be va
and
cemn and sueh databas al dutepol us fiwd day
DBMS Data Bose Mowglnt Sysbm
asst seRtua aoe hoation, Jobival, soa
QndYmamdgtmnto the datababe. ttnbueh that data
otaosDBMS
blus t sRDBMS
wog.2 b-Rbdras e RolatinaDEMS
RDBMS
b
as data
datine b
stoAl in fohn of celaztin
commen f u l d o tho
o tabksorsultiers
talblls. AND oN NeX AAE
DDL f a a t r s

DtRR subsats o seL TRUNCATE DDL uskiy pd dapinia


DDLDta Dondh Lomgung@)AlWows to berfetm yo'tousoboatie
m the dotabaso suc as CREATE ALTERrADELETE o
DMLIDaia MaipuatienLoonauaag- ARlous to LAss andlmon
lodta. t Aelha ub to iseAT. UPDATE, DELETE KKETRIVEJet.
DEL fBdia ¬onbnt Lamguant}- Plous tofonioaccsjto Due
dodtaloasa. gGRRNT, REVoKE accsss vmisbiors,
PRIMARYKEY
tioacelumn oa sato cowwmns that wmiquoly idstikistdkSno
t i s a spacial lRimd e i q jue ku t commst be NvLL.

FORETGN KEY
t ib afilda st Aodls tha usxpntia aeertePRIMERYIKy
TCLTIamsactien ohel Longuage)
Aleus te manage tombadions iSa daalas.
Mamane dhomges made-to the dan m tabh by a DML
Copls
coMMT, RoLLBACK, SAVEPOTNT
Soea s Rostre doatalbase
Mabe p@nanad te Jast cowwttoo Sotha y pm Wsak
Staato te that beiit whoreh Sunpl
dho
SQL (sttsad Guthux Lamquan-
OEecde qpezia, driine dota,ima ocohols , uwbedale.
Aucerdb.
ORDMS-Ralatiemal Dotabose Monanemant Susem
b a i e sQ,all mesn database systems Such as-
MS SQL Seue 18M D82,01aca MysQL, Accas
* E e TABLE i baekon uh into- Smaeh anttis callod.

FIELDS. A EIELD a celumnim a taloka that s


tecsitl
designad te mairtain shscilic tnfo beil owehy
* A Roud oRECCAD i6 sack_indiuilual snty inthe talsle
A DaTABASE mest ofpten cortaimk one oh mtik talslab

SQL STATEMENTS

SQLkayuehde asant Cabe Sonine. seLECT S2laat


Somo Jstoloase subtems ouia ater sach stacemant.
COMMANDS
SELECT-EdaosTs datafema data loase
UPDATE-updas dota in a databasa
DELETE Dolaes dato faam a datalbase
INSERT INTO Inghb O dadta. iuo a datolase

CRERTE
DATABASE Gueals a naur datalaRo
ALTER3DATABASE Medis dota Ssas a

Gaalb a nr tall
CRERTE TABLE
ALTERTABLE Maddub o tal
TABL Detis a taN
DRo
DROP
INDEX Deloteb a
SQL SELECT STATEMENT
SELECTceli, col SELECT%

FROMtable-name FROM talbla-nam2

SELECTDISTINCT
SELECT DISTINCT Gurdb Solads distin odbie
FROM Custemeb
wHERE
SELECT cel1,ol22- Vsed te ftlha suotds
FROM talble_mae SQL nadsarounel tzo
wHERE conditioni fios but notuith nei

oPERATIONS IN wHERE =,7,<,2,<


NtEaA BETWEEN K Spai
NtEaua Seme paitl muidbiple petsle veznas
wHERE Con be combiwnao uwit AND,OR amd NOT

motrer Lndition.
AND, OR uad fou }tesimg en
SELeCTPRoM tnbl
wHERE Cond 1 AND Lend 2 AND..,JwHERE enel1 oR iencd2ak
wHERCG NOT Cond Use () to mist cendikienb
ORDER BY a ln
SELECTAcol1, col2- usedl to sot oesults by a
paducullah csl in ASC
FROM t a Desc way

ORDER BY cl1,d2 ASc|DESL 2ta


Mulp ORDER BYat
S o3cwgdiwg Coub
SELECTFRoM Gustomeh and Auonolg umo
Name'
ORDER BY Gndbuy ASC, Gustema Namo DESC
INSERT INTO a n bewsad im 2 aya
Waedl t e inbont mEu RoWS IN THE TA E
ONSERT INTO tablerome (ol1, col2, cAL3,.
VALVES (viv2, V3).--)5 doitsv! in col1, 22.
IT HOUT SPeTIFYIN& Cot
ull oe to follow the
sanl
INSERT INTD talole-name
rden in wlich the ols ro.
VALVES (vi,v2,v3- --)5

TESTNULL VALUES
, 7 Cont be wsed fer tMULL VALUES..
md 1 NOT NULL
e s 2 15 NULL SELECT col- ammis
SELECT col-nome FROM talale1
FROM talola
w H E R El 1 1 6
NOT NUL
wHERE col-1 1sNULL
uistimg Jucotds.in a tale.
UPDATE Vsed te malily
UPDATE
UPDATE table1
tale Schmict, Coh=
GET ContaaNam A e l WHERE
SET Contaatalanme udati L cel col
WHERE GAtomehID
UPDATE MULTIPLE RECORDS

UPDATECovdtadIName
Gstemme nb UPDATES ALL nluls
='Juom'
SET wih Mito s cealu
WHEBE Coumiy e 'MLnics j
3tcotols im a table
Uadte Deleta enistimg
DELETTE Dletesboked ea condlihiba
FROM talble 1
WLETE
HEBE connditien su
uoouu of ttalsle
s o ab
Cutomes Delite all
Delutes
stincdu
DELETE FROM
net daataq tulil Kacpiasq
ORACLE adiblutes k ndoodbs.
SOSERNER
M-ACCES6 MYSa

TOP LIMIT RowNUM SELECT col-noml


SELECT
coR-1
TOP A EROM tallena&
SELECT EROMtoble-nonnk
FROM taba nom WHERE RoWNUM<-3
wHERE Como
wHERE
n LIMIT 3
uLed
SELECT
ToP 5o PERCENT
FRoM t l o l e - 1

MN),MAX() Moc
SELECT MAXcok-nonom
Mn MIN
SELECT nome) FROM todolo1
FROM talola,1 wWHEREcnd
wHERE n d i
Rctufvn K
ewb, rotch
Ratuwb the Rutums he a o e
GuaChagt valut o tetal sum o wwm uo

COUNT)AVGL) SUM)-
SELECT CoUNTL an)ANG(mne)|0M(Ll-ram
FROM table_1
wHERE_comdibiarnj
LIKE ubed im.a uhhe dause tesonrh fi ashocite patiesn
The þetuumt siqm hosebtats
CESS
0,1 e altiplochasaclers .

SYNTAYK
SELECT d c2
-Rubesots a Simg FROM tla
WHERC ci LiKEPATTEEN
LIKE PATTERNS
a Stosdt with a -S% in 2a e 8
J a End wth a a-%_Stast udth.ak b n z 2
or% Hone o in awj peSw al,D s t o t h a ne witho

M
AEWILDCARD
single hahaden withim the baaekats
CI L Raebets any
Ral s a h&isbanot_inthe Siackets
Repiesodo a range dosadbos
Cbsp stasttmg i h bns ip [a-c]% staoztig wi ablc
hoct t,kbe at ot fetond Rat
alleuwb t spt madtiple saluus in WHERE olaws
IN
Shedtwom
SELECT wvn-nom e SELeCT ol-nmel9
FROMt-1-
FROM ale-wom wHERE Cel nome tN
wHERE epmnnam IN dv2- SELECT STATEMEN
BETWEEN Tt solects ealuss utbi a qun uaongpe
NOT BETWEEN akblegts
6ELECT col-nom
FROM tallbl-1
WHERE C-nome BETWEEN vi and ;

Con ba ceubed wth lIN ael NOT IN


CoMMENS
--
Sinae nt ymmon
SQL ALIASES
nml
inSt ate usid te gwea tableh olumn atimpeiay
SELECT o-OdID, o-Ordh batu,ceNiaml
FROM Gstemehs AS L,Ondorh AS O
SELECTaustmch Namd_coNCAT[AddRs,,Postalela, y
Cubr) As [Hom Addsse
FROM Gdtomes
ndeh Spuea L
shace put
SQL JoINS
mR
Jeun claAse is uaed to cemoime heuws fom tue eh
talotes lansedona eateol el betueen them
SYNTAX Eh.
SELECT_OAdktg.Od Gustonsh$CName ,Ohdes Dtte
FROM hdoub GstanciS-CT
INNERJoiN Gtomthb ON Orhns.o=
bIFFERENT TYPES OF JOINS INSQL
INNER JoIN-Rutuwma Jcetds,
wtl machvg valuchi beth tases
vetohid frem higkt
LEFTJDIN-Retsmb allsccoidb faon letam od
RIGHT TOIN- Rotuvna a uros
fensid roltthid fren t
FULLTOIN- Ratusms al uSLdS ahale malth ia ight
ei

INNER JQIN 2 LEFT JoIN


Examp alsen
RIGKT JoIN ( FULL SolN

SELF JoIN
A cal ToIN i a uola jeiun., bud the tadle is, joini
wth to 6ELekT ol1
FROM able-t1,tablet 2
wHERE conditioni
CROSS JoIN
T doRimad os a witeo phedudt o the tne talsos
he
imelnda oim-centaio Somlne eus
o in the
oub 2 talolas
roeedupt p e
DoS blw GRoUP BY & DISTINCT
Both distbinet and GRovP By alhces the ne'o lutnad
ANe weGRoUP BY hn we wamt to apblyan agggale func

UNION uted te tombine the l t sat o twe e meiu Soket|


Cause
SELECT c-ni FROM t1
UNIDN
SELECT - n 2 FROM t2
UNLDN ALL
UNION efsehater solacts only distinct wluls by default.
To alour dausticati vedlueb usl UNION AL

GROUP BY
toupb
0
sws thal hae the somu,wallb ine Sumymauy
swb JkRL tUstomeb in each couuma
ORu used u t h 0gate funetins.
EA SeLECT eldnt
FRoM t-1 A
Chiuenotbg4 wHERE Conel
BY -vane
Somihiue. GRoUP
ORDER BY el_name

HAVING
HAVINa dausa thas oddoo to SQL as the wHERE anse
Culom! t be used utth agpugati fucions
E SELECT COUNT( c3),Cotaf
FROM
ORoUP BY
cou
co
HAVING coUNTCCAy 75
75
ORDER 8Y coUNTCCJA) DESC
exiST5
Tost f the andstnnce d Om socehd im aSubguehy
otuwe tue suls quey uiunb ove e. moL saiords
SELECT
FROM S h
wHERE ExiTS (seLECT PreduztKAame FRoM
Paeouats WHERE P: SJel=
=S-SJAL AND Padce2c)

ANY
PNY ePate gusns toue any e the susayusuy ouas
mab th tomd in BRSe subeins "lstSadtishmg csdh

SeLecT Patrann
FRoM Praouucts
wHERE fhotI b ANY SELECT Pdad T
FROM elthDetais wMERE -dte
AL UeAgg th sUmvlah yust ALL pact dANY
RduvS tue all Suluties Satisy, ordn
SELECT INTO Copiob lata fsom onl talsa to antals
b done in Sowme R e n t doalsose
DiEE Å ue ube IN t shlciA daalns
SELECT*INTO Neutabl Nome IN Ocpamal dlb
FROM old tale
wHERE Condn
INSERT INTD SELECX aneheh tab
d o t a faem. ene talsko am intedte t
Solectid Collmm&..
INSERT INTO talS% 2 INSERT INTO 2 d , 2 , - )
SELECT * FRoM talbo1 SELECT l , 2, 3-
wHERE ondn} FRoM t
wMERE condn

-dse loe tye Srstunbavoue uhin 4Seadss mt


CASEsELElT
CASE
Roloce
e
ea
vaei
wHEA atiy 30 THE AwoD th o
LwHEN uatit= 30
MEN' Q 3 0
Erabatuy bgobon EL6EQuwe 30'
ousumb values Gaerdosan cula ban
Gccecng4 END AS Cuavt ert Cwno wuDS a TMESE
FROM OAdoa.batnil Shothand forCASEU)
IF NULL(, 1SNULL) , COALESCE(), NVL)
MS-ACcOS
SQL SeWO
acle
Usep to swploe NUL wlus wh 0 nany ethor
wal ab lauinol
SeLEC Nme, Uait PeiUmitStel+ FNULL 0ls
FeoM Pats Dul bw SNULLC) &coAescE
STRED PROCEDURE
Aupopd 5L ode ha you cam aué,ad edetas be
Aed veh Dme ovehcgoim
CREATE PROCEKURE SelatARGstemeg
AS
SeLECT FRoM Guton0A3

EXEC sohdALLateh
-
vu V n
CREATE DATABASE te Guco DG
CREATE DATABASE testDb
DRDP DATABASE Diob nistung SAL datasose
an

DRoP PATABASE stDB


BACKUP DATAEASE fp_create ful bockup o datalase
te Phal
BACKUP DATABASE tatDeB
To DiSK =D:\backubs testDB-bk
U1IH D) FFERE NTIAL caab dilntal
Baeu
CRLATE TABLE
lCREATE TABLEnautaloloname
ol1 Jatatylpe of ol L
el2 2
CREATE TABLE FROM ANO THER TABLE
a cREATE TABLE nentalslomoum AS
SELECT cl, c29-.
FROM istina tals
JHERE--j
DROP TRBLE TRUNCATETABLE
dnnns0
Selote dato, eide
Ponstinng da tabb im talble btb net telle
DRoP TABLE Sons; dTRUNCATeTASLE
ALTER TABLE
to aoll,
Uadcpm la mod oums n nistung vosl
alss add o dhaecensbawts
Are R TheLE talle- Yann ALTER
DRoP
TA8LE aAstamo
ADD oN dainbype N Emaly
opne Dotatylpe
ALTER TABLE taluh-newn
ALTER COLUM Col- roml datitype
Di b/wPet & UNiQve
NuOln N aluwaysallouwesl
CONSTRAINTS Rs soi data im a talbl
on bi spiktdl whle vMbing_CREATE TRBLE ALTERTAESt
Us imit the tybe a data that an ge ide a tatl.
ba&ues acuwhnoy and ukabliby ol he data in the tabo.
onstiaints.ca. b"celamn Aul table lnel
owmanly useel_costhaintsin SQL3
NOT NULL-Emsuis dhat a iel an!t hone NULL valut
UNIQUE Ensuus that all vauts ina aumn atl d
wnguely db
PRIMARY KEY-Cominmabion e NOT NU LL UNIQVEah
FoREIGN KEY-Uniqaully iobntilus a suceid in austhe tale
CHECK Esuwrils that all valads.inaul tiugskelete
DEFAULT-Sts a dolault value ha cconn.wkn veval isshecla
INDEXUsdlto cat k paleuiedat thomHho clatabas
Okad, SRL Seve, Acccy dRu MysQL
cRERTE TABLE Peusons Trspad o DNIQ UE Raso
iD NOT NULL UNI@UE
LostNgmuohehait256 NOT KItt ule haue Omodher Qime os
FiuslNowme yewhaA (255) UNIQUE (ID
it at last
S Multie cos
oALTeRTABLE PataeMS ALTER TPABLE Pohes
ADD UNIQUe (ID); AbD CONSTRAINT UC-ote
ALTER TA6LE P2sos VNIQUE sb Lastone)
DRoP CONSTRAINT UC-feeni
MULTIPLE
oek, SQU SOWeI, Accobs SINGLE
PR IMARY
KEY(ID, Nawn?
PHEY D NOT NULAict)PRIMARY KEY
i S8L Sedh PRIMARY KEY (ID)
rod& , My 50L
erba 3D ut NT NOLL PAINAty veY, PRIM ARY KEY (OT)
Pahben D FoREls kGY REFERENES FOREIGN KeY (P REFERECeS
oeahltnID)
OME
CMECK Ae TaCHECK(A>18) CMLCkA 2=19
DEFAVLT Cd vrohwhoh|155DEFAULT
ALTER TAGE PASs)
'Sadonush
ALTER Cy seT DEFAVLT S a d :
INDEX
Adatalsase inelen b a data-sbuebuke that þouiobs quik Jooknp
in alumm o talummb of talle tEhancer Hee
a
dola a

detalsase tahu0
ohatvens ocevsima, data uam a maitan
te coet of oddioral wites and mamory to
eata stwctue y uara
Swr
inclones ima bssk.
I Bha ibne ndsn to alp the n, the Vy
hacks ave ow im the tuia tam bsginmigto
a Talle Scan bod joa panRvmancz , Ind,e UnIare yy
outononiy

couns htalole dern't hnn_yclustnd idit


TYPES oF INDExES:
CLuSTEAED PND NON-CLLSTBE
UNIQUE AND O-UNQVE
UHIQUE Lndonas that alp airtasm dosta a y y n u d i n
Thet ne 2nswb
BETWEERNTQUE coETRAILT A Ravelu
DIFFERENCE
Thhe au ng mah d uncesbw awaue constat rd a
wniane n d l r n . J n t o s t a n we add a wniaue cortrain a nia

indan qots dused beind tha econ


Uviaue mdm com be dlutehadl a nen- duteo
*Bdaoaudt, Psimau BRau cnstaninto uduba umiaui rd
wheua a UNiquË raoimE aeis nnu nondhustoInd
unad,
'ndin.Thut JoaJks a mdan
pa dhonged y ua
an loe hRro an anikEv
on
Unue embtho A
a l U the tolblL carams u i nus n tre ka dunmb
HON-UNTdUE Trdnes ohe ve a s t onlera oriPnints'stood
are sRy usdto imbuse ausr paRahne bataian
a str a r datd volas tht dauy
CLUSTERED AND FNOH-CEUSTERED THEEX
Osus mdera osa mdanes uose crdss R te sous in the atalkeso
ohbrpo to tha rdir c the aous in te ynclert
l yont dustid ndon_con dnist imatl whila multil
Rabthe dota n t e dabebast-
* b t a b a monngn dionpts to
i Spne o r a t e cspondling Ryb apah bn the clsta2
imgn.
3 DiEEEKENCES
4t Cusssad mdon medKs the wa e A d s aa stond ima databeo
bosad Sn the indlinedL coumm Non dustehol mole cHLales
a sapnaa udity stim e tloke uhid uforenab the
oiajmal tulla.

dno trsm the dadboloais, woos tebJhincoanshtha


ven
dussud indon is rlotvey douioh
A a e co h a a single Justaur nod whercas tt on
hone malliblanedutorud mda
UNION , MINUS, INTERSECT
OUNION : Combines and hotwns the s e s t sit etsiued by
ma UBelSELECT
OMINUS totemerts.
to wmone ukals m-the aslt set

2 SELECT y fom e sutt toimad by tius


SELECT queuy on t w n ftoned out Juults
the
tNTERSECT tt comlines the fitekad by
u o SELECT Gtadlmanttswkern the Jecerdss faon ON
the othe ond e m c u m s this idteislctuO O0
ondtlons fe uen e UNION, MINUS,INTERSECT
*EadhseLECT statomunt wthim the clavse must haw
SAME NO' OF COLUMNS
*
celouwm must alke hane simila data types
SAME DATA TYPE
The colown n, a h sELECT shouLol hoe the Some ohdoh.
sAME ORDER

KELATIONSHIPSIN SG
O o te One - o m b e doimeo ob h e ulationship blw 2 talas

h e e eas sucod in a t a e is awseclatad wdh woe of end n otha tal


Oni- te-Monu k Many-te -OmR- Mott cermonly wsA nladionhi
A ucAd ina talbl s obsociated wth mltA n d s im cwrtall.

Mom te Mony us n Caa whUn multttsle atanas Aan


eb sido au naadaA Ah dokntng a ulations
Sel Raouncng RalationaRIS- Usd uhen a talole
reals te dlime a selatiemship with.Utsal
ENTITIES AND RELATIOMSHIPS
Entity An tiby cam be a Suall-uoild o i e ,etthor
tamgRe_c itanajote, thodt com be ansib idantiialsl
Feta og- Jn a calage dotabas, studsis,ud
mends gmd phaiects om be
Pouloois, wdkas
&ntitios.
Fach odiby hos Soma astoeiatad pobotios that mdde

Rolationp L bs tuuetn avtitas thadt hane Somathine


to do with.each oth.hoh JgEmplouees talble in
aaoase_com be dpsoeiat wibh the saDos
cemsamysalb le m Somne dloct a s e .

VIEW
A Rwin SQL visdtual talble basid en he a,H
a

O L statemDnLA ilw ceriaims sus ond ce


Set
hs
T 0b. J a l tolole. Fulols tm viuu are fialds fhom one
e ms toUSKASm dotalsnae
NORMALIZATION
Tt auaRestts the wau o otgomiaino stndtunud data n the
databate aiciovdRy. I t meluelas, Oustion o8 talbas
estalelishimg alotintpb bfu thavmg ond daltning ulo% j o
those uNationship, Inconbistoncq amd saludomy an
Rat in check baged on hose ulnas,hance addinlnid
to tho dotallase
usa ta to leueh toa a dibaay
KMALIZATION (ACCAs dada Rem higho S Ceneed
t e b e onewnalizotion, neumalze Sohemo
ite a schema whidh Rass edundovit inyenadtien
The aumamee is tmusved by vimg Jasumdaney and Raa
the ubulttamt dsta conaistotThe ooben p m
domarmalzation b the oveshals rduad in quoy Precasse
oe- nomai 2ed 6uuewe
d d s th udundnnt dota to a talRa lay imoobdtma
datclsos qNUDEOs that comline dota faom atious toR
wtoa swgki tadle
E
ADVANTAGES OF NORMALIZATION
Precbb eOtoaniziq data n stuetusod wey be aroidl diploatien
Batte Dadtalsabi OgemizAien
MotL Talalab utth Smalloh uo
EAciont Data access
GUortor onbUtu for quwiS
Eabioh to Umplenment socs
Alous tosl, modilicndban
Risluaion duslicate dat
2Mshe comaadt Jatasase
Ensuse conisterl data a modliation.
IN Sa
DIFF B/w wHERE AND HANING CLAUSe
WHERE wetkb o n dew data. HAVING weks om agg
t occuts
bejott ony ghouping ot nado. Usad to fte valas temaa
DATA NTEGRITY taiels
cCacydatay Cswistoney of datajJruauoy
tonece buaints3 ulis onlalln E t
w:ACID PROPERTY DF DATABA6E n g
ConruDn
Rabaon Atomicity oLTsolalgr
nsistemc Data dD DwioJlitu Toonsadion alava
KeubDyme / a ( all valzdatio udes Seeuns
TBIGGEB Pos stahta.
18ggch.in SQL ake a spacial tupbe of stored preceus
thotahe doined to WMscun autenatically in blace oà
alteh_datamanliliaLien. Jt allens yot te wnt
a batdh of coole_whon an insent, updo ch amy olheh
Quthyib Srcieited aainmkt a shocii talolo
Tupabef TageBalaeAmabt, ALbn sast,Bla updata,
Dalate."
CASE MANIPULATION EUNCIONS INSQL
LOwER-A0L te Lawe
UPPER ARL to uppe
iNITCAP f s t dhaa ab Upo

You might also like