Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select date range on mysql timestamp

Tags:

sql

mysql

I am trying the following but get no results:

SELECT *
FROM users_test
WHERE dateadded >= UNIX_TIMESTAMP('2012-02-01 00:00:00') 
AND dateadded <  UNIX_TIMESTAMP('2012-11-01 00:00:00');

Yet I know there are columns with dates within that range e.g.

2012-05-11 17:10:08

Is there a better way to do this?

Eventually I want to search multiple parameters, albeit not at the same time, like today, yesterday, last week, last month etc and also a date range and month range

like image 317
StudioTime Avatar asked Nov 16 '12 14:11

StudioTime


People also ask

How do I select a date range in MySQL?

If you need to select rows from a MySQL database' table in a date range, you need to use a command like this: SELECT * FROM table WHERE date_column >= '2014-01-01' AND date_column <= '2015-01-01'; Of course you need to change: table.

How do I create a timestamp range in SQL?

SELECT * FROM users_test WHERE dateadded >= UNIX_TIMESTAMP('2012-02-01 00:00:00') AND dateadded < UNIX_TIMESTAMP('2012-11-01 00:00:00');

How do I select a date from a timestamp in SQL?

In MySQL, use the DATE() function to retrieve the date from a datetime or timestamp value. This function takes only one argument – either an expression which returns a date/datetime/ timestamp value or the name of a timestamp/datetime column. (In our example, we use a column of the timestamp data type.)

How do I pass a date range in SQL query?

SELECT * FROM PERSONAL WHERE BIRTH_DATE_TIME BETWEEN '2000-01-01 00:00:00' AND '2002-09-18 12:00:00';


2 Answers

Have you tried?

SELECT *
FROM users_test
WHERE dateadded >= '2012-02-01 00:00:00'
AND dateadded <  '2012-11-01 00:00:00'

For what I can see, it seems your table has the data stored in the same way you want to look for it (2012-05-11 17:10:08), so in this case you won't need UNIX_TIMESTAMP.

Also I can see you want to exclude the 2nd date from results (because you're using < instead of <=), otherwise using WHERE dateadded BETWEEN '2012-02-01 00:00:00' AND '2012-11-01 00:00:00' would be fine as well...

like image 158
DarkAjax Avatar answered Sep 20 '22 15:09

DarkAjax


Just use the SQL BETWEEN keyword. That's all.

like image 45
RTB Avatar answered Sep 19 '22 15:09

RTB