0

I have this query

SELECT * FROM tracklogs.sms_outbound
WHERE gsmno = 'rk4@*******.com.ph'
AND cdate > cast('2013/11/14 09:44:48 PM' as datetime)

where cdate format is in %Y-%m-%d %h:%i:%s %p.

I have tried converting the date into that format then cast it as datetime but still doesn't working.

3
  • you shouldn't need to cast it. MySQL recognizes strings as dates if they are in ISO format. You may need to convert your 9:44 PM to 24-hour time though. Commented Nov 17, 2014 at 1:28
  • What version of MySQL? Before 5.6.4 fractional seconds weren't supported in DATETIME variables. What is the data type of cdate? Commented Nov 17, 2014 at 1:37
  • cdate is in date format %Y-%m-%d %h:%i:%s %p. Commented Nov 17, 2014 at 1:45

2 Answers 2

2

Use STR_TO_DATE() to correctly convert the datetime literal you have provided to a proper DATETIME value. It seems that your cdate column is a char() or varchar() column. So you will also need to convert that to DATETIME to compare it.

What you need is this:

That works like this (http://sqlfiddle.com/#!2/d41d8/48741/0)

STR_TO_DATE(cdate, '%Y-%m-%d %h:%i:%s %p') >
 STR_TO_DATE('2013/11/14 09:44:48 PM', '%Y/%m/%d %h:%i:%s %p')

Converting these strings to DATETIME data items ensures that the comparison handles both the date and the time correctly. See this fiddle (http://sqlfiddle.com/#!2/d41d8/48743/0)

But, you should consider changing your cdate item to a DATETIME, because then you'll be able to index it and speed up your search.

Sign up to request clarification or add additional context in comments.

Comments

-1
SELECT * FROM tracklogs.sms_outbound 
WHERE gsmno = 'rk4@*******.com.ph' 
AND UNIX_TIMESTAMP(str_to_date(cdate,'%Y-%m-%d %H:%i:%s')) > UNIX_TIMESTAMP('2013-11-14 09:44:48')

4 Comments

but the greater then operator doesn't work with the time
Ummm, you lost the PM in this answer.
please try @user3094947
I recommend explaining what your code snippet does.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.