MySQL - Date Format - mysql

A couple of questions.
In SQL Developer I could type alter session set nls_date_format='DD-MON-YY HH:24:MI:SS'; to include the time and all queries on that tab would then include this format. I could then type alter session set nls_date_format='DD-MON-YY'; to remove the time. Any easy equivalent in MySQL that could flip my date formats like this?
If it's not that simple, let me ask this: Can the format be changed on a single query line. So if i have this
select name, start_date from Users;
If this normally shows the date and time, how can i alter it to only have the results show just the date?

Any easy equivalent in MySQL that could flip my date formats like this?
Yes, there is.
What you're looking for is the DATE_FORMAT() function.
Example:
select DATE_FORMAT(start_date,'%d-%m-%Y') from Users
Adjust the specifiers as needed.
Common specifiers:
%d day of month
%m month
%Y year
%H hour (00..23)
%h hour (01..12)
%p AM or PM
%i minutes
%s seconds
For other specifiers, see DATE_FORMAT().

start_date is presumably a datetime column. You can truncate the time by converting it to a date:
SELECT name, DATE(start_date)
FROM users

Related

How to Convert date day time format to date only. example "07-13-2020 Mon 10:13:32 am" to "07-20-2020" in sql

Good day,
I am trying to fetch range of data in my database but i cant get any result when i try to query like this.
SELECT * FROM `doc_history` WHERE date BETWEEN '07-13-2020 Mon 10:13:32 am' AND '07-20-2020 Mon 01:24:28 pm'
but if i try only to search specific date. it normally show the data. but when it comes to RANGE SEARCH, it show nothing.
I am trying to convert this date format to a simplified date format "07-20-2020 Mon 01:24:28 pm" to "07-20-2020".
I tried others formula but still no result.
You should valid MySQL timestamp/datetime literals:
SELECT *
FROM doc_history
WHERE STR_TO_DATE(date, '%m-%d-%Y %a %h:%i:%s %p')
BETWEEN '2020-07-20 13:24:28' AND '2020-07-20 13:24:28';
But note that you are currently not really searching for a range, but rather a point in time. So the above query I wrote is equivalent to:
SELECT *
FROM doc_history
WHERE STR_TO_DATE(date, '%m-%d-%Y %a %h:%i:%s %p') = '2020-07-20 13:24:28';
If you want a meaningful range, then the start and end values should be different points in time.

How to delete string date older then 2020/11 month in MySQL?

I have a database, with around 500k rows, I don't know why but instead of using "Date" type on the column it uses "varchar". Now the date has a format - 01/02/2021 07:08:49 AM
My question is how should an SQL query look to delete this kind of "old" date rows from the table? Or in another hand how should I convert the column without losing the data and holding the same format to a Date type column?
I tried deleting with something like this:
DELETE FROM `visited` WHERE LEFT(`last_visit_date`, 2) != '01' OR LEFT(`last_visit_date`, 2) != '12';
However, this didn't fully clean the table.
Any help would be appreciated.
You may use STR_TO_DATE in your delete query to convert the text dates to bona fide dates:
DELETE
FROM visited
WHERE
STR_TO_DATE(last_visit_date, '%d/%m/%Y %h:%i:%s %p') < '2020-11-01';
Note that if your text dates actually have month before day, then use this call to STR_TO_DATE:
STR_TO_DATE(last_visit_date, '%m/%d/%Y %h:%i:%s %p')
If you don't want to lose the dates with the wrong format, you can update the table:
UPDATE visited
SET last_visit_date = STR_TO_DATE(last_visit_date, '%d/%c/%Y %r')
WHERE last_visit_date LIKE '__/__/____ __:__:__ __';
and change the data type of the column to DATETIME (if all the other values of last_visit_date are valid datetimes):
ALTER TABLE visited MODIFY last_visit_date DATETIME;
See a simplified demo.

How to convert text datatype to datetime in mysql?

In mysql database,column name created.This "created " column is text datatype,I need to change this to datetime.Now this column have so many datas.Is it possible to convert it or?
Database look like
created
18-11-15 18:21:25
Expecting ouput is
created
2018-11-15 18:21:25
When am doing
ALTER TABLE invoices MODIFY created datetime
This query giving wrong data.its converting from 15-09-18 03:03:43 to 2015-09-18 03:03:43
If the original data is not in MySQL Datetime format (YYYY-MM-DD HH:MM:SS), you cannot just change the column datatype from Varchar/Text to Date/Datetime. Otherwise, there will be an irreparable Data loss.
This will be a multi-step process. You will first need to convert the date string to MySQL date format (YYYY-MM-DD HH:MM:SS). We can use STR_TO_DATE() function for this.
Your sample date string (18-11-15 18:21:25) is basically in %y-%m-%d %T format. Following format specifiers can be used:
%d Day of the month as a numeric value (01 to 31)
%m Month name as a numeric value (00 to 12)
%y Year as a numeric, 2-digit value
%T Time in 24 hour format (hh:mm:ss)
The query to update the date would look as follows:
UPDATE invoices
SET created = STR_TO_DATE(created, '%y-%m-%d %T');
Now, you can use Alter Table to change the data type from Text type to Datetime.
ALTER TABLE invoices
MODIFY COLUMN created datetime;
The best thing to do here is to not store your dates as text. Assuming you have already done this, we can cope by calling STR_TO_DATE to generate a bona fide date:
SELECT
STR_TO_DATE(created, '%y-%m-%d %h:%i:%s') AS created_out
FROM yourTable;
Since the output you expect is standard date output, we can stop here and avoid also calling DATE_FORMAT to generate a different output.
you want to convert output or database records ? for second you can use sql query :
UPDATE 'table_name' SET 'created' = CONCAT('20', 'created')
You will need first to interchange the day with the year in the created column, as follows:
UPDATE invoices
SET created = CONCAT(SUBSTR(created, 7, 2), '-', SUBSTR(created, 4, 2), '-', SUBSTR(created, 1, 2));
Then, you convert the column to DATETIME, as follows:
ALTER TABLE invoices MODIFY created DATETIME;
Hope this helps.

Read data stored as text and use in IF statement

I have a column that stores dates as text, I need to select all the entries with date less than the date of today.
If I use this:
SELECT *
FROM mytab
WHERE expire < CURRENT_DATE( )
ORDER BY expire DESC
It doesn't select the correct entries but only the ones with da_expire empty.
How can I fix it?
In the first place, why are you storing it as string?
You need to convert it to date using MySQL's builtin function so you can be able to compare it with today's date.
WHERE STR_TO_DATE(expire, '%Y/%m/%d %H:%i') < CURDATE()
This will be a little slower since it will not use any index if you have one defined on the column.
MySQL Docs: STR_TO_DATE()
Use STR_TO_DATE(expire, '%m/%d/%Y') instead of expire in the query. I have assumed you are storing the date in month day year format. You will need to adjust the format as per the string format. However, for performance reasons convert the type of expire during load/insert process .

can mysql find the year value of a unix timestamp?

im storing the dates that entries were posted on in the db using a standard unix timestamp.
is it possible, using only a mysql query (no php logic), to select entries that were posted in a certain year?
id like to avoid retrieving ALL entries and then using php to filter on year value. i could store the year in a separate field of course, just curious about this
This should be what you're after:
SELECT FROM_UNIXTIME(my_unix_timestamp_column, '%Y') AS year FROM table_name WHERE my_unix_timestamp_column BETWEEN UNIX_TIMESTAMP('2004-01-01 00:00:00') AND UNIX_TIMESTAMP('2004-12-31 23:59:59');
You only want MySQL to do the hard work of extracting the year once:
SELECT your, columns
FROM posts
WHERE postdate BETWEEN UNIX_TIMESTAMP('20080101') AND (UNIX_TIMESTAMP('20090101')-1)
Obviously, this adapts easily to extract posts within a certain month or day or decade etc.
maybe use the FROM_UNIXTIME() function
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_from-unixtime
A better way to do that is to use a little bit of PHP to create the unix timestamp you want. If it is this year try
$timestamp = strtotime("January, 1, 2009");
$db->query("Select * from table where time < $timestamp");
This is just an example, but you will be able to quickly narrow your results and only do very minimal php logic.
Depends of your mysql version. 5.1 has this neat function FROM_UNIXTIME(unix_timestamp,format)
mysql> SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(),
-> '%Y %D %M %h:%i:%s %x');
-> '2007 30th November 10:30:59 2007'