Sorting varchar field containing time numerically - mysql

I'm using a varchar field to store a time notation (format: 00:00).
How'd I sort results on this field, so that eg 08:00 comes before 10:00?
Thanks for your support.

Ideally you should be storing the data as TIME but you can always CAST the date time literals on-demand:
ORDER BY CAST(thetime AS TIME)

Use TIME_FORMAT function in your ORDER BY clause
assuming your column is named thetime and is always expressed as 24-hours format hours:minutes (23:43)
ORDER BY TIME_FORMAT(thetime, '%H:%i');

You don't have an issue. '08:00' is less than '10:00'.
You don't have the problem because you have zero-padded the string. This works for up to '99:59'. If you need three-digit hours, then you need to store an addition 0 for the hour: '008:00'' and'010:00'`.
Of course, you can also use a TIME data type. That would generally make sense, but it is limited in its range and it stores sub-minute parts for the time (so under some circumstances, it might not be a perfect fit for your needs).

Related

questions about the datetime type values

I have several things which I want to discuss with you guys.
Since, they were just simple questions, so no dataset here.
Suppose I have a datetime type column which called started_date, the value in it was like:
yyyy-mm-dd hh:mm:ss. So, if I want to select some IDs which were larger than one specified day (let's say June/01/2017), can I just using
select ID, started_date
from table1
where started_date>"2017-06-01";
Does this work?
I tried some samples, and it worked indeed in the mysql. However, someone told me that I cannot compare the datetime column with string values without converting their format. And it confused me. Because I thought the value "2017-06-01" here was date type value, so it does not need convert. Or am I thinking wrong?
Another thing was about the double quote and single quote, I understand that the single quote was used for string values. However, in this case, when I used double quote to quote "2017-06-01", it works. So, does it mean the double quote can quote date values?
I am just asking, so any response is welcome.
Thanks.
Your query is fine. You are using a safe date/time format for the string. In other words, if you have to store the value as a string, then use that format.
I would write the code as:
where started_date >= '2017-06-01'
I see no reason to exclude midnight on 2017-06-01 (although you might have a reason). Second, single quotes are the standard delimiter for strings.
That said, you can store the value as a string.
As a best practice, I stay away from comparing time-stamps to date-stamps. In this case you can be explicit and truncate the start date. And yes, use single quotes instead.
where SUBSTR(started_date, 1, 10) > '2017-06-01'
To make sure it works you could just convert the date time to a string first and compare the two strings:
to_char(started_date,'YYYY-MM-DD') >= '2017-06-01'
The Strings will compare just fine in that format.

MySQL timestamp format and datediff

Hi I'm writing queries for MySQL, and now my database has a column containing the timestamp in this format: 7/14/2015 7:57:49 AM, but I need to use the DATEDIFF function, so how can I convert the timestamp into the format like: 2015-7-14 (or 2015-07-14, I'm not sure which one is correct; just the date)?
This should convert your string to just the date in a date format, then you can use DATEDIFF on the date fields in question:
SELECT STR_TO_DATE(LEFT(t,LOCATE(' ',t) - 1), '%m/%d/%Y') FROM my_table;
The LEFT function will take the substring to the left of the space, which is just your date, then STR_TO_DATE will convert that substring to a date the system can use.
(Not knowing your field and table names, I used t and my_table.)
You don't need to. The way MySQL displays timestamps has nothing to do with the way they're stored internally; as long as it's TYPE TIMESTAMP or some compatible type, the DATEDIFF() function will know what to do with it.
TIMESTAMPs are actually stored as a really huge integer representing (I think) milliseconds from Midnight UTC, January 1st, 1970. The display format is determined by a system global variable, and has nothing to do with the actual value.
Converting from a string to a DATETIME or TIMESTAMP is actually also fairly straightforward using the STR_TO_DATE() function; in your case the format string would be something like
STR_TO_DATE('%c/%e/%Y %l:%i:%s %p', datecol)
although you might have to experiment a bit to make it work reliably.

MySQL SEC_TO_TIME gives hh:mm:ss.000000

As said in the caption I am wondering why the SEC_TO_TIME-Function of MySQL gives me that Zeros at the end.
Refering to the docu (http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_sec-to-time) that shouldn't happen (I am using MySQL 5.0.11).
Any Idea why this Zeros appears and how to get rid of them? To much zeros for displaying miliseconds.
Sine the zeros doens't break MySQLs Date-funcions, it's more a "I don't like that"-Question rather than a real Problem (at least till now^^)
// EDIT: I just figured out that the zeros aren't coming from the SEC_TO_TIME but from the FROM_UNIXTIME()-Function. Thx to #Abhik Chakraborty to ask for the input!
// EDIT2: I used FROM_UNIXTIME(last_try, '%Y-%m-%d %H:%i:%s') to get rid of the zeros. But When I do TIME(FROM_UNIXTIME(last_try, '%Y-%m-%d %H:%i:%s')) the zeros are back. Why??
Seems like every function adds the zeros back. Using SEC_TO_TIME on a simple integer-value also gives zeros...
Here is the whole query iam using:
SELECT
SEC_TO_TIME(FLOOR(TIME_TO_SEC((TIME(FROM_UNIXTIME(`last_try`))))/1800)*1800)
FROM `last48h`
The query reads the timestamp, gets only the time, converts it to seconds, breaks the seconds into half-hours (/1800 gives 0 < x < 48) rounds down and converts back to time
SEC_TO_TIME produces a TIME data type for its result. You can format that as you wish with DATE_FORMAT.
If you actually need subsecond time resolution you'll need to move to version 5.6.4 or beyond.
When you directly SELECT any sort of TIME data type to display, you get a default TIME-to-string conversion operation. The default TIME-to-string conversion in some generations of MySQL yields a string ending in hh:mm:ss+zz00. +zz00 is a timezone indicator, and often displays as +0000. Any chance that's what you're seeing?
It doesn't make sense to try to handle a UNIX_TIMESTAMP() style number of seconds using SEC_TO_TIME(). As of mid-2014 the current unix timestamp value is above 1.39 gigaseconds. TIME data types are used for stuff like elapsed times, and have a limit of just under 839 hours (3 megaseconds, precisely 3020399 seconds), and silently truncate their values.
For example, this is a good use of SEC_TO_TIME:
SELECT SEC_TO_TIME(end_timestamp - start_timestamp) AS duration
edit
Strangely enough, this query
SELECT
SEC_TO_TIME(FLOOR(TIME_TO_SEC((TIME(FROM_UNIXTIME(UNIX_TIMESTAMP()))))/1800)*1800) AS a,
FLOOR(TIME_TO_SEC((TIME(FROM_UNIXTIME(UNIX_TIMESTAMP()))))/1800)*1800 AS b,
TIME_TO_SEC((TIME(FROM_UNIXTIME(UNIX_TIMESTAMP()))))/1800 AS c,
FROM_UNIXTIME(UNIX_TIMESTAMP()) AS d,
FROM_UNIXTIME(UNIX_TIMESTAMP() - UNIX_TIMESTAMP() % 1800) as e
doesn't show any of the 0000 stuff through the phpmyadmin instance I use.
By the way, most people who round time to the nearest interval (a half-hour in your case) prefer to use a modulo and a subtraction; it's less dependent on implicit numerical type conversion than your method.
SELECT TIME(FROM_UNIXTIME(last_try - last_try%1800))
does what the query in your question does.
I had the same problem with the 'SEC_TO_TIME' function.
I had overlooked the fact that I was storing timestamps as a VARCHAR.
I changed my datatypes from VARCHAR to BIGINT and it is formatting the output values as expected (hh:mm:ss).
Try to use TIME_FORMAT with %k specifier it should help.

why this MySQL SELECT doesn't include the right dates?

The main problem is, that I have stored in database datetime , not the date (what I need). Ok never mind.
I have thousands of reports stored each day.
I need to LEFT by 10 my datetime_view (to cut the time) and everything's fine. Except this. I'm trying to figure out why do I have to put in the condition + one day from the future? Otherwise it won't search what I want.
SELECT
LEFT(datetime_view,10),
count(type)
FROM reports
WHERE
type IN (1,2,5)
AND
datetime_view>='2012-10-28'
AND
datetime_view<='2012-11-04'
group by LEFT(datetime_view,10);
You can see I must search from the future. Why??
It gives me an output from 28.10 to 3.11 ....
don't use string operations on date/time values. MySQL has a huge set of functions for date/time manipulation. Try
GROUP BY DATE(datetime_view)
instead, which will extract only the date portion of the datetime field. Your string operation is not y10k compliant. Using the date() function is.
As for your plus one day, consider how the comparisons are done: A plain date value, when used in date/time comparisons, has an implicit 00:00:00 time value attached to it, e.g. all dates have a time of "midnight".
i think it's better to use DATE(datetime_view) to cut the time instead of LEFT(datetime_view,10), also on the where condition:
DATE(datetime_view) <= '2012-11-03'

Mysql time stamp queries

I have a column that uses time stamp. My question is I am a bit confused about how to make queries against it,how would I say
Where $time is after X date
Are queries made in local time or CUT?
When I just try to do where andthe post date /time I get an error because of the space and if I quote it I think it takes it as a string : /
What format do I use for the date in the WHERE clauss !?!?
You can use the normal logical comparisons, for example:
SELECT * FROM table WHERE date >= '2010-01-31'
SELECT * FROM table WHERE date >= '2010-01-31 12:01:01'
Time is generally in your current local time, but you can run the query "SELECT CURTIME()" to check. Also, make sure you have the year-month-date in the right order... that can cause issues.
The manual has more details:
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html
Assuming you talk about TIMESTAMP column type (not Unix timestamp) the format is either 'YYYY-MM-DD HH:MM:SS' (quoted) or YYYYMMDDHHMMSS
Atually, in the first case you can use any spearators you wish (or none), only numbers are taken into ccount