MYSQL Fetch Date and Time Stored as String and ORDER BY - mysql

I have a specific reason for storing Date and Time in DataBase Table as String in below format
DateFmt = "dd-MM-yyyy";
TimeFmt = "hh:mm a";
Now while fetching I want to sort by converting the string to Date and Time and sort to display in TableView, so the row with newer ones come on top.
This wil work if we store as date and time,
ORDER BY `DATE` DESC, `TIME` DESC
How do we convert from String and use order by

Use str_to_date():
order by str_to_date(date, '%d-%m-%Y')
I should add: I can think of no good reason for storing a date in that format in the database. You should be using the built-in date/time types. They exist for a reason.
If you do have to store a date as a string (which I have to do occasionally), you should use YYYY-MM-DD format. This is ISO standard, converts readily to a date, and sorts correctly.

I came with the solution like this :
SQL :
SELECT * FROM NamTbl
ORDER BY STR_TO_DATE(CONCAT(DateCol,' ',TimeCol), '%d-%m-%Y %h:%i') DESC
SQLite :
"SELECT * FROM " + NamTblVar +
" ORDER BY STRFTIME('%d-%m-%Y %h:%i'," + DateKolVar + "|| ' ' ||" + TimeKolVar + ") DESC;";

Related

Select only date form datetime field in where condition

I have stored this kind of format 2022-02-06 18:40:00 in my trans_reminder_date. I want to use only date in where condition but with this condition i am not able to fetch data
$today = date('Y-m-d');
SELECT * FROM sales_detail
WHERE trans_reminder_date = '".$today."'
AND trans_reminder_date != ''
ORDER BY sales_detail_id DESC";
If when your filter parameter is a string:
select * from sales_detail
where cast(trans_reminder_date as date) = cast('2020-03-22' as date)
if you want to use the current date for filtering then MySQL has a function that getting only the current date without time.
select * from sales_detail
where cast(trans_reminder_date as date) = curdate()
On MySQL for converting other types to another, you can use a cast
P.S.
Starting with MySQL 8.0.13 we have now an easiest way to create functional indexes. When you are using cast(updated_at as date) then DB will not use index for column updated_at. You must create a functional index for best performance.
The following query will give you all the result for the current date. By doing this there won't be any need to cast values.
SELECT
*
FROM
sales_detail
WHERE
trans_reminder_date >= curdate()
AND trans_reminder_date < curdate() + INTERVAL '1' DAY
ORDER BY
sales_detail_id DESC;
Using Cast function to change datetime type to date example
Cast(column_name as date)
Or
You using convert function change datetime type to date
CONVERT(column_name, date);
CONVERT(expression, datatype);
OR,
CONVERT(expression USING character_set);
character_set: It specifies the desired character set in which we want to be converted.
Data type : It specifies the desired data type in which we want to be converted.
Expression : It is a specified value going to be converted into another specific datatype.

mysql date comparision is not working unable to find the issue

i have a huge data with dates as string.
column name date1
datatype varchar
the stored data is in this format:14-Mar-2016 05:44:38pm
Now I have split only date from this string like this: 14-03-2016
By using this: DATE_FORMAT(STR_TO_DATE(gr.date1, '%d-%M-%Y'),'%d-%m-%Y')
Now I am trying to compare the date with this query:
SELECT * FROM
( SELECT date1,DATE_FORMAT(STR_TO_DATE(date1, '%d-%M-%Y'),'%d-%m-%Y') as dateFormatted
FROM `grabt` ) as mTbl WHERE mTbl.dateFormatted >= '19-01-2016'
AND mTbl.dateFormatted <= '25-01-2016'
but it is not working what could be the possible error.?
The timestamp string 14-Mar-2016 05:44:38pm can be converted to a datetime using the STR_TO_DATE() along with the format string %d-%b-%Y %r. We can then obtain only the date portion by wrapping that with DATE(). Have a look here for a demo to see that this works.
SELECT *
FROM
(
SELECT DATE(STR_TO_DATE(date1, '%d-%b-%Y %r')) AS dateFormatted
FROM grabt
) AS mTbl
WHERE mTbl.dateFormatted BETWEEN '2016-01-19' AND '2016-01-25'
As Gordon already pointed out, you should ideally be using date types not strings for your date calculations. And by the way, use a valid date string when comparing in your WHERE clause. YYYY-MM-DD is a valid format, e.g. 2016-01-19, but 19-01-2016 is not.
Learn to use the right types for columns. Perhaps you are stuck with someone else's really bad decision to store date/times as strings. Perhaps you cannot change that. But, within a query, use the right types!
SELECT mTbl.*,
LEFT(date1, 10) as FormattedDate -- Is this really necessary?
FROM (SELECT date1,
STR_TO_DATE(LEFT(date1, 10), '%d-%M-%Y') as thedate
FROM `grabt`
) mTbl
WHERE mTbl.thedate >= '2016-01-19' AND
mTbl.thedate <= '2016-01-25';
This will do the comparison as dates not as strings.

How to concatenate Date and DateName together

I want to concatenate Date And Date Name Together. How Can I do it.
I need output like
2015-10-09 Friday
I got the DateName= `SELECT DATENAME(dw,'2015-10-09') as MyDateName`
Is it possible to make it in a single query?
Try this:
select CAST('2015-10-09' as varchar(10)) + ' ' +DATENAME(dw,'2015-10-09')
SQLFIDDLE DEMO
If your date is already in the varchar format then you dont need to CAST the date and simply try to concatenate them using +
select '2015-10-09' + ' ' +DATENAME(dw,'2015-10-09')
Since the value you provided is already a string, and DATENAME also returns a string, you can just concatenate together with +:
SELECT '2015-10-09 ' + DATENAME(WEEKDAY,'2015-10-09') as MyDateName
Assuming that in reality this is a parameter or a column of datatype datetime, you'll need to convert it to varchar first. There is no built in style for converting to varchar which contains the Day name, so you'll have to do the work yourself in two parts.
See MSDN page on cast and convert for the built in formats.
For the sake of my example, I'll create a datetime variable to use for tests:
DECLARE #d DATETIME; SET #d = '20151009';
Then to convert it to VARCHAR:
For the date part, ODBC is closest to the format you've asked for with the format yyyy-mm-dd hh:mi:ss(24h). So to get the date in that format as a varchar, you can use CONVERT with that style, value, 20.
SELECT CONVERT(VARCHAR(10), #d, 20)
Note I have converted it to VARCHAR(10) to truncate the timepart of the datetime that you don't want in the output. Then if you concatenate this with a space and the day name you already worked out, you can get your output:
SELECT CONVERT(VARCHAR(10), #d, 20) + ' ' + DATENAME(WEEKDAY, '2015-10-09') AS MyDateName
(Replace my variable with a column name and add a FROM statement if you're after output from a table)
You can try this code:
SELECT
CAST(CAST(GETDATE() AS DATE) AS VARCHAR) + ' ' + DATENAME(DW, GETDATE()) AS [DATE_WITH_WEEKNAME]

Compare String with curdate() - Mysql

I plan to make a selection of multiple database tables.
The problem is that I want the current date is equal to current date, only that it is of type varchar, I can't make a direct comparison with the CURDATE () ... Is there any way to compare the current date with the String type?
Code:
select records.date , records.hour, records.Temp, records.Hum, sensors.idSensor, sensors.idLocalization
from records, sensors
where records.idSensor=sensors.idSensor
and records.date = curdade() // Here is where I wanted to make the comparison date
order by records.date desc;
------------------EDIT (Solved)--------------------------
Thank you all for your help.
I switched CURDATE by curdade.
He made the comparison correctly.
Convert the curdate() to a string of the appropriate format. Something like:
select r.date, r.hour, r.Temp, r.Hum, s.idSensor, s.idLocalization
from records r join
sensors s
on r.idSensor = s.idSensor
where r.date = date_format(curdate(), '%Y-%m-%d') // Here is where I wanted to make the comparison date
order by r.date desc;
You need to use the appropriate format for your date column. I just used the "right" format, the ISO standard date format that is the best to use when representing a date as a string. You can read about the formats in the documentation. And, it is better to turn the current date into the right format than to convert the string to a date. By putting the function on the "constant" part of the comparison, MySQL can still take advantage of an index on date.
Try this. It may work. But this is a date-to-date data type comparison, not a string-to-string comparison.
select STR_TO_DATE(records.date, '%Y-%m-%d') AS date , records.hour, records.Temp, records.Hum, sensors.idSensor, sensors.idLocalization
from records, sensors
where records.idSensor=sensors.idSensor
and date = curdate() // Here is where I wanted to make the comparison date
order by date desc;

How does one construct a query that only returns this months rows, based on Timestamp?

I'm curious what the right way is to construct a query where the rows are pulled based on a timestamp that represents a specific month. Given that different months have different numbers of days, is there a way to generate a query that always gives you the rows where the timestamp contains the current month so that the results would only include the current month?
Do you mean something like this
SELECT * FROM tbl WHERE
MONTH(timesp) = MONTH(NOW()) AND
YEAR(timesp) = YEAR(NOW());
You can use the FROM_UNIXTIME() function:
SELECT *
FROM tableName
WHERE MONTH(FROM_UNIXTIME(timestampField))==6
Just use MONTH:
select *
from foo
where month_column = MONTH(getdate())
and year_column = YEAR(getdate())
Try this sql.
select *
from yourtable
where yourdatefield>=DATE_SUB(CURDATE(),INTERVAL 1 MONTH);
You're looking for something like this:
SELECT * FROM table where MONTH(date_row) = $month;
If you have an index on your date field, then this is efficient (T-SQL syntax, the idea applieas to any RDBMS though)
SELECT
*
FROM
tableName
WHERE
dateTimeField
BETWEEN
-- build the string 'YYYY-MM-01', cast back as a datetime
CAST(
CAST(YEAR(GETDATE()) AS varchar) + '-' + CAST(MONTH(GETDATE()) AS varchar) + '-01'
AS datetime
)
AND
-- add one month, subtract one day
DATEADD(mm, 1,
-- build the string 'YYYY-MM-01', cast back as a datetime
CAST(
CAST(YEAR(GETDATE()) AS varchar) + '-' + CAST(MONTH(GETDATE()) AS varchar) + '-01'
AS datetime
)
) - 1
Of course any other method to get two datetime values in the right range would work.
SQL Server has LEFT(CONVERT(varchar, GETDATE(), 120), 8) + '01' to convert a datetime to string, other Db servers have their own functions to do the same. Maybe you can calculate the two values in the calling application more easily - how you get them, is not the point.
The point is that BETWEEN can use an index, whereas the other solutions that work with WHERE MONTH(dateTimeField) = 6 will trigger a table scan, which is about the slowest operation you can do on a table.