120

I want to compare a date from a database that is between 2 given dates. The column from the database is DATETIME, and I want to compare it only to the date format, not the datetime format.

SELECT * FROM `players` WHERE CONVERT(CHAR(10),us_reg_date,120) >= '2000-07-05' AND CONVERT(CHAR(10),us_reg_date,120) <= '2011-11-10'

I get this error when I execute the SQL above:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'us_reg_date,120) >= '2000-07-05' AND CONVERT(CHAR(10),us_reg_date,120) <= '2011-' at line 1

How can this problem be fixed?

Cœur
  • 37,241
  • 25
  • 195
  • 267
NVG
  • 3,248
  • 10
  • 40
  • 60

5 Answers5

112

You can try below query,

select * from players
where 
    us_reg_date between '2000-07-05'
and
    DATE_ADD('2011-11-10',INTERVAL 1 DAY)
Tadeck
  • 132,510
  • 28
  • 152
  • 198
Nik
  • 4,015
  • 3
  • 20
  • 16
105

That is SQL Server syntax for converting a date to a string. In MySQL you can use the DATE function to extract the date from a datetime:

SELECT *
FROM players
WHERE DATE(us_reg_date) BETWEEN '2000-07-05' AND '2011-11-10'

But if you want to take advantage of an index on the column us_reg_date you might want to try this instead:

SELECT *
FROM players
WHERE us_reg_date >= '2000-07-05'
  AND us_reg_date < '2011-11-10' + interval 1 day
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • 1
    I appreciate your consideration of taking advantage of the index. I think the query should not have the "+ interval 1 day" clause. – Jurgenfd Dec 14 '16 at 08:58
15

This works:

select date_format(date(starttime),'%Y-%m-%d') from data
where date(starttime) >= date '2012-11-02';

Note the format string %Y-%m-%d and the format of the input date. For example 2012-11-02 instead of 12-11-2.

Rahatur
  • 3,147
  • 3
  • 33
  • 49
7

I got the answer.

Here is the code:

SELECT * FROM table
WHERE STR_TO_DATE(column, '%d/%m/%Y')
  BETWEEN STR_TO_DATE('29/01/15', '%d/%m/%Y')
    AND STR_TO_DATE('07/10/15', '%d/%m/%Y')
peterh
  • 11,875
  • 18
  • 85
  • 108
Gurjeet Singh
  • 103
  • 2
  • 6
4

this is what it worked for me:

select * from table
where column
BETWEEN STR_TO_DATE('29/01/15', '%d/%m/%Y')
 AND STR_TO_DATE('07/10/15', '%d/%m/%Y')

Please, note that I had to change STR_TO_DATE(column, '%d/%m/%Y') from previous solutions, as it was taking ages to load

Iria
  • 433
  • 1
  • 8
  • 20