Professional Documents
Culture Documents
Fetching Records Between Two Date Ranges
Fetching Records Between Two Date Ranges
Fetching Records Between Two Date Ranges
WecancollectrecordsbetweentwodatefieldsofatablebyusingBETWEENquery.Wecanusethistoget
recordsbetweentwoyearsorbetweentwomonth.Wecancombineallthisandtryforgettingrecords
betweentwodateranges.
Betweentwoyears
Wewillfirststartwithdisplayingrecordsbetweentwoyears.Beforethatyoucanreadonhowtogetyear
partfromadatefield.Nowletustrytogetrecordsbetweenyear2004and2005.Hereisourquery
SELECT*FROM`dt_tb`WHEREyear(dt2)between2004and2005
INtheabovequerydt2isourdatefieldandintheresultboththeyears2004and2005willbeincludedinour
records.
Betweentwomonthranges.
RelatedTutorialDateDifferenceLast15daysrecordRecordsoflast10minutesBetweenarangeofRecords
Nowletuscollecttherecordsbetweentwomonths.Notethatifweareusingonlymonthinourbetween
commandthenforanyyeartherangeofmonthwespecifiedwillbereturnedbythequery.Forexampleifwe
askforrecordsbetweenFebandAugmonthsthenwewillgetrecordsofbetweenthemonthFebandAugfor
alltheyears.Hereistheexample.
SELECT*FROM`dt_tb`WHEREmonth(dt)between'02'and'08'
TheabovequerywillreturnusrecordsofallthemonthsbetweenFebruaryandAugustofanyyear.Wecan
specifytheyearalsoalongwiththemonthslikethis
SELECT*FROM`dt_tb`WHEREmonth(dt)between'02'and'08'andyear(dt)between2004and2005
Therearemoredetailsonhowtogetthemonthpartofanydatefieldhere.
Betweentwodateranges
Nowletusmovetoselectarangeofrecordsbetweentwodates.Hereisthesqlforthis
SELECT*FROM`dt_tb`WHEREdtBETWEEN'20050101'AND'20051231'
DateFormattouseinquery
Youhaveseenwehaveused'Ymd'dateformatinourquery.Wemaynotgetdataalwaysinthisformatso
hereisthePHPcodetoconverttothisformatbeforeusinginsideaquery.
$date=newDateTime($dt2);
$dt2=$date>format('Ymd');
Similarlyyoucanchangevariable$dt1tonewdateformat.
Nowwecanuseinsideourquery.
SELECT*FROM`dt_tb`WHEREdtBETWEENBETWEEN'$dt1'AND'$dt2'
GenerateQuerybyusingdatesfromCalendar
DEMOofhowdateisusedtocollectrecords
HereisthecodeforSQldumpofthefiletocreateyourtablefortesting.
CREATETABLEdt_tb(
idint(2)NOTNULLauto_increment,
dtdatetimeNOTNULLdefault'0000000000:00:00',
dt2dateNOTNULLdefault'00000000',
PRIMARYKEY(id)
);
#Dumpingdatafortable`dt_tb`
INSERTINTOdt_tbVALUES(1,'2004102600:00:00','20050125');
INSERTINTOdt_tbVALUES(2,'2004050523:56:25','20050612');
INSERTINTOdt_tbVALUES(3,'2005120813:20:10','20050606');
INSERTINTOdt_tbVALUES(4,'2003052600:00:00','20071218');
INSERTINTOdt_tbVALUES(5,'2007121800:00:00','20030816');