tags:

views:

187

answers:

8

I have a datetime column in a MySQL table and I'd like to select records that have the same year, month, and day (but perhaps different hour and minutes). In other cases, I'd select ones with the same year and month. Is there a way to do that?

A: 

I've seen a date conversion done this way before in SQL server (not sure if this works in MySQL):

select convert(varchar(10), getdate(), 120)

(This is just an example of how to convert the date into just YYYY-MM-DD)

Andy White
A: 

There are functions like year() and hour() that will do this for you.

 select * from users where year(lastlogin) = year(now())
Tom Ritter
+6  A: 

You can use some of the MySQL Date and Time Functions to extract/compare the parts of the date you're interested in.

SELECT * FROM table WHERE DATE(datetime1) = DATE(datetime2);

SELECT * FROM table WHERE YEAR(datetime1) = YEAR(datetime2) AND MONTH(datetime1) = MONTH(datetime2)

etc
Chad Birch
this isn't a good way to do it because you won't be able to use an index on datetime1
Greg
@RoBorg, but when you want to, say, find all the ones with the same day and month regardless of the year (like anniversary dates), this method is really your own choice.
Paul Tomblin
@Paul Tomblin very true, although in those cases you might be better having separate columns for the year/month/day
Greg
this would have been my answer
bjeanes
A: 
SELECT
  foo
FROM
  FooTable
WHERE
  DATEADD(dd, 0, DATEDIFF(dd, 0, TheDate)) = DATEADD(dd, 0, DATEDIFF(dd, 0, @SomeDate))

This: DATEADD(dd, 0, DATEDIFF(dd, 0, TheDate))

  • calculates the date (in days) difference from date 0
  • adds the result (in days) to date 0

effectively setting the time part of a DATETIME value to 00:00:00, without the need to do string conversion or such.

Tomalak
+10  A: 

The fastest way to do this is using BETWEEN, for example:

SELECT fields FROM table WHERE
datecolumn BETWEEN '2001-01-01 00:00:00' AND '2001-12-31 23:59:59';
Greg
Fast - but hard to get the SQL written correctly. Fast because it can use indexes if they're available.
Jonathan Leffler
ummm, why exactly is it hard to get the SQL written correctly?
Sujoy
A: 

I know I'm leaving off the time, but the concept is the same... assume datetime is like: 12/25/2009

SELECT * FROM table
WHERE SUBSTRING(datetime, 6, 4) = targetYear
AND SUBSTRING(datetime, 0, 2) = targetMonth
42
A: 

Yes, you want to use one of the following date functions in your selection

Noah
A: 

You can also do

SELECT * FROM table WHERE datetime LIKE '2008-08-01%'

or

SELECT * FROM table WHERE datetime LIKE '2007-05%'
Paulo
OMG NO, please no! Using string conversions (this uses an implicit CAST/CONVERT, but it still uses one) is so Very inefficient. It also forces a table scan as this will destroy the optimiser's ability to use Any indexes available.
Dems