0

Something is wrong with statements with datetime field:

MyDB:

id  name   datetime
1   test1  2011-04-28 19:37:44
2   test2  2011-04-28 21:27:04

When I run the following statement

SELECT * 
FROM myTable 
WHERE ('datetime' > '2011-04-28 21:00:00')

I get all - test1 and test2

When I run this statement

SELECT * 
FROM myTable 
WHERE ('datetime' = '2011-04-28 21:27:04')

I get nothing

When I run the following statement

SELECT * 
FROM myTable 
WHERE ('datetime' > '2011-04-28 21:00:00')
    AND ('datetime' < '2011-04-29 21:00:00')

I get nothing

Why?

1
  • are you sure your datetime field is a real datetime field, and not varchar? What db are you using? Commented Apr 28, 2011 at 20:14

4 Answers 4

1

You are putting the field name "datetime" into quotes and MySQL treats it as a string, not a column.

SELECT * FROM myTable WHERE datetime > '2011-04-28 21:00:00';
Sign up to request clarification or add additional context in comments.

1 Comment

+1 Actually every DBMS treats 'datetime' as a string literal and datetime as a column name.
1

You are doing string comparisons, i.e. comparing the string "datetime" to a certain date.

Change your query to

...WHERE ([datetime] = '2011-04-28 21:27:04')

Comments

0

Remove the quotes around the column name:

SELECT * FROM myTable WHERE (datetime > '2011-04-28 21:00:00')

In your query, you are comparing the string "datetime" against another string, consisting of numbers.

Alphanumerically, numbers come before letters, so the "datetime" string is greater than the numeric date string you are comparing against.

Comments

0

Are you actually putting the datetime column name in single quotes? If you are, it means you are comparing the string 'datetime' to the string '2011-04-28 21:00:00' which doesn't make much sense. In SQL, if something is surrounded in single quotes it is usually a string literal.

Have you tried:

SELECT * FROM myTable WHERE datetime > '2011-04-28 21:00:00'

Or more likely:

SELECT *
FROM myTable
WHERE datetime > to_date('2011-04-28 21:00:00','YYYY-MM-DD HH24:MI:SS');

Note: That to_date function and the format string are specific to Oracle, you did not specify which database you are using and these functions tend to be db-specific.

Comments

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.