Professional Documents
Culture Documents
SQL BETWEEN Command To Fetch Records From A Range
SQL BETWEEN Command To Fetch Records From A Range
Manytimeswemayrequiretofindoutrecordsbetweenarangeofvalue.Wecanspecifyoneupperlimit
andonelowerlimitandthequeryshouldreturnalltherecordsbetweenthesetwovalues.ThesqlBETWEEN
commandwillgiveustherequiredresultinallthesecases.WewillapplyhereBETWEENcommandtoa
numericfieldandseehowtherecordsarereturnedfromaMysqltable.Hereisourtable.
id
name
class
mark
sex
JohnDeo
Four
75
female
MaxRuin
Three
85
male
Arnold
Three
male
KrishStar
Four
60
female
JohnMike
Four
60
female
AlexJohn
Four
55
male
FullstudenttablewithSQLDump
OnthistablewewillapplyourBETWEENcommandtogetalltherecordswithinsomeupperandlower
limits.Sayourupperlimitis75andlowerlimitis60.Sowewillgetalltherecordswithintheselimitsand
pleasenotethatlimit60and75bothareinclusive.HereisoursqlBETWEENcommand.
SELECT*FROM`student`WHEREmarkBETWEEN60and75
id
name
class
mark
sex
JohnDeo
Four
75
female
KrishStar
Four
60
female
JohnMike
Four
60
female
18
Honny
Five
75
male
20
Jackly
Nine
65
female
21
BabbyJohn
Four
69
female
34
GainToe
Seven
69
male
Youcanseewehavealltherecordsbetween60and75(bothinclusive).
Pleasenotethatwehavetofirststartwithlowerlimitandthenupperlimit.Sotherecordsbetween60and
75willbedisplayed(NOTBETWEEN75and60)
Displayingfromhighesttolowestmark
Usingorderbywecanchangetheabovedisplayandshowfromhighesttolowest
SELECT*FROM`student`WHEREmarkBETWEEN60and75orderbymarkdesc
Outputishere
id
name
class
mark
sex
JohnDeo
Four
75
female
18
Honny
Five
75
male
21
BabbyJohn
Four
69
female
34
GainToe
Seven
69
male
20
Jackly
Nine
65
female
KrishStar
Four
60
female
Displayingfromoneclassonly
Wewillrestrictthestudentsofclassfouronly
SELECT*FROM`student`WHEREmarkBETWEEN60and75ANDclass='Four'
id
name
class
mark
sex
JohnDeo
Four
75
female
KrishStar
Four
60
female
JohnMike
Four
60
female
21
BabbyJohn
Four
69
female
DisplayingfromlimitedclassusingIN
OnlyfromClassFourandClassSeven
SELECT*FROM`student`WHEREmarkBETWEEN60and75ANDclassIN('Four','Seven')
id
name
class
mark
sex
JohnDeo
Four
75
female
KrishStar
Four
60
female
JohnMike
Four
60
female
21
BabbyJohn
Four
69
female
34
GainToe
Seven
69
male
DisplayingfromlimitedclassusingNOTIN
SELECT*FROM`student`WHEREmarkBETWEEN60and75ANDclassNOTIN('Four','Seven')
id
name
class
mark
sex
18
Honny
Five
75
male
20
Jackly
Nine
65
female
Numberofstudentsfromeachclass
Howmanynumberofstudentshavesecuredmarkbetween60and75ineachclassbyusingGROUPBY
SELECTclass,count(id)asnoFROM`student`WHEREmarkBETWEEN60and75groupbyclass
class
no
Five
Four
Nine
Seven
Selectingrecordsbetweentwodateranges