MySQL DATE_FORMAT "%d" issue - mysql

I'm sure there's a logic to this, but I do not understand it
date_format(date, '%m.%d.%Y') // Output: 03.05.2021
date_format(date, '%D.%m.%Y') // Output: 5th.03.2021
date_format(date, '%e.%m.%Y') // Output: 5.03.2021
But
date_format(date, '%d.%m.%Y') // Output: 28.02.2021
There seems to be an issue when I start the date_format with "%d", but I need my output to be 05.03.2021 (which is 5th March 2021), but I'm not able to achieve that. Can someone please explain this logic to me and help me?
Updated Explanation: In my database I have data from 5th March 2021 to 17th February 2021, so when I SELECT from the table using date_format(date_column, '%d.%m.%Y'), and order by date_column desc, the table begins from 28.02.2021 instead of 05.03.2021

You need to convert the date which is stored as string to a valid mysql date ,yyyy-mm-dd , in the order by for example
SELECT *
from table
order by str_to_date(date_column,'%d.%m.%Y') desc
You could be clearer on how your data is stored by providing samples

Your third example uses %e. Changing that to %d will give you the format you want.
If the value is stored in the database as a DATE, DATETIME or TIMESTAMP, then ordering by that value will give you what you need:
SELECT DATE_FORMAT(date_column, '%d.%m.%Y') AS formatted_date FROM table ORDER BY date_column DESC
N.B. Ordering by formatted_date won't give the order you want, because it's just a text string rather than a DATE or similar.
If the value is not stored in the database as a DATE or similar, then the suggestion from P.Salmon is what you want.

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

Make a query that will get a specific month from my sales table

In my sales table have the date column and the date is formatted like this January 9, 2018, 5:06 pm. How can I specifically get all the sales made from the month of January 2018 using MySQL?
assuming you date column is a date data type columns you can use year() and month() function
select * from my_table
where year(my_date_col) = 2018
and month(my_date_col) = 1
Since
the date is formatted like this January 9, 2018, 5:06 pm
and this is not recognizable time format for MySQL I belive the solution is:
SELECT * FROM table WHERE date like 'January%2018%';
I know this is not a "best practice" as well as storing time in a wrong type.
Since the column isn't already in a DATE format, let's assume it has to stay in its current format for the application purposes and add an auxiliary DATE column to select on (because SELECTs will be more optimized this way).
First we add a VIRTUAL column (requires MySQL 5.7+), which is a calculated column that is calculated at runtime but not stored on disk. We don't need to store this column on disk because we're going to index it later. Our VIRTUAL column will convert the application date's format to a MySQL DATE.
Replace str_date with your current date column:
ALTER TABLE `my_table`
ADD `virtual_date` DATETIME AS (STR_TO_DATE(`str_date`, '%M %d, %Y, %l:%i %p')) VIRTUAL AFTER `date`;
Now add the INDEX:
ALTER TABLE my_table ADD INDEX (`virtual_date`);
Now we can perform a properly indexed SELECT:
SELECT *
FROM my_table
WHERE virtual_date >= '2018-01-01'
AND virtual_date <= '2018-01-31'
or
SELECT *
FROM my_table
WHERE virtual_date >= '2018-01-01'
AND virtual_date <= LAST_DAY('2018-01-01')
The MySQL DATE format is YYYY-MM-DD. The latter query is logically simpler; the LAST_DAY() function will give you the last DATE of the month given a DATE or DATETIME value.

MySQL Filter Records Set Using DD-MM-YYYY Date Format

I'm a bit confused on how to filter records by date formats.
I have date column of date(yyyy-mm-dd) data type in date table.
Ex:
date
-----
2017-01-29
2017-01-30
I'm want to change the format (dd-mm-yyyy). I'm using this code
SELECT
DATE_FORMAT(`date`, '%d-%m-%Y') as date
FROM
dim_date;
date
-----
29-01-2017
30-01-2017
I want to filter the records with the(dd-mm-yyyy) format. So I tried this code.
SELECT
DATE_FORMAT(`date`, '%d-%m-%Y') date
FROM
dim_date
WHERE DATE_FORMAT(`date`, '%d-%m-%Y') BETWEEN '20-04-2015' AND '06-09-2017';
Results
Nothing
But if I try to filter with the original format (yyyy-mm-dd) It Works.
SELECT DATE_FORMAT(`date`, '%d-%m-%Y') date
FROM dim_date
WHERE DATE_FORMAT(`date`, '%Y-%m-%d') BETWEEN '2015-04-20' AND '2017-01-07';
Why is this weird behavior in Mysql? Am I missing something here?
I also tried with this format DATE_FORMAT(date, '%d-%c-%Y') , DATE_FORMAT(date, '%d-%l-%Y') & DATE_FORMAT(date, '%e-%l-%Y')
No happy face, Please let me known.
Thanks
Max
with your query you convert the date in string and then you are comparing values using between in wrong order ('20' > '06' ) so don't work.
Between require first the min value and second the max value.
If you are working with date you sould convert the string date
so the where between work correcly and avoid the string behavior is filter
SELECT date
FROM dim_date
WHERE date BETWEEN str_to_dat('20-04-2015', '%d-%m-%Y')
AND str_to_date('06-09-2017', '%d-%,-%Y');

SQL get date from timestamp

I have a database where all my data have a unix timestamp as a integer, the integer is the amount of seconds since 1.jan 1970.(like what Time.now.to_i returns in ruby http://www.unixtimestamp.com).
Is there any way i can get the date from 1447277423 in SQL? I need to group the rows by date.
I want this to be done in a view, and not use another script to do it.
Is this possible?
Convert the unix timestamp to date only (since you don't want hours/seconds), then group by it.
SELECT * FROM table
GROUP BY FROM_UNIXTIME(date_timestamp, '%Y %m %d');
Or, if you don't want to actually group them and just want them outputted all in order, ORDER BY instead.
SELECT * FROM table
ORDER BY date_timestamp
/* when ordering, it doesn't matter so much if its the whole timestamp or not since the date comes first in the timestamp */
To go one further, you can SELECT the formatted date as well
SELECT *, FROM_UNIXTIME(date_timestamp, '%Y %m %d') as date_Ymd FROM table
ORDER BY date_timestamp;
FROM_UNIXTIME docs
Just use FROM_UNIXTIME():
group by DATE(FROM_UNIXTIME(your_unix_timestamp_field))
That is the nice part of unix timestamps, you can just treat it as an integer.
SELECT something FROM table WHERE date >= 1447277423
Hope this helps

MySQL Order By Query for varchar saved date

I try to order the results of a query by the date which is in the format yyyy/mm/dd and I am using this query to no avail.
SELECT * FROM table ORDER BY STR_TO_DATE(date, '%y/%m/%d')
I can't change the type of field that the date is stored in so I am hoping I can order the date post data entry.
Any help and advice appreciated.
If the date is in that format, you don't need to convert it to a date, surely? That format would sort alphabetically, assuming it is 0 padded... (i.e. July is 3 July 2012 is 2012/07/03...)
So you can just go:
select * from table order by date
What type of field is your date field: are you sure it is a varchar?
Assuming it is a varchar, you can work out what is going wrong by going:
select str_to_date(date, '%y/%m/%d') from table
You (should) get all NULL's, because the %y is wrong. Try:
select str_to_date(date, '%Y/%m/%d') from table
and it should work. But as noted, you don't have to convert to sort.
Try with capital Y:
SELECT * FROM table ORDER BY STR_TO_DATE(date, '%Y/%m/%d')
Lowercase Y is for yy, uppercase for yyyy.
SELECT * FROM table ORDER BY date