What is the best way to format a date in a MySQL query?
I am currently running the query below which selects the data but doesn't order the information correctly, I presume this is due to the current format of the 'updatetime' row.
SELECT * FROM updates WHERE udcode='Remote Connection' ORDER BY updatetime DESC LIMIT 20;
The current format is as follows:
31/03/2015 13:41:45
How should this date be formatted in order for the ORDERING to work correctly?
Thanks in advance.
Use:
ORDER BY DATE_FORMAT(updatetime, '%Y-%m-%d %H:%i:%S') DESC
you can change the format of your date in MySQL with DATE_FORMAT
SELECT *, DATE_FORMAT(`updatetime`, '%Y-%m-%d %H:%i:%S') AS mydate FROM updates WHERE udcode='Remote Connection' ORDER BY mydate DESC LIMIT 20;
http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_date-format
You are doing this correctly in the Query, however if you are getting undesired results then there is a possibility that the data type for your updatetime attribute is not correct.
You should use datetime as the data type so that the query is correctly able to distinguish that the information is a date and knows how to order it properly. For example if you are using a varchar it will think that the first digit reading left to right is the most significant rather than recognising the difference and relationship between days, months, years and time.
If you dont have the correct datatype you would either have to include formatting in a bloated query or you would end up with all the days from 10-19 ordered before the 20-29 and then followed by the days 3-9. In this situation the 30th would be considered to be ordered before the 4th for example.
There will be little relevance by the time you are ordering months or years as the day units will have mixed everything up
You can try following changes
Change date format to
yyyy-mm-dd hh:mm:ss
And edit query to
SELECT * FROM updates WHERE udcode='Remote Connection' ORDER BY `updatetime` DESC LIMIT 0, 20;
Related
I need to create a query to select some data of my mysql db based on date, but in my where clause i have to options:
1 - trunc the date:
select count(*) from mailing_user where date_format(create_date, '%Y-%m-%d')='2013-11-05';
2 - use between
select count(*) from mailing_user where create_date between '2013-11-05 00:00:00' and '2013-11-05 23:59:59';
the two query's will work, but whats the better? Or, what's recommended? Why?
Here is an article to read.
http://willem.stuursma.name/2009/01/09/mysql-performance-with-date-functions/
If your created_date column is indexed, the 2nd query will be faster.
But if the column is not indexed and if this is your defined date format, you can use the following query.
select count(*) from mailing_user where DATE(create_date) = '2013-11-05';
I use DATE instead of DATE_FORMAT as I can make use of the native feature of getting in this format('2013-11-05').
From your question it seems you want to select records from one day, according to the documentation A DATETIME or TIMESTAMP value can include a trailing fractional seconds part in up to microseconds (6 digits) precision.
So this means your second query might actually get unlucky and miss some records that were inserted into the table at the very last second of that day, so that is why I would say the first one is more precise and is guaranteed to always get you the correct result.
The downside of this is that you cannot index that column using the date_format-function, because MySQL isn't cool with that.
If you don't want to use date_format and get around the precision issue you would change
where create_date between '2013-11-05 00:00:00' and '2013-11-05 23:59:59'
into
where create_date >= '2013-11-05 00:00:00' and create_date < '2013-12-05 00:00:00'
Number 2 will be faster if you have an index on the create_date because number one won't be able to use the index to quickly scan the results.
However this requires there to be an index on the create_date.
Otherwise I imagine they would be similar speed, possibly the second would still be faster because of the smaller processing time to compare(datetime comparison rather than converting to a string and comparing strings), but I doubt it'd be significant.
I have list of date in MySQL in the format of "MM-DD-YYYY" and When I was trying to fetch the latest date from table it just return the last date of a Year like 12-01-2014 instead of return latest date 03-16-2016.
Payment history table:
to_date
03-16-2016
12-01-2014
11-07-2014
10-03-2014
01-09-2014
I used following query:
SELECT MAX(to_date) FROM paymenthistory WHERE empid=59;
Result : 12-01-2014
Related post: Get the latest date from grouped MySQL data
Thanks in advance
You're working with strings, not native dates, so you're getting the maximum date.
Either convert those strings to ACTUAL mysql date/datetime values, or you'll have to go with ugly hacks, like
SELECT MAX(STR_TO_DATE(to_date, '%m-%d-%Y'))
and performance will be massively bad. MySQL's native date format is yyyy-mm-dd hh:mm:ss, which is a natural "most significant first" format. If your date strings were formatted like that, then even a max(string) would work.
It sounds like your date column is actually a VARCHAR format since it is seeing 12-01-2014 as the last date which is only true if stored as a VARCHAR.
Be sure your to_date column is a DATE type.
have you tried this?
SELECT TOP 1 * FROM paymenthistory WHERE empid = 29 ORDER BY to_date DESC;
For mysql try this
SELECT * FROM paymenthistory WHERE empid=59 ORDER BY to_date DESC LIMIT 1;
How can I filter the dates that it would sort first by today then normal?
I have a column with data type datetime, I wanted my results to be sorted showing today's date first and continue normal sorting.
What about
SELECT
...
FROM
...
ORDER BY IF(DATE(datefield=CURRENT_DATE()),0,1), datefield DESC
Edit
Added the DESC to the ORDER BY after the 3rd comment to the OQ
i need to retreive data from database with the condition from date to to date using between query,
my query is,
select * from Master where Date between '01-08-2013' and '30-08-2013'
but it retreive all data from the table...
i need only data with in that date..
i tried another one like,
select * from PatientMaster where EntryDate >= '01-08-2013' and EntryDate<= '30-08-2013'
how its posible..
whats wrong with my query...
sorry im very bad in english...
thank you in advance...
A date string has the syntax YYYY-MM-DD and not DD-MM-YYYY
select * from Master
where `Date` between '2013-08-01' and '2013-08-30'
for that you can use
select * from Master where Date >='01-08-2013' and dateadd(dd,1,'30-08-2013')
You have to convert your strings to dates. This page shows you how to do it in mysql, which is what you have tagged. For sql server, which is in your subject line, use this page.
Then you do a slight modification of your 2nd attempt. Instead of
and EntryDate <= the end date
you want
and EntryDate < the day after the end date
That takes care of any time components. It might not matter in your case, but it's a good habit to get into.
You'll be looking for an query that works with your format? (dd-mm-yy)
CAST to the desired format!
http://www.w3schools.com/sql/func_convert.asp
105 = dd-mm-yy
SELECT * FROM Master
WHERE CONVERT(date, Date, 105) BETWEEN '01-08-13' and '30-08-13'
Be conscious with regards of the choice of data type for date Columns,
with or without time, day or year first etc. and please do not use varchar
for dates...
know that it CAN be confusing to call a date column for only Date...
be consistent with high/lower case.
I've posted this question before and found a solution: ORDER BY with two columns in MySQL
It's about sorting events. The priority SHOULD BE that TOP-PREMIUM and PREMIUM events are always on top of each date, no matter what.
The solution was that one column was ENUM and not INT. That's why he sorted wrong.
So now I'm sorting this way: ORDER BY e.date ASC, e.highlight DESC
Now I've another new problem, because all my dates were set to time 00:00:00 the time I asked the question here and thought it's all solved. If I'm setting the time to some hour after 00:00, it will be at the top of all events. Even in top of PREMIUM AND TOP-PREMIUM (highlight) events.
Can I somehow let MySQL ignore the time of the datetime type column date or is there any other way to make this work like I want to?
The problem also is that I can't order by highlight DESC first, because then the whole list won't be sorted by date.
You can use the CAST() function or the DATE_FORMAT function to get the date portion only, so this should work:
ORDER BY CAST(e.date AS DATE), e.highlight DESC
ORDER BY DATE_FORMAT(e.date, '%Y-%m-%d'), e.highlight DESC
Demo: SQL Fiddle
Edit: Updated sql fiddle demo to use 2 columns, you can see that the time portion of the date is not affecting sort order.
You can also use the DATE function, which strips the time component from a DATETIME:
ORDER BY DATE(e.date), e.highlight DESC