How to order by time stamp in mysql? - mysql

SELECT * FROM table ORDER BY timestamp;
When i'm trying to order the records by its timestamp i'm getting the following order
08/20/2012 02:09:39 PM
08/20/2012 03:19:08 PM
08/20/2012 09:04:24 AM
08/20/2012 09:05:25 AM
How to change the query so that the records are ordered from AM to PM?

The problem is that your string representation of the timestamp is not in canonical format, that is, sorting the string value does not sort in timestamp order.
To get the rows sorted in order, you can convert the character representation of the value into a DATETIME or TIMESTAMP datatype, or at least into a character representation in a canonical format (e.g. 'YYYY-MM-DD hh:mm:ss' with a 24 hour clock).
The STR_TO_DATE function is useful for converting a string representation in a known format into DATETIME:
SELECT * FROM table
ORDER BY STR_TO_DATE(`timestamp`,'%m/%d/%Y %h:%i:%s %p')
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-format
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_str-to-date

You will want to use STR_TO_DATE()
select *
from dates
order by STR_TO_DATE(dt,'%m/%d/%Y %h:%i:%s') desc
See SQL Fiddle with demo

just add the DESC:
SELECT * FROM table ORDER BY timestamp DESC;

Related

Sort by varchar date entry in SQL

I want to sort my table by DATE which is a varchar holding date information like this:
January 06, 2023 // format is Month Day, Year
I want to sort by date but it doesn't work since this is not datetime. I've tried casting DATE but it doesn't seem to work. I tried like this:
SELECT * FROM receipt WHERE ID=? ORDER BY CAST(DATE AS datetime) DESC
I also tried convert but it did not work either, I must be using the syntax wrong.
How can I sort by date if my DATE entry is of type varchar.
In MySQL you can use str_to_date with the appropriate date format to convert a varchar to a date:
SELECT * FROM receipt WHERE ID=? ORDER BY STR_TO_DATE(date, '%M %d, %Y') DESC

Filter month in mysql when date is in varchar

I have a 2 columns called id and publish_date. publish_date is in varchar format(e.g. 2015-11-08 20:11:59). I used the following code to filter results based on month:
SELECT * FROM 'table' WHERE MONTH(STR_TO_DATE(publish_date, '%d/%m/%Y')) = 11
MySQL returned an empty result set. What's going on?
Here is a solution using TIMESTAMP().
SELECT * FROM `table` WHERE MONTH(TIMESTAMP(publish_date)) = 11
Demo:
mysql> select MONTH(TIMESTAMP('2015-11-08 20:11:59'));
+-----------------------------------------+
| MONTH(TIMESTAMP('2015-11-08 20:11:59')) |
+-----------------------------------------+
| 11 |
+-----------------------------------------+
1 row in set (0.00 sec)
If you had referred to the function manual, you'd see the second argument is supposed to be the given date format.
https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_str-to-date
If you're varchar entry is 2015-11-08 20:11:59 then you need to specify a format of '%Y-%m-%d %h:%i:%s'
In your query, when you convert date from varchar to date you can give that format which is used in column like ('%Y-%m-%d' for 2015-11-08)
I assume your publish_date (2015-11-08) format is yyyy-mm-dd
SELECT * FROM 'table' WHERE MONTH(STR_TO_DATE(publish_date, '%Y-%m-%d')) = 11;
Your character timestamp is of the format
2015-11-08 20:11:59
Therefore your format string which you pass into STR_TO_DATE() should be
%Y-%m-%d %h:%i:%s
SELECT *
FROM 'table'
WHERE MONTH(STR_TO_DATE(publish_date, '%Y-%m-%d %h:%i:%s')) = 11
For documentation on how to use various types of format strings, I prefer TechOnTheNet.
The format specified in STR_TO_DATE doesn't match the format of publish_date.
(Is there any good reason why publish_date isn't defined as a DATETIME column?)
Test your conversion, using a different format, one that matches the format of your strings...
SELECT STR_TO_DATE(publish_date,'%Y-%m-%d %T')
FROM `table`
LIMIT 10
That second argument to STR_TO_DATE function has specific meaning. It's not just a jumble of gibberish.
http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_date-format
Given the format of publish_date string matches the default format for MySQL DATETIME, you could omit the explicit reference to STR_TO_DATE function:
MONTH(publish_date) = 11
But personally, I would include the STR_TO_DATE function, to make the conversion explicit.
But if I had to do what you need to do, comparing VARCHAR values, I wouldn;t bother with converting it to date, I'd just use SUBSTRING function to extract the 5th thru 8th characters
SUBSTR(publish_date,5,4) = '-11-'
Your query should be as per below-
SELECT * FROM 'table' WHERE MONTH(STR_TO_DATE(publish_date, '%Y-%m-%d')) = 11;
Here you have to understand that you are trying to convert your string to date format means here you need to tell mysql that in which format your string is not in which format you want to convert-
To understand it if your date string is suppose '08/11/2015 20:11:59' then your query should be-
SELECT * FROM 'table' WHERE MONTH(STR_TO_DATE(publish_date, '%d/%m/%Y')) = 11;
Hope now it will be clear to you.

convert date from numeric value to date valid format

I need to filter all dates which greater than, say 01 january 2011.
select * from table_name where date > '01/01/2011';
the problem is that date field store int values, here is an example:
1339011098
1336717439
1339010538
How to convert the date field on the sql query (from the int format to date format), I need to convert it to a valid date so that I can compare it towards the above date.
Thanx.
You're going the wrong direction. Rather than converting potentially millions of records for the compare, try converting your target date, which you only need to do once. Those look like unix timestamps, so the resulting query should look like this:
SELECT * FROM `Table_name` WHERE date > unix_timestamp('01/01/2011')
Or, if you can control this, try using the ISO date format, which avoids confusion with european date formats for dates like 3/2/13:
SELECT * FROM `Table_name` WHERE date > unix_timestamp('2011-01-01')
You can use UNIX_TIMESTAMP()
select *
from table_name
where date > unix_timestamp('2011-01-01')
Or conversely use FROM_UNIXTIME()
select *
from table_name
where FROM_UNIXTIME(date, "%Y-%m-%d") > '2011-01-01'
First, you should not store date values as integers and if it's under your control your goal should be to fix the database and any queries that insert an integer value for that column instead of date.
The two date functions that you need to use with the current setup are UNIX_TIMESTAMP(), which accepts a date value and returns the epoch timestamp integer and FROM_UNIXTIME() which accepts an epoch timestamp integer and returns a date value.
For your example, you could use either:
SELECT * FROM table_name WHERE FROM_UNIXTIME(date_field) > '01/01/2011';
or
SELECT * FROM table_name WHERE date_field > UNIX_TIMESTAMP('01/01/2011');
But I would advise using FROM_UNIXTIME as a general rule as this would simplify more sophisticated queries such as:
SELECT * FROM table_name WHERE
FROM_UNIXTIME(date_field)
BETWEEN '01/01/2013' AND '04/01/2013';
Essentially, until your date field is actually storing values that are date types, your queries should covert the field values with FROM_UNIXTIME.

query between dates returns rows from previous months too

I have the following where clause
AND DATE_FORMAT( l.created_on, "%d/%m/%Y" ) BETWEEN '06/02/2013' AND '07/02/2013'
where created_on is a timestamp.
Now for some reason the query returns rows from previous months as well. anyone knows why?
NOTE :
I need the date to be in that specific format
Mysql string date format follows pattern yyyy-mm-dd. Do not convert to dates if you have timestamps, just compare the timestamps.
WHERE l.created_on
BETWEEN UNIX_TIMESTAMP('2012/02/06') AND UNIX_TIMESTAMP('2013/02/07')
if created_on is already a date (datatype),
you can directly query it using,
WHERE created_on BETWEEN '2013-02-06' AND '2013-02-07'
but if date is a string, use STR_TO_DATE
WHERE STR_TO_DATE(l.created_on, '%d-%m-%Y') BETWEEN '2013-02-06' AND '2013-02-07'
UPDATE 1
since you don't want to change the format of your inputted date, then you need to format it using STR_TO_DATE
WHERE l.created_on BETWEEN STR_TO_DATE('06/02/2013','%d/%m/%Y') AND
STR_TO_DATE('07/02/2013','%d/%m/%Y')

mysql order by closest date/hour before or after

I have a mysql table that has a column that stores dates but isn't in the date format, it's a varchar.
The column is called data_hora and have dates in the dd/mm/yy format, example: 06/09/2012 15:00, so I had to convert to date format in mysql query.
And I need to get the closest date and hour before or after the current time, I came up with the following code, but for some reason it seems to get only closest date but not hour, weird?!?!
SELECT str_to_date(data_hora, '%d/%m/%Y %H:%i') AS data_hora
FROM requisicoes
ORDER BY abs(DATE_FORMAT(NOW(),'%d/%m/%Y %H:%i') - data_hora) LIMIT 1
Help :(
try this:
Your ORDER BY Clause has to be changed
SELECT str_to_date(data_hora, '%d/%m/%Y %H:%i') AS data_hora
FROM requisicoes
ORDER BY abs(TIMEDIFF( NOW() , str_to_date(data_hora, '%d/%m/%Y %H:%i'))) LIMIT 1
You shouldn't format NOW() to a string: it is already a TIMESTAMP value; instead, take the (absolute) difference between the present UNIX_TIMESTAMP() and that of the data_hora alias for your selected STR_TO_DATE() column:
ORDER BY ABS(UNIX_TIMESTAMP() - UNIX_TIMESTAMP(data_hora))
If at all possible, I would advise altering your schema so that your data_hora column is stored as a TIMESTAMP: it will greatly improve the performance of queries of this sort.