Using MySQL & SQL Server
ID sDate
001 03/06/2010
002 07/08/2010
....
....
sDate Datatype is varchar
Format mm/dd/yyyy
I want to take the date count means How many days is still there, It should compare the system date...
How to convert my varchar to datetime datatype, then how to compare the mysdate to system for getting the totalday counts
sDate - SystemDate = Totalday
ExpectedOutput
ID sDate Totaldays
001 03/07/2010 3 days
002 07/07/2010 7 days
.....
How to make a query for this condition. Need query help.
Your question states MySQL & SQL Server so here is both:
SQL Server datediff function:
SELECT ID, DATEDIFF(DAY, GETDATE(), CONVERT(DATETIME, sDate)) FROM TABLE
MySQL datediff function:
SELECT ID, DATEDIFF(CURDATE(), STR_TO_DATE(sDate, '%c/%d/%Y')) FROM TABLE
This uses the STR_TO_DATE function to convert the varchar to a date and assumes that the format of your date strings is in the format month/day/year.
Gopal, in response to your "How to convert varchar to datetime in mysql...", it's easy:
ALTER TABLE sometable CHANGE sDate sDate datetime;
and MySQL will happily attempt to convert the values for you. However, if it can't properly parse the original date string, that record's sDate will get set to NULL or 0000-00-00. You'll have to massage the sDate field first to convert it to a more normal MySQL format for date strings, which is YYYY-MM-DD. A bruteforce hack would be:
UPDATE sometable SET sDate=CONCAT(
SUBSTR(sDate, 6, 4),
'/',
SUBSTR(sDate, 3, 2),
'/',
SUBSTR(sDate, 0, 2)
);
Of course, this is assuming that your dates are in DD/MM/YYYY format. If they're MM/DD/YYYY, then just swap the middle and last SUBSTR calls. Once this update's completed, then you can use the ALTER TABLE to change field types.
And of course, for anything that affects the entire table like this, make sure you have a backup of it first.
Related
I have a column called "month" that I have imported into MySQL:
Datatype: TEXT
Display: 2021-01
My goal is to convert this column into some sort of DATE datatype (ie. DATE, DATETIME) so that MySQL will recognize it as yyyy-mm.
I have tried the following method but still received NULL
--- (1) add dummy date
SELECT CONCAT(month, '-01')
FROM tablename;
--- (2) convert to DATE datatype
SELECT CONVERT(month,DATE)
FROM tablename; -- if I just run (1) and (2) i receive NULL
--- (3) Format back to yyyy-mm format
SELECT FORMAT(month,'yyyy-mm') AS month2
FROM tablename; -- If i run from (1) to (3), i receive 2,021
So:
How do i solve this problem conversion problem in MySQL
Is there anyway i could have prevented this before/while importing?
If you are looking for a one time migration from your string format to a SQL date or datetime, then you can just do
UPDATE tablename SET columname = CONCAT(columname, '-01');
and then update the column to a DATE or a DATETIME.
Alternatively if you do not want to update the values you could use the following queries to cast to a DATE or a DATETIME:
SELECT CAST(CONCAT(columnname, '-01') AS DATE) FROM tablename
or
SELECT CAST(CONCAT(columnname, '-01') AS DATETIME) FROM tablename
I'm trying to convert a string to date with a format of yyyy/mm to yyyy
STR_TO_DATE(SUBSTRING(time,1,4), '%Y')
This returns null for every value as well as when I try to convert without getting rid of the mm:
STR_TO_DATE(REPLACE(time,'/',''), '%Y%m')
This method has worked for me before, I'm at a loss for what I'm missing.
Thanks in advance!
Edit for clarification:
Eventually I am going to insert the year into a column with data type year, so I need to convert a varchar to a date type so I can extract the year in order to insert the data into a new table
I am in the process of making sure it will work before populating the new column with a command like this:
INSERT INTO table (year)
SELECT STR_TO_DATE(SUBSTRING(time,1,4), '%Y')
FROM `origtable`
I'm trying to convert a string to date with a format of yyyy/mm to yyyy
Just use left():
select left(time, 4) as yyyy
There is no need to convert to a date or datetime. You want a simple string operation.
EDIT:
year is a really weird type. I would just use an integer. But if you are using it, you can insert a full date into the field:
select date(concat(time, '/01'))
The resulting date can be inserting to a year column.
The default date format in my SQL is : '2019-05-06'
and its fine but when i insert date to my table i want this format 2019-5-6 not the above format
It means month and day must be start 1 to 30 not 01 to 31.Is there any way to change default format in my sql?
You seem to be looking for the MySQL STR_TO_DATE function :
It takes a string str and a format string format. STR_TO_DATE() returns a DATETIME value if the format string contains both date and time parts, or a DATE or TIME value if the string contains only date or time parts.
So if the date coming out of your application is like '2019-5-6', to convert it to a MySQL date you need :
STR_TO_DATE('2019-5-6', '%Y-%c-%e')
In an INSERT statement :
INSERT INTO mytable VALUES(1, STR_TO_DATE('2019-5-6', '%Y-%c-%e'));
Tip :
%Y : Year as a numeric, 4-digit value
%c : numeric month name (0 to 12)
%e: day of the month as a numeric value (0 to 31)
The default way to store a date in a MySQL database is by using DATE. The proper format of a DATE is: YYYY-MM-DD. If you try to enter a date in a format other than the Year-Month-Day format, it might work but it won't be storing the dates as you expect.
In order to run a MySQL Insert command and add the current date into your table you can use MySQL's built-in function CURDATE() in your query.
An example of how to Insert a Date in MySQL using CURDATE
$query_auto = "INSERT INTO tablename (col_name, col_date) VALUE ('DATE: Auto CURDATE()', CURDATE() )";
Also, you can run a query to set the date manually
An example of how to Insert a Date in MySQL manually
$query_manual = "INSERT INTO tablename (col_name, col_date) VALUES ('DATE: Manual Date', '2008-7-04')";
It is recommended to do the date formatting when doing a query, like so:
SELECT DATE_FORMAT(BirthDate, "%W %M %e %Y") FROM Employees;
You can find more examples of formatting the date here:
https://www.w3schools.com/sql/func_mysql_date_format.asp
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.
I have a database(table), in which 2 fields are:
fromdate varchar(20)
todate varchar(20)
Dates are stored in this fashion:
YYYY-MM-DD HH:mm:ss
For ex: '2014-10-30 10:10:10' in database.
Now I want to compare two dates and fetch records from database by using query, 2014-09-10 10:10:10(fromdate) to 2014-10-10 10:10:10(todate)
How to fetch all accurate records.. Is there any kind of solution..
Thanks.
Just compare the string without extra overhead.
This format "YYYY-MM-DD HH:mm:ss" shares chronological and literal alphabetical order
SELECT * FROM someTable
WHERE fromdate >= '2014-09-10 10:10:10' AND todate <= '2014-10-10 10:10:10'
Also, I would create an index on those columns.
i have a database(table), in which 2 fields are: fromdate varchar(20)
todate varchar(20)
It is a design flaw. Date should always be a DATE data type and never be string.
dates are stored in this fashion YYYY-MM-DD HH:mm:ss
DATE is never stored in any format. it is for us, human beings to understand.
Oracle stores DATE in total of 7 bytes. Each byte in it stores values for an element of the DATE as follows:
Byte Description
---- -------------------------------------------------
1 Century value but before storing it add 100 to it
2 Year and 100 is added to it before storing
3 Month
4 Day of the month
5 Hours but add 1 before storing it
6 Minutes but add 1 before storing it
7 Seconds but add 1 before storing it
for eg :"2014-10-30 10:10:10" in database.
Now i want to compare two dates and fetch records from database by
using query, 2014-09-10 10:10:10(fromdate) to 2014-10-10
10:10:10(todate)
Just use to_date('2014-10-30 10:10:10', 'YYYY-MM-DD HH24:MI:SS')
NOTE This is for Oracle database. I see you have tagged SQL Server too. I don't understand why did you do that.
Use STR_TO_DATE()
select * from your_table
where str_to_date(fromdate, '%Y-%m-%d %H:%i:%s') >= '2014-09-10 10:10:10'
and str_to_date(todate, '%Y-%m-%d %H:%i:%s') <= '2014-10-10 10:10:10'
First, you can use convert function:
SELECT CONVERT(Datetime, '2014-10-30 18:00:00', 120)
Second, if you can't change the existing columns and their type, it does not mean that you can't add additional column with correct date type that duplicates the meaning of "wrong" column. This would both save your legacy code and help you in new development, as all the operations with convertation in queries are very expensive in terms of performance.