0

I have simple problem with SQL query.. I would like to search fields, where dates begin and ends in specific date and time.

Field is defined as CHAR and have structure: DD.MM.YYYY hh:mm:ss and I cannot change it.

I tried to declare some variables and search by this, also tried by Converting.

This is what I tried and didn't work:

SELECT date FROM table WHERE date BETWEEN '1.01.2017 00:00:00' AND '1.02.2017 23:59:59'

SELECT date FROM table WHERE date >= '1.01.2017 00:00:00' AND date <= '1.02.2017 00:00:00'

SELECT date FROM table WHERE date >= Convert(DATETIME, '1.01.2017', 104) AND date <= Convert(DATETIME, '1.02.2017', 104)

Always after this query I get all dates, not this what I asked.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Frihu
  • 43
  • 9

3 Answers3

0

Your field is not in a format that can be compared lexicographically as strings, so you need to convert it to a date. But it's not in the format that MySQL can parse by default (it expects dates in the format YYYY-MM-DD). So use STR_TO_DATE() to parse it with a format string.

SELECT date
FROM table
WHERE STR_TO_DATE(date, '%d.%m.%Y %H:%i:%s') BETWEEN '2017-01-01 00:00' AND '2017-01-02 23:59:59'
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

I solved my problem. Problem was with that HOW this fields are storage in DB. I thought that they are storage like: DD.MM.YYYY hh:mm:ss, but it was only structure. In DB they are storage like: YYYYMMDDhhmmss and after changes in WHERE query line it works.

SELECT date FROM table WHERE date >= '20170101000000' AND date <= '20170101235959'
Frihu
  • 43
  • 9
-1
SELECT date FROM table WHERE STR_TO_DATE(date, '%d.%m.%Y %H:%i:%s') BETWEEN '2017-01-01 00:00:00' AND '2017-02-01 23:59:59'

OR

You can use STR_TO_DATE() function.

SELECT date FROM table WHERE STR_TO_DATE(date, '%d.%m.%Y %H:%i:%s') BETWEEN STR_TO_DATE('1.01.2017 00:00:00','%d.%m.%Y %H:%i:%s') AND STR_TO_DATE('1.02.2017 23:59:59','%d.%m.%Y %H:%i:%s')

You can try above query.

halfer
  • 19,824
  • 17
  • 99
  • 186
Sagar Gangwal
  • 7,544
  • 3
  • 24
  • 38