Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL timestamp select date range

Not sure really where to start with this one. Can anyone help/point me in the right direction.

I have a timestamp column in MySQL and I want to select a date range for example, all timestamps which are in Oct 2010.

Thanks.

like image 530
DRKM Avatar asked Oct 20 '10 10:10

DRKM


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

Usually it would be this:

SELECT *    FROM yourtable  WHERE yourtimetimefield>='2010-10-01'    AND yourtimetimefield< '2010-11-01' 

But because you have a unix timestamps, you'll need something like this:

SELECT *    FROM yourtable  WHERE yourtimetimefield>=unix_timestamp('2010-10-01')    AND yourtimetimefield< unix_timestamp('2010-11-01') 
like image 137
Wouter van Nifterick Avatar answered Oct 04 '22 09:10

Wouter van Nifterick


A compact, flexible method for timestamps without fractional seconds would be:

SELECT * FROM table_name  WHERE field_name  BETWEEN UNIX_TIMESTAMP('2010-10-01') AND UNIX_TIMESTAMP('2010-10-31 23:59:59') 

If you are using fractional seconds and a recent version of MySQL then you would be better to take the approach of using the >= and < operators as per Wouter's answer.

Here is an example of temporal fields defined with fractional second precision (maximum precision in use):

mysql> create table time_info (t_time time(6), t_datetime datetime(6), t_timestamp timestamp(6), t_short timestamp null); Query OK, 0 rows affected (0.02 sec)  mysql> insert into time_info set t_time = curtime(6), t_datetime = now(6), t_short = t_datetime; Query OK, 1 row affected (0.01 sec)  mysql> select * from time_info; +-----------------+----------------------------+----------------------------+---------------------+ | 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34 | +-----------------+----------------------------+----------------------------+---------------------+ 1 row in set (0.00 sec) 
like image 31
cEz Avatar answered Oct 04 '22 07:10

cEz