Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL like clause for dates

Tags:

date

sql

select

I am querying a db to get all blog posts from a certain month of a certain year. The date is stored in the database as YYYY-MM-DD

What is the best foolproof method of getting only the posts of a certain day and year? I have tried chaining like clauses, but I've come to realise a few ways in which they would fail, for example if I used the statement:

'SELECT * FROM entries WHERE date LIKE \''.$year.'%\' AND date LIKE \'%'.$month_no.'%\''

This would fail if the month number happened to be contained within the last 3 digits of the year number. Would I have to use regex and if so, could anyone suggest a statement I could use?

like image 820
Inigo Avatar asked Jul 27 '26 21:07

Inigo


1 Answers

Please.. just use a date filter. It will help performance (use an index)

$query = "SELECT *
FROM entries
WHERE date >= '" . $year . "-" . $month_no . "-01'
  AND date <  adddate('" . $year . "-" . $month_no . "-01', interval 1 month)";

That was for MySQL. For SQL Server, use something similar, but use DATEADD instead

...
WHERE date >= '$year" . $month . "01'
  AND date <  DATEADD(month,1,'$year" . $month . "01'";

The reason for adding one month is that it is easier to handle the case when month is 12 (December).

like image 51
RichardTheKiwi Avatar answered Aug 04 '26 05:08

RichardTheKiwi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!