MySQL timestamp select date range - mysql

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.

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')

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)

I can see people giving lots of comments on this question. But I think, simple use of LIKE could be easier to get the data from the table.
SELECT * FROM table WHERE COLUMN LIKE '2013-05-11%'
Use LIKE and post data wild character search. Hopefully this will solve your problem.

SELECT * FROM table WHERE col >= '2010-10-01' AND col <= '2010-10-31'

This SQL query will extract the data for you. It is easy and fast.
SELECT *
FROM table_name
WHERE extract( YEAR_MONTH from timestamp)="201010";

Whenever possible, avoid applying functions to a column in the where clause:
SELECT *
FROM table_name
WHERE timestamp >= UNIX_TIMESTAMP('2010-10-01 00:00:00')
AND timestamp < UNIX_TIMESTAMP('2010-11-01 00:00:00');
Applying a function to the timestamp column (e.g., FROM_UNIXTIME(timestamp) = ...) makes indexing much harder.

If you have a mysql timestamp, something like 2013-09-29 22:27:10 you can do this
select * from table WHERE MONTH(FROM_UNIXTIME(UNIX_TIMESTAMP(time)))=9;
Convert to unix, then use the unix time functions to extract the month, in this case 9 for september.

Related

Restrict TIME data type in mysql to hold only till 24:00:00 hrs

Actually i am using MySql 5.6.4 version.But the problem is that MySQL retrieves and displays TIME values in 'hh:mm:ss' format (or 'hhh:mm:ss' format for large hours values).
TIME values may range from '-838:59:59' to '838:59:59'. The hours part may be so large because the TIME type can be used not only to represent a time of day (which must be less than 24 hours), but also elapsed time or a time interval between two events (which may be much greater than 24 hours, or even negative).
I want to restrict TIME data type in mysql 5.6.4 version to hold only till 24:00:00 hrs, so if will insert the time which is greater than 24:00:00 then it will show error message.
I have googled a lot for this but i didn'yt find anything although i am bit confused... I just want to know How can i do it?
Insert into exp1.mock_table (reviewTime, created_dt) VALUES ('37:00:00', NOW());
Insert into exp1.mock_table (reviewTime, created_dt) VALUES ('22:01:53', NOW());
alter table exp1.mock_table modify reviewTime time(0) , add check (extract(hour from reviewTime) between 0 and 24);
If you are using MySQL 8+, then you may handle this using check constraints when you define your table:
CREATE TABLE mock_table (
reviewTime time CHECK (HOUR(time) < 24)
created_dt datetime
);
Technically a 24 hour day doesn't support 24:00:00, because 23:59:59 automatically wraps around to 00:00:00 of the next day.
Not sure if this is what #strawberry had in mind but you could test the time and force burst it
drop table if exists t;
create table t
(ts time);
insert into t values (if('20:00:00' > '23:59:59','840:00:00','20:00:00'));
Query OK, 1 row affected (0.02 sec)
insert into t values (if('37:00:00' > '23:59:59','840:00:00','820:00:00'));
ERROR 1292 (22007): Incorrect time value: '840:00:00' for column 'ts' at row 1
select * from t;
+----------+
| ts |
+----------+
| 20:00:00 |
+----------+
1 row in set (0.00 sec)
Consider the following:
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table (id SERIAL PRIMARY KEY, t TIME NOT NULL);
INSERT INTO my_table (t) SELECT '22:23:00' FROM (SELECT 1) n WHERE TIME_TO_SEC('22:23:00') BETWEEN 0 AND 86400;
INSERT INTO my_table (t) SELECT '212:23:00' FROM (SELECT 1) n WHERE TIME_TO_SEC('212:23:00') BETWEEN 0 AND 86400;
SELECT * FROM my_table;
+----+----------+
| id | t |
+----+----------+
| 1 | 22:23:00 |
+----+----------+

Selecting all rows before a given time in SQL

I have a fairly simple SQL table (using MYSQL Workbench 8.0) where the rows of the table contain dates and values like so:
date | value
--------------------|----------
2018-09-06 18:00:00 | 73
Values in the date column range from %18:00:00 to %17:30:00.
All I would like to do is return results from a query where I exclude all rows where the time in the date column is before 17:00:00.
The query I am currently using to no avail is:
SELECT * FROM table_name where td_time <> '%17%'
For reference, the values in column 'date' are formatted as type datetime.
I believe I'm missing something fairly simple, but this is my 2nd day using SQL and I cannot figure out if I am missing a small nuance to the syntax.
There are many function in MySQL to process time and date value, you can do like this:
select * from table where hour(date) < 17 and hour(date) > 17
Or
select * from table where time(date) < '17:00:00' and time(date) > '18:00:00'

Converting sql number to date [duplicate]

I want to convert a timestamp in MySQL to a date.
I would like to format the user.registration field into the text file as a yyyy-mm-dd.
Here is my SQL:
$sql = requestSQL("SELECT user.email,
info.name,
FROM_UNIXTIME(user.registration),
info.news
FROM user, info
WHERE user.id = info.id ", "export members");
I also tried the date conversion with:
DATE_FORMAT(user.registration, '%d/%m/%Y')
DATE(user.registration)
I echo the result before to write the text file and I get :
email1;name1;DATE_FORMAT(user.registration, '%d/%m/%Y');news1
email2;name2;news2
How can I convert that field to date?
DATE_FORMAT(FROM_UNIXTIME(`user.registration`), '%e %b %Y') AS 'date_formatted'
To just get a date you can cast it
cast(user.registration as date)
and to get a specific format use date_format
date_format(registration, '%Y-%m-%d')
SQLFiddle demo
Convert timestamp to date in MYSQL
Make the table with an integer timestamp:
mysql> create table foo(id INT, mytimestamp INT(11));
Query OK, 0 rows affected (0.02 sec)
Insert some values
mysql> insert into foo values(1, 1381262848);
Query OK, 1 row affected (0.01 sec)
Take a look
mysql> select * from foo;
+------+-------------+
| id | mytimestamp |
+------+-------------+
| 1 | 1381262848 |
+------+-------------+
1 row in set (0.00 sec)
Convert the number to a timestamp:
mysql> select id, from_unixtime(mytimestamp) from foo;
+------+----------------------------+
| id | from_unixtime(mytimestamp) |
+------+----------------------------+
| 1 | 2013-10-08 16:07:28 |
+------+----------------------------+
1 row in set (0.00 sec)
Convert it into a readable format:
mysql> select id, from_unixtime(mytimestamp, '%Y %D %M %H:%i:%s') from foo;
+------+-------------------------------------------------+
| id | from_unixtime(mytimestamp, '%Y %D %M %H:%i:%s') |
+------+-------------------------------------------------+
| 1 | 2013 8th October 04:07:28 |
+------+-------------------------------------------------+
1 row in set (0.00 sec)
If the registration field is indeed of type TIMESTAMP you should be able to just do:
$sql = "SELECT user.email,
info.name,
DATE(user.registration),
info.news
FROM user,
info
WHERE user.id = info.id ";
and the registration should be showing as yyyy-mm-dd
FROM_UNIXTIME(unix_timestamp, [format]) is all you need
FROM_UNIXTIME(user.registration, '%Y-%m-%d') AS 'date_formatted'
FROM_UNIXTIME gets a number value and transforms it to a DATE object,
or if given a format string, it returns it as a string.
The older solution was to get the initial date object and format it with a second function DATE_FORMAT... but this is no longer necessary
Just use mysql's DATE function:
mysql> select DATE(mytimestamp) from foo;
You should convert timestamp to date.
select FROM_UNIXTIME(user.registration, '%Y-%m-%d %H:%i:%s') AS 'date_formatted'
FROM_UNIXTIME
If you are getting the query in your output you need to show us the code that actually echos the result. Can you post the code that calls requeteSQL?
For example, if you have used single quotes in php, it will print the variable name, not the value
echo 'foo is $foo'; // foo is $foo
This sounds exactly like your problem and I am positive this is the cause.
Also, try removing the # symbol to see if that helps by giving you more infromation.
so that
$SQL_result = #mysql_query($SQL_requete); // run the query
becomes
$SQL_result = mysql_query($SQL_requete); // run the query
This will stop any error suppression if the query is throwing an error.
I did it with the 'date' function as described in here :
(SELECT count(*) as the-counts,(date(timestamp)) as the-timestamps FROM `user_data` WHERE 1 group BY the-timestamps)
If you want to change the datatype of the column, you can simply convert first from TIMESTAMP to INT:
ALTER TABLE table_name MODIFY column_name INT;
And then INT to DATE:
ALTER TABLE table_name MODIFY column_name DATE;
But, if you didn't mean to change a column, but wanted SELECT only, then you can use date() function:
SELECT date(your_timestamp_column) FROM your_table;
I want to convert a record 1580707260
Usually, I am using online timestamp converter
Want to showcase it in the query result
Please try this
DATE_FORMAT(FROM_UNIXTIME(field name from table), '%e %b %Y')
AS 'display name for result'
Try:
SELECT strftime("%Y-%d-%m", col_name, 'unixepoch') AS col_name
It will format timestamp in milliseconds to yyyy-mm-dd string.
You can use this command FROM_UNIXTIME(unix_timestamp, [format]); but sometimes timestamp is in a long value that you have to remove 3 last values to 0.
for instance you use this command from_unixtime(e.EVENT_TIME/1000);
this way solve my problem.

Convert timestamp to date in MySQL query

I want to convert a timestamp in MySQL to a date.
I would like to format the user.registration field into the text file as a yyyy-mm-dd.
Here is my SQL:
$sql = requestSQL("SELECT user.email,
info.name,
FROM_UNIXTIME(user.registration),
info.news
FROM user, info
WHERE user.id = info.id ", "export members");
I also tried the date conversion with:
DATE_FORMAT(user.registration, '%d/%m/%Y')
DATE(user.registration)
I echo the result before to write the text file and I get :
email1;name1;DATE_FORMAT(user.registration, '%d/%m/%Y');news1
email2;name2;news2
How can I convert that field to date?
DATE_FORMAT(FROM_UNIXTIME(`user.registration`), '%e %b %Y') AS 'date_formatted'
To just get a date you can cast it
cast(user.registration as date)
and to get a specific format use date_format
date_format(registration, '%Y-%m-%d')
SQLFiddle demo
Convert timestamp to date in MYSQL
Make the table with an integer timestamp:
mysql> create table foo(id INT, mytimestamp INT(11));
Query OK, 0 rows affected (0.02 sec)
Insert some values
mysql> insert into foo values(1, 1381262848);
Query OK, 1 row affected (0.01 sec)
Take a look
mysql> select * from foo;
+------+-------------+
| id | mytimestamp |
+------+-------------+
| 1 | 1381262848 |
+------+-------------+
1 row in set (0.00 sec)
Convert the number to a timestamp:
mysql> select id, from_unixtime(mytimestamp) from foo;
+------+----------------------------+
| id | from_unixtime(mytimestamp) |
+------+----------------------------+
| 1 | 2013-10-08 16:07:28 |
+------+----------------------------+
1 row in set (0.00 sec)
Convert it into a readable format:
mysql> select id, from_unixtime(mytimestamp, '%Y %D %M %H:%i:%s') from foo;
+------+-------------------------------------------------+
| id | from_unixtime(mytimestamp, '%Y %D %M %H:%i:%s') |
+------+-------------------------------------------------+
| 1 | 2013 8th October 04:07:28 |
+------+-------------------------------------------------+
1 row in set (0.00 sec)
If the registration field is indeed of type TIMESTAMP you should be able to just do:
$sql = "SELECT user.email,
info.name,
DATE(user.registration),
info.news
FROM user,
info
WHERE user.id = info.id ";
and the registration should be showing as yyyy-mm-dd
FROM_UNIXTIME(unix_timestamp, [format]) is all you need
FROM_UNIXTIME(user.registration, '%Y-%m-%d') AS 'date_formatted'
FROM_UNIXTIME gets a number value and transforms it to a DATE object,
or if given a format string, it returns it as a string.
The older solution was to get the initial date object and format it with a second function DATE_FORMAT... but this is no longer necessary
Just use mysql's DATE function:
mysql> select DATE(mytimestamp) from foo;
You should convert timestamp to date.
select FROM_UNIXTIME(user.registration, '%Y-%m-%d %H:%i:%s') AS 'date_formatted'
FROM_UNIXTIME
If you are getting the query in your output you need to show us the code that actually echos the result. Can you post the code that calls requeteSQL?
For example, if you have used single quotes in php, it will print the variable name, not the value
echo 'foo is $foo'; // foo is $foo
This sounds exactly like your problem and I am positive this is the cause.
Also, try removing the # symbol to see if that helps by giving you more infromation.
so that
$SQL_result = #mysql_query($SQL_requete); // run the query
becomes
$SQL_result = mysql_query($SQL_requete); // run the query
This will stop any error suppression if the query is throwing an error.
I did it with the 'date' function as described in here :
(SELECT count(*) as the-counts,(date(timestamp)) as the-timestamps FROM `user_data` WHERE 1 group BY the-timestamps)
If you want to change the datatype of the column, you can simply convert first from TIMESTAMP to INT:
ALTER TABLE table_name MODIFY column_name INT;
And then INT to DATE:
ALTER TABLE table_name MODIFY column_name DATE;
But, if you didn't mean to change a column, but wanted SELECT only, then you can use date() function:
SELECT date(your_timestamp_column) FROM your_table;
I want to convert a record 1580707260
Usually, I am using online timestamp converter
Want to showcase it in the query result
Please try this
DATE_FORMAT(FROM_UNIXTIME(field name from table), '%e %b %Y')
AS 'display name for result'
Try:
SELECT strftime("%Y-%d-%m", col_name, 'unixepoch') AS col_name
It will format timestamp in milliseconds to yyyy-mm-dd string.
You can use this command FROM_UNIXTIME(unix_timestamp, [format]); but sometimes timestamp is in a long value that you have to remove 3 last values to 0.
for instance you use this command from_unixtime(e.EVENT_TIME/1000);
this way solve my problem.

mysql update multiple columns with same now()

I need to update 2 datetime columns, and I need them to be exactly the same, using mysql version 4.1.20. I'm using this query:
mysql> update table set last_update=now(), last_monitor=now() where id=1;
It is safe or there is a chance that the columns are update with different time, because of the 2 visible calls to now()?
I don't think that it can be update with different values (I think internally mysql calls now() just once per row or something similar), but I'm not an expert, what do you think?
Update:
Second question was extracted here.
Found a solution:
mysql> UPDATE table SET last_update=now(), last_monitor=last_update WHERE id=1;
I found this in MySQL Docs and after a few tests it works:
the following statement sets col2 to the current (updated) col1 value, not the original col1 value. The result is that col1 and col2
have the same value. This behavior differs from standard SQL.
UPDATE t1 SET col1 = col1 + 1, col2 = col1;
Mysql isn't very clever. When you want to use the same timestamp in multiple update or insert queries, you need to declare a variable.
When you use the now() function, the system will call the current timestamp every time you call it in another query.
MySQL evaluates now() once per statement when the statement commences execution. So it is safe to have multiple visible now() calls per statement.
select now(); select now(), sleep(10), now(); select now();
+---------------------+
| now() |
+---------------------+
| 2018-11-05 16:54:00 |
+---------------------+
1 row in set (0.00 sec)
+---------------------+-----------+---------------------+
| now() | sleep(10) | now() |
+---------------------+-----------+---------------------+
| 2018-11-05 16:54:00 | 0 | 2018-11-05 16:54:00 |
+---------------------+-----------+---------------------+
1 row in set (10.00 sec)
+---------------------+
| now() |
+---------------------+
| 2018-11-05 16:54:10 |
+---------------------+
1 row in set (0.00 sec)
You can store the value of a now() in a variable before running the update query and then use that variable to update both the fields last_update and last_monitor.
This will ensure the now() is executed only once and same value is updated on both columns you need.
You can put the following code on the default value of the timestamp column:
CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, so on update the two columns take the same value.
If you really need to be sure that now() has the same value you can run two queries (that will answer to your second question too, in that case you are asking to update last_monitor = to last_update but last_update hasn't been updated yet)
you could do something like:
mysql> update table set last_update=now() where id=1;
mysql> update table set last_monitor = last_update where id=1;
anyway I think that mysql is clever enough to ask for now() only once per query.
There are 2 ways to this;
First, I would advice you declare now() as a variable before injecting it into the sql statement. Lets say;
var x = now();
mysql> UPDATE table SET last_update=$x, last_monitor=$x WHERE id=1;
Logically if you want a different input for last_monitor then you will add another variable like;
var y = time();
mysql> UPDATE table SET last_update=$x, last_monitor=$y WHERE id=1;
This way you can use the variables as many times as you can, not only in mysql statements but also in the server-side scripting-language(like PHP) you are using in your project.
Remember these same variables can be inserted as inputs in a form on the front-end of the application. That makes the project dynamic and not static.
Secondly if now() indicates time of update then using mysql you can decalre the property of the row as a timestamp. Every time a row is inserted or updated time is updated too.