You are on page 1of 25

DATABASE FUNDAMENTAL$

+ sQL DDL Comnonds (Data Dehinition Longusge)

DOL comnands {on Dot Boses :


Coeate
2) Dxcp
CREATE DATABASE CompusX; id ute adatabose
nomed compusX
CREATE DATA BASE IF NoT EXISTS CampuSX ’ wil ony oute
e dattose nomed campusXi
it does not eust aluady.

DROP DATA GASE Compus 'X ; wil dalite the dasabase


nomed compuSX.
DROP DATA BASE IF EXLSTS com X
pus w i l dtate datbase
campusx it ests

DDL (ommonds fon Tobles:


CREATE
2) TRUNCATE
3)-DROp
CREATE TABLE USns(
useLid INTEGER
nome VARCHAR (2 55),
emaid VARCHAR (255)
poswotd VARCHAR(255)
dGSate
Date
Fupe

TRUNCATE TABLE USenS wid em pty the toble


'Usos' but wid not
delete it.

DROP TA BLE TF EXISTS USens wid dalate the table


usens

DATA IATEGRITY: Rels to the otaracy,LompletenesS ano


consistency os the doat stoaed in a databose
Vauous methods used to enswne data
integwtyincudes: (enstraints, Tan so ct
onmalization
Constaints ane ules on conditions that must be met gon dat
to inseted, updatd om deleted in adatabose Table
NOT N0LL ensones that value Connot be MULL
UNIQUE ensunes that uaue is unique doesrt getdup lit
PRIMARY REY
AUTO INCREM ENT + automatica (ly updates a value
CHECK ’ dato ony inseoad when n tunsnditiontsueit
checkS
DEEAULT we Can g st de<autt vaues
FORETGN KEY

nome VARCHAR (255) UNIQUE;

CONSTRALNT USos_emad. unigue UNTQUE


(nome, emol, poswoMd)
- the combination o nomk, emai, pos wotdis unqu
CASCAOt we chong onyfhing in p
nellected in boeign ICey tolole.

CONSTRATNT UseS-pK PRIMARY KEYusoid,nome)


-- now hoe he cembinahiorn o usoid nome i3 pumau
Kuy KEY Ccid) REFERENCES
cON STRALNT deys-K FOR ETGN
custemus(cid)
CHECK
FNTEG ER CHECIK (ooe >6 AN0 oge < 25)
age
oge <25
CONSTRAINT students-ogecheckk CHECK Oge > 6 ANO
when we dalate o value 6om pu maska
ON DELETE CASCA DE
Key.then it wil be daleted er
7ouign Ney
ON DELETE SET NUL
ALTER TABLE used to modity the stsw chre q an exushng
toblu
adol columns,dalate columns,modi by
Columas

egl: ALTER TA BLE CuSto mes ADD CoLUMN sunnome VARCHAR(225)


MOT NUL
AFTER nome
new oumn 'suÝnOme' wil be addd aten'name column

eg2 ALTER TABLE customens


ADD (OLUMN pon.numbon VARCHAR (255) AFTER suonome
A0D COLOMN joining-doate DATETIME uoT NULL
e, 3:ALTER TABLE customans DROP CoLUMN pan.numbon
ALTER TABLE Customes MODIFY CoLUMN Sename INTEGG ER
ALTER TAGLE Customens OROP CONSTR AL NT ustomu- age- check
ta6:ALTER TABLE customes A0D coNSTRAENT ustomch. oge. check CHEUK
age >6
classute
Date
Pace

DATA MA NIPULATION LANGUAGE:


INSE RT ’ Used to ingot data into our databose lables

TNSERT INTO databog nome.tade-nomeusULid, nome.


emol,posifwod)
VALUES( NULL,'ni fsh', 'nitish@gmail.com, '1234)
INSE RT INTO database-nome. table-nome
VALUES NULL'onkit','onkit@gmoul.com','1234 5')
eq9 INsERT TNTO dabbase-nome. table nome(nome,email)
VALUES('omit 'omitQgmail. om)
eg INSERT LNTO daabase-nome. table_ nome VALUES
(NULL,'Bús habh,'sus@gmail.Com' 1234),
(NULL Hohon, ohgmaid- Com 1234),
NOLL nahu' sah@moud.com',123'

SELECT used to onetuve inomaton ot data k'rom


own database table.

SELECT * FROM databasenome. table-nome


- i t selects all the columns (om the datalbase table
ond ditplays it. (It gether eueonything)
SELECT column,tolumn2 FROM databage nome. kha.n
ALIAS ued tb menome a column whle stetuiving
SELECT coymn-1 AS Col-l colwmn-2 AS co)2 FROM
datbose_nome. fabe_ nome
elkssmte

SELECT coumnl
foumh-5)coumn6
sRT( column-3coumn3t cowmn-5
AS PPE-vaue FROM databaenome. table- name

DISTINCT used to s1etuve unque vaues forom a coenn.


BRANDST
90 SELECT DTSTINCT Coumn- I AS
FROM databose-nome. table -name

SELET DISTINCT cowmn-1, coumn2


PROM databose nome.table-name
- selects Uníque comloination of calumn- calumn-2
WHERE ’ used to ittey owwS based on some condihons

oa SELECT t FROM datbose-name. table- name


WHERE coumn3 =va lue
SELECT t PROM dabbase-name. table-name
OHERE pouce >l0000

BET KEEN + used to select sows blw cestoun aroge.


SELECT FROM databosename. table-name
wHERE Qyice BETlEEN 10 000 AND 20000

sE LECT t FROM dabbase nome. tblename


wHERE coumn y'uaue- ANO column2<'ualue-2
ANO (oumn-3 y'uaue
dASSA
Dats

Poce

ORDER OF QUERY EXEcUTION :

H D
GROUP BY HAVING SELET DrSTTNT
FROM JOTN WWHERE
ORDERS
adunoexeuhon

IN NOT IN ’ Used os on alteo natiue to OR

SELEC FRoM databose-name. table-nome


WHERE Column INvawe'value2value-3
selects gowS ÍF whene the vaue in olumns
walue- a91 value-2 091 Malue- 3

dame with NOT IN with oppositeae unchoing


UPPATE ’ Used to update some waues in a column
UPDATE databose _nome. table. nome
SET coumn- 5 = new-ualue'
IHERE column5 = 'old-ualue'
wid update the value qiold-ualue'with 'new udlud
in column- 5
UPDATE databosenome. table- naMe
sET email= 'uenky gnail.tor', passwad =l12345
WHERE home =uenkates h
CETL () ’eg: co nuvts 6-l to 1 4 6-4,toJ
FLOORC) g: (onunts 6-1 to 646-9 to6

DELETE

DELETE FROM olatabase-name.table- name


WHERE camena > 150 AMD bnand-name=lsamcung

taggate functiong :
MAX/MIN :
SELECT MAX(olumn) FROM datbase-nome. tade-nor
’ metons the maxímum value omn column-1
simi louy MIN netoins mimum value

AVE:
SELECT AVG (roting) FROM databasename. table-name
wHERE ondname = xiaemi
’ netuinS
wheetheborond-name
auerage uaue o oumn

SUM :
sELECT suM(psuce) FRM dataose-nome, table-nom
’ netnns sum of all uaue tor the ulumn pouce
COUNT:
SELECT CoUNTC*) FRorM databose_name. tabkname
wHERE loand-name = " apple"

SELECT coUNT (DISTENCT (pt0essa)- brond))


FROM database name. table-name
STD:(standoud euiaíon
VARIANCE
$QL Gutuping 4 Sonting
fpating : (ORDER 6Y)
gind top 5somsung phones withFRoMbiggesT stnecnsize
SELECT model, scsteen -size CompuSX. Smastphones
wHERE bond-nome = " Sam surg
ORDER BY scoreen-size DESC
LIMIT 5

’ using 0«dn by we saxt the column'sceen -s ize in


descending ordun
’Usira LIMIT S, we only get top 5 9tows

2) sost a the phenes n destending amdrq numbon to tal camoag


SELECT model, num-gtont. comHos tnum.suan- comval
AS total camas
FRDM (ampusx.smasphones
OROER BY total-camenos DESC

a) soxthing boscd on multkple calumn


SELECT FROM Campusx. smastphones
ORDER 8Y borand-name ASC, Hating DESC

lisst it wiu be sooted bosed on boronc- nome alghabaticaly


and then bavd on oating in descening to dien in
cach borand.name catugoy
LIMTT 10

LIMÊT I9, 2 s ta tirg tth 1onow, gine 2 sut


whh may now 10 on wiu be oute

GtRouping:GROUp BY)
SELECT botond_name CoUNT (*) As num-o7- phenes
FROM Compusx. Smatphones
GROUP BY bond-name
bxond-na mt
ORDER 8Y num-o-phones DESC Aum-o- fhen
LIMIT5 Ki om 134
Sa msung 132

eg2 SELECT borond-nome, coUNT C) AS uivo


num-phones' Haalime
RoUNO(AVG (pice)) AS 'oug puice' OppO
MAX (Mating) AS 'mox mating'
ROUNO (AVG ( soneen-size),2) AS 'aug sneen size
RoUND (AVG (battony-capocity ) As 'aug battey capauity'
FROM compusN. smatphones
GRoUP BY hnond-nome
ORDER 6Y num-phenes DESC
LIMIT 15 MAH
SELECT has. 5q has 5q ug psucething
AUG (pice) AS 'aug puice', False 3416-S3 66- 164
AVG (matng) AS 'gating Tsue 43200.49 13355
FRDM ampus X. Smaotphones
GROUP BY has 5g
Top S most cestuest phene bnonds

SELECT boondname, RoUNDAUG (pice)) AS aug- psuce


FRoM Campusx. Smasutphones
Rou BY bnondname
ORDER BY aug- pice DESC LTMIT 5
CoUNT ( ) it Counts nO: t0w
Dute

gup Simastghones hy the bnand, Dnd gind the btand with he


highest no.o_modall that haue both NEC ond an IR blaste
SELECT hond nome CoUNT(*) AS'eunt
FROM campusx.smatphaner
WHERE has -nc = TRUE' AND has-i1- baste =TRUE
GROUP BY louname
ORDER 0Y count DESC LIMIT |

90 ind all somung S enabled snantphonet and find out he


pouce jot NEC and Albn- NEC phones
SELECT hac.n{c, AUG Cpice) AS 'auq-pice
FROM campusx Smavthoncs
HERE bondnom samSung
(RoUp 8Y has-nc

HAVING: used to hittoy in GROUP B clause

eg0ind Hhe oug ahing a7 snattphone bonds whch haut mau ton
20 phones.

SELECT lord-ncme,
COUNT (*) AS count!
AuG (9ahing) As 'aug- maing
FROM Cam pusx. Sman tphenes
GRoUP BY brand-name
HAVINÇ Count > 40
oROER SY oug. nahing DE SC
sELECT boordnome, proce S$0- bund (ouT C) AS na phon es,
psunny-comuHa- Hia)) As 'aug comoa otesal uhone
RoUNO (AVG(
FRoM saleohning: smastphenes
qRou eY brandname,pnocei509h-bmand

haue o nepesh nat


caTind top 3 lhsonds with ighest oug nom that than t0 pher
Hz t kost choging ausilable dent congidun hrondl lest
at ost 46
SELECT botand -nomt.
AVG (ro. capacity) AS aug-nam
FROM CampusX -s matphoies
lable = I
wWHERE elreshnat >40 AN0 tust- chaging-ouai
GRouP BY bnond- nome
HAVENG CoUNT ( ) >O
ORDER 6r aug.am' DESC LIMIT 3

Ingoatont Niote : when we haue tb do 4ilteiny hased on


a9gpgat function hen it wiu be done in
HAVENG nd if we haue to do giteing bosd
on naMMal columa value th (0w] then it
wid be den e in HERE Cclause.

+ $QL JorNS
Ajoin is a way to combine data otom two on mane dotabase
tables boseol an a nalatad column betoeen ttem

Lqt Join Right Join Lony Join

Sels Join
Ctoss Join
Ful Join (outo Join
CROSS JOIN :
CAS)
SELECT FROM databose- nome.tble|
+2
CROSS JOIN database-nome. table2 AS

INNER JoIN :

SELECTEROM database-name. table| AS tl


LNNER JoIN da tabose-nome. table-2 AS t2
ON 1. uso-id = t2. user-id

LEFT JOIN :

sELECTFROM datbosenome.table-1 AS tl
LEFT JOIN databost _name.table. 2 AS +2
ON l. uSMid H2.usrid
RIGHT JoIN

SELECT * FROM databose_name. table- 1 AS +I


RIGHT J 0IN datoabo se -nome- table- AS #2
ON l use-id = 42. usn- id
QUTER JorN :(we do nst haue OuTER lay wthd in My Sql,
we haue to use UNTOC, LEFTrTGHT Je
SELECT t FROM database_no me. tablel tI
LEFT 30IN dotboge-name. table2 t2
ON .useid = 42.use-id
UNION
SELECT FROM da talbasename.table
RTGHT JjoIN databosenon.table2 t2
$ET OPERATION :
UNION: the UNTON opra ton is usd to Cambine the mesltr
o two aynaMe SELECT stotements into a single ne sult st.
The UNION openatot mamaucd dupicatewS bw th
yaious SELECT stafements

2 UNION ALL : The UNION ALL op Maton is Similo to the UN ION


bpaton but itdoes nof emoUe dupcatt nows om ths
1esultset

TNTERSECT The TNTERSECT opevafan e kans only the seus


Hhat appean in both sesut sets o two SELECT
statements.

4 EXCEPT : The EXCEPT om MINus opetatost getunns only the desthnc


JnwS that appean inthe linst snesuit sat but nat in tha
setond nesult set a too sELETstatments
SELF JoM Type oy join in which a table is joined with
itselk
SELECT FROM datubafe. name. some- tableFI
LNNER JOLN databasenome. some- table +2
ON l.emtgen y-con tact = t2, usO i
name age emeqg ncy-cenfe s U ]nome ocemnugcny- confac
A A
2
C 2 1
D
14

44
4 3 3
Dote

one (oumn
on mone han
Jpining stdents AS t|
StLECT t FROM sqleoning.
closs AS 42
INMER JOIN sqllemning AMD
ON 1. class-id = 42. class-d
enrollment-yean = #2. closr-y<an

Joining mote than 2 Tables ?

SELECT FROM sqlletining. oncdler-de feuld t1


JoTN sqleasnung
ON L OMdon-id 12. code.id
JOIN sqllecs ning. uss t3
ON 2. use.id = 13. usen.id

Filteung Columns :
Find ondoid name ond city by
joining usou and ordos
sELECT tl.ondonid, 2. name, 2. dty
FROM sqlleahning-ondons tl
30TN sqlac1ning- usens t2
ON t), usu-io
42.usutid
Tind cndenid product
catgony by joining
SELE CT }1.0hden id,2.
eROM uenhcal
salleagining.oxdey-detai
JoTN sqlltaning- cotegony ls+2 t\
ON 1.
categoy-id =
Filteúng Rows
customen Sos to
Tìnd au the omdens placed in lune (aom

SELECT FROM Sqlltconnung. o1de tl


usens t2
JoTN cqlltoininq 42.
oN . usnid = us.id
2.nane = Saite'
WHERE *2. City =Pune' ANO

which is the most proitable


Tind all 1oitable 0ndesed.
seLET +l. 0dm-icl,suM (12.pnoit) categony
FROM sqllecsnungondens I SELECT 2.vonhcal, suM (prot)
JoIM sq' leconing.oNde -de
tils +2 |EROM sqlleaonning-ondo deteuls HI
ON -0nduy.id #2. ondu-id 1J0IN sql kaining.categary t2
RoUP 6Y tl. oMdunid |ON . cotegay-id = t2. categay-id
HAULNG suM 42- pnoit) >0 qROUP eY 2.uentical
OROER BY sUM (proit) OESC LEMIT
Qind the customun who hus placed iewhich is the most pnoitabe
Ahe maximum no. o ond1S state
SELECT nome, (ouNT ( )AS 'num-odos' SELECT stute, SUM(prokit)
EROM sallecnningodes t| FROM sqllkaning. ovds t
JoTN sallacnning. usens t2 J0IN sqlleaoining-onde.de tw'lt #
ON H.usn-id - 2. usonid ond +1. o9dnid = +2. ondid
ROUP Y t2.name JOIN sqlleasning.uses t3
ORDER BY num- 031 dens DESC ON H.usenid = 43. usen-id
LLMIT GROUP BY stete
Tind al cotesosues with poiaits OROER BY sUM(progt) 0¬SC
highen than 3000 LIMLT

SELET 32-vwtica sUM(paoit) FROM sqlleamning.cadendeteils 4l


JoTN salleasning . categony +2 ON Hl. cotegcny-id =A2. categohy -idl
HAUCMG suM (hot) ) 3oo0
fubquezics witinanathth
ItAsabquay is 2 qung
isa sELECT chtement that is aested (nside anoth
statemmet.
SELECT, IMSERT Ur DATE, an DELETE

inst and iti nesut s


the subquany is exeuted hen used
Find the híghest mated mowie
SELECTtFRoM Mouíes.mouie
wHERE staste (sELECT MAX (sL ne) FRoM Moua, miujal

Tyges OF Subqucwes
Bosed on :
) The mesult it utuns
Retned Data
Scala kow
sabquey Subquny subqut
hosaoy
iennes
husue 6-1
te manu
iachen 1-6

2 Based on
woniny
tooalated
he innet ot quwwy ane
in dapendat om eoch othe
They an getexcuteo uy cant gt exe tel sepavaltuy
Sepoonately.
Indigendent SubauIS Scalan Subquy

Tind the molie wth highest pnoit


SELECT* FROM mowes
(gmorr- budget)
wHERE (qxocs - budget) =( sELECT MAX
FROM mues) i

Find how mony mewies haue a narhng he auteage o al the


meu'e natiaqs (Zind the count o abaue auraaz melies
SELECT FROM mBwes
wHERE sceste > ( SELECT AUG (scase) FROM mouies)

Maw to nd count e such mouwes


sELET CoUNT () FeoM mouwes
wWHERE ScONe > ( seLET AUG (scene) FrKorM melaes)

Find the highest atd mmewe of the yean Doo0


SELECI * FRoM mowes
wHERE O 2000 AND suoe =( SELET MAX (sL are )

HERE yeor = 2o00

Find the highest yatd mouie among all mouwer whose


numben of
wotw ane >the daaset ag uotes.
SELECT+ FROH mowes
wHERE scate = ( sELE CT MAX( sCote) FeDM moues
wHERE Vo tes > (sELELT AUG Cvotes)
PgoM mawies)])
Row SubquuyOne
Tadajendent Subquy
neue 01dcned.
Eind allthe use who
SELECT FROM usus
SELECT
WHERE uset_d NOT IN/
DTSTTT
FROM on dans)

Find all the mouies mads by top 3


to tad guossincome) dinectons.(in
SELECT* FROM mo\ues
WHERE diecto IU SELETdecta
PROM mowes
G-ROUP BY dectay
OROER BY soM(qMOSs) DES
LLMIT 3)
C Using cTE (ommon table expnesion)
wITH top- dinectonS AS SELET dinecHo
fROM mowes
CROUP BY dorecto
oROER BY SUM(qnos) DESC
LTMIT 3)
SELECT t FROM moues
wHERE dinecto PAN (sELECT teROM top- dinect
hind all mBuies al ath tHhost actans whose ilinogaphy I
oug naing5(tale 2So00 voter af uto )
SELECT *FROM mbwes
wHERE stan IN ( sELECT stanFR0M mewes
WHERE Votes > 2so00
cfoUp Br stan
MAUIMG AUG(scCee) >-5)

Trdapendent Subquny Table Subquwy (hulh a| Multi Row


ird the most poitabs maue a each yeaM
SELECT FROM mouies
WHERE (yas, gnos -budget) INSELECT yeas, MAXr-budat
FROrM mouies

Find the hiahesf natd mBue al eoch genMe,uo fes


25000". autot t
StLECT * FROM moies
wHERE (gensne, suone) IN (StLECT gen9ne, MAX(Sa1e)
FeOM mouies
wHERE uotes 2So00
Gpoup BY genne )
AN0 uotes > 2soo0
elAcSkute
Dste
Poge

find the highest grasting maueí o top 5ecteon)


3
Combo in tmf o totol qoosl inLonme dinectn
WITH t- duos AS
SELECT sto, dnectan, MAX (gt0ss
FROM melwes
CHROUP BY st, dinecto
ORDER Br sUM(g0s) DESC LIMLT S
SELECT FROM mowes
wHERE (st, dinectan, quosc) IN SELECT TFROM top- dui

Coseloted Subgquny :
The innot quony can't be esuted seqonately, it nquu
the outin quy ton eKeution
Find all he moli'es that haue a nakng hghn than th
auag ahng of mauiei in the same que
SELECT * FROM molies ml
wHERE SCome >(sELGCT AVG (Scane) pRoM moues m2
wHERE m2.gensu - ml.gnae)

Find the auousute Lod of each ustomen


WETH fa-foood AS(
SELECT t2.usOid, nome. k-no me, CouNT()AS 6uguen
F2OM usS tl
J0IN oMduys t2 ON t.uset-id = 42.usey_id
JoTN otday- de tail ç+3 ou t2. oMdid =t3.01du-10
wlindow tun chens
sELECT AVG (maues)
OUER (PARTITION 6Y bronch
FROM ampusy-manKs

manls AVE (mank) ouER( PARTETICu


Student-d bnonh

13 74
A
14 14

C c SE 15 14
32
92 $2
ECE 83 82
2 MECH S2

MECH S2

MECH 53 52

Tind all the students who haue mans highen than the aug manl
o theim nespec hiue bnanch
SEE SELECT * FROM sELECT #

AUG (naKs) oueR( ART E1LOU BY branch )


AS 'bronch- aug
FROM wm ans\AS f
wHE KE t.manlss > t. bManch aug
RANIC DENSE_RAUK RowNUmGER
RAUIK DEMSË -RHNK

3 2
Dgte

SELE CT+
RANK C) oUER (taRTITION 6Y byanch ORDER BY maaks DEsc)
DEAISE-RANK () DUERPARTLIION 8Y branch oROER BY
FROM mAnKS
mas DE
SELECT+
RowNUM6ERC) OU ERARTITION 8Y bhonch
FROM manls

studentid nome bronchme Row.wUM8ER C) OVER

32 2
C 3
3 ECE 64
2
EcE 63 2

MBUM
MECH S 2
S 13
MECH 3
MECH 92 4

+ FIRST- VALVE / LAST. VALUE/NTH-VALUE


SELECTt
FIRSTVALUE (nome) OvER OROER GY maks pESC)
FROM maks
> This qusry inst sot the th data in
descendi'ng odn o
masky then sclect the finst vaue ol none coumn
snd displauys it al ten wy no
LAST- VALVE:

sELE CT
LAST-VALUE (mawks ) ouER ORDER 6Y manks DESC
RowS BETWEEN ON BoUNOED
PRECEDING AND UNBOUNOED FoLLOwIE
FROM mcos

NTH_ VALU6 :

SELECT,
NTH- VALO¬ nome, 2) ouER/PARTITTON 8Y bnonch
ORDER 8Y monks DESC
ROws BETWEEN UuROUNDED
PRECEDINE AND UN BOVNOE) PoLLOwDu
FROM mascks

Hhis quuy wiu giue mname o 2n0 tap pem eucny bron
Studentid name banch movs NTH-Ua
CSE B
2 B cSE
3
4 CSE
¬CE
6
¬CE
ECE 10
61 J
MECH S J
MEUY
2 " 44
LAG)
SELECT
LAG (mass) ovER (ORDER8Y studentid
FROM madls

nome branth moKs


Stdantid
LAlNULr(maslls
2 al 82
3 61
EC 67
S ME 13 6|
ME 13

LEAD C)
SELE CT 4
LEAO (madks) oVER(oRDEK BY shudent-id)
FROM maul f

shudentid nme bytanch mcuuls


LCD (modcs
A 82
2
CS
67
C
67 61
4 D
61 13
S
ME 73
F ME
NULL
Windew unchon use coses ;

Ranking
Tind MoM qrowth nate aq Zomato
SELE CT MONTHNAME(dote),suM (omount],
tsuM(amount)-LA 4(sum(omount)) au ER (OROER BY MouH(dsy)
FROM o91dens
GROUP BY MOLTHNAME Cdate)
SRDER BY MONTH (dote) ASC
MopTHNAMC(dotu) sunomount)
May 2425 Nul
June 3220 32-1835
4845 So. 465?

3de Ahame fnom qaculty whcae hname iKe/.A/


name bsan chN sal Oy
ABC 50005
2

Many ee
NVLL
Smi4h MULL
fech al the de aue o the shededs studyingin. an dup
wwhydatment hey a utteYC antnen

You might also like