Replace character in MySQL varchar - mysql

I'm trying to convert a column named A with "YYYY/MM/DD" varchar (already inserted data) to a "YYYY-MM-DD" date. As an example I need the 1987/12/23 (varchar column) data to end up 1987-12-23 (date column), probably using UPDATE and REPLACE.

Try something like this:
UPDATE table
SET A = replace(A, '/', '-')
WHERE A LIKE '____/__/__';

As tadman pointed out, you can use the REPLACE function.
UPDATE `table` SET `A`=REPLACE(`A`,'/','-')

Related

SQL Query to concat a string in the database

I have a database table, with a column that contains integers. Each entry is a phone number, and they are all missing a zero at the beginning.
e.g. I have 798514586,
785558999
I want to run a SQL query that will modify each entry by putting a zero infront of it.
So the result will be
0798514586,
0785558999
IS there such a query to do this?
Try this
Syntax:
UPDATE <table> SET <column_to_update> = CONCAT(<string_to_concat>, <column_to_update>)
Example:
UPDATE contacts SET phone = CONCAT('0', phone)
I suppose you dont't want to add leading zero if it already exists:
update TableName
set SomeColumn = concat('0', SomeColumn)
where SomeColumn not like '0%'
It's not a good idea to store phone numbers as INTs, it's better to use a VARCHAR here. I would suggest you do add a new varchar column:
ALTER TABLE numbers ADD COLUMN phone_new VARCHAR(15);
then you can use an UPDATE query:
UPDATE numbers
SET
phone_new = CONCAT('0', phone)
MySQL will automatically cast the number to a string, and using CONCAT you can add a leading zero.
You can try by this:
update tableName set fieldName = CONCAT('0',fieldName)
You can use LPAD :
Update _table set _col = LPAD(_col , 10, '0');

Converting String Data Value into date

Good Morning All;
I currently have a MySQL table where there are 3 date fields (Columns) that were loaded as strings in this format 20140101 YYYYmmdd. I would like to convert this to a date format 2014/01/01 YYYY/mm/dd. Can someone please provide a simple sql syntax that would alter the table to a date format from a string and change the column to display the dates like this 2014/01/01 and not like 20140101. Thanks to all
Try this:
date_format(str_to_date(datecolumn, '%Y%m%d'),'%Y/%m/%d')
If you just want to reformat the values in the VARCHAR column, assuming that the column with sufficient length e.g. VARCHAR(10), and all the values are eight characters in length...
You could do something like this:
UPDATE mytable t
SET t.mycol = CONCAT( LEFT( t.mycol ,4)
, '/'
, SUBSTR( t.mycol ,5,2)
,'/'
, SUBSTR( t.mycol ,7,2)
)
WHERE CHAR_LENGTH(t.mycol) = 8
We want something in the statement that will prevent the statement from "working" a second time, if it's inadvertently re-run. It doesn't have to be CHAR_LENGTH. We might want to include a check that the value doesn't already contain a slash character AND t.mycol NOT LIKE '%/%'.
But why on earth are "date" values being stored in character columns, rather than in DATE datatype, which is custom designed for storing and working with date values?
ALTER TABLE mytable MODIFY mycol DATE ... ;
(If the column is defined as NOT NULL, has a default value, has a comment, those attributes can be retained, they need to be included in the new column specification, e.g.
ALTER TABLE mytable MODIFY mycol DATE NOT NULL COMMENT 'creation date';
Note that DATE columns do not have a "format" per se. When converting to string, MySQL uses date format '%Y-%m-%d'. And MySQL expects string literals representing date values to be in that same format. To get a value from a DATE column converted to string in format 'yyyy/mm/dd'.
SELECT DATE_FORMAT(date_col,'%Y/%m/%d') AS date_col
To get a string value in that format converted to DATE datatype
SELECT STR_TO_DATE('2015/06/01','%Y/%m/%d')

Adding text to each column of MYSQL Database

I have a database table in MYSQL with around 1000 rows. In the table I have a column called 'overview'. In each row, this column has some value and at the end of that value I have a specific line (text) starting with: 'Source...'
Now what I want is, I want to remove this line from each column and replace it with some other text content.
I believe it can be accomplished with some smart query.
You can simply use REPLACE in your query like this
UPDATE your_table SET col_name = REPLACE(col_name , ‘Source...’, ‘new_val’)
WHERE col_name LIKE '%Source...';
Check Out the SQLFIDDLE.
MySQL database has a handy and simple string function REPLACE() that allows table data with the matching string (from_string) to be replaced by new string (to_string).
The syntax of REPLACE is:
REPLACE (text_string, from_string, to_string)
In your case, you can do this way:
UPDATE `tableName` SET `column` = REPLACE(column , 'Source...', 'Replaced Value')
Use Replace
update TBL
set overview = Replace(picture, 'Source..', 'replacement')
keep a backup of the table before anything.Or you can do it on a copy.
you can do this by following:
update table_name set col_name = replace(column_name , ‘Source...’, ‘Replaced String...’);

mysql change date format

I have a date field (tinytext) holding date information in format of "dd-mm-yy" e.g 07-01-90. Using a mysql query I want to change it to yyyy-mm-dd date format. I tried the code below but nothing happens.
mysql_query("UPDATE Table SET date=STR_TO_DATE('date','%Y,%m,%d')");
You're using the correct function STR_TO_DATE(str,format) to achieve the goal, but you're making two mistakes:
In your query the format argument does not match the string expression format. You said it's in dd-mm-yy format while you passed %Y,%m,%d (comma separated) to the format argument. The query will return a "incorrect datetime value" error. You should use %d-%m-%Y.
You can't change data type of a column on the fly, by setting different type of the value being passed. You have to first update the values and then change data type for column.
So, summarizing:
mysql_query("UPDATE `Table` SET `date` = STR_TO_DATE(`date`, '%d-%m-%Y')");
mysql_query("ALTER TABLE `Table` CHANGE COLUMN `date` `date` DATE");
Additionally, consider switching to the recommended PDO extension in place of old and slowly deprecated mysql extension.
Error in your query
is STR_TO_DATE(date, '%Y-%m-%d')
mysql_query("UPDATE Table SET date=STR_TO_DATE(date,'%Y-%m-%d')");
Try this:
INSERT INTO table(date_field) VALUES(STR_TO_DATE('December 8, 2010','%M %d,%Y'));
Try it with DATE_FORMAT() function.
mysql_query("UPDATE Table SET date=DATE_FORMAT(date,'%Y,%m,%d')");
To display 2 digit year
mysql_query("UPDATE Table SET date=DATE_FORMAT(date,'%y-%m-%d')");
To display 4 digit year
mysql_query("UPDATE Table SET date=DATE_FORMAT(date,'%Y-%m-%d')");
I'd say you have to do this:
UPDATE table_name SET date = DATE_FORMAT('date', %Y-%m-%d);
If you are using my_sql with php, you can use date function

How to convert a varchar column type to date type without losing the dates

I am looking for a way to change the datatype of a column. Currently, in my database, the date columns types were defined as varchar and I need to convert them back to the date type.
Any idea how to do it?
You will need to adapt this based your your exact table structure but something like;
CREATE TABLE temp (startdate varchar(255), stuff varchar(255));
INSERT INTO temp
SELECT startdate,stuff
FROM mytable;
TRUNCATE TABLE mytable;
ALTER TABLE mytable ALTER COLUMN startdate DATETIME NOT NULL;
INSERT INTO mytable
SELECT CAST(startdate AS DATETIME), stuff FROM temp;
DROP TABLE temp;
First, create the new column with type data
Next, run update query, to populate the new column with the value of the old one, applying any conversion if needed
Next, drop the old column
Finally, rename the new column to the old one
Create a new DATE column with a temporary name
Populate the new column with an UPDATE query that makes use of STR_TO_DATE()
If everything's right, remove the VARCHAR column and rename the DATE column.
Mysql default date format is : YYYY-MM-DD . If your try to insert the date otherwise, as you actually did, the date will be inserted with these values : 000-00-00, giving you a hint to the acceptable date format for mySql.
Wanna share this for SQL server users. For me this method is much convenient and safer.
In your Table create new column "NewDate" (temporarily or name whatever you want).
Make sure no invalid Datetime format in the Table you want to convert. Try those formats here: https://www.w3schools.com/sql/trysqlserver.asp?filename=trysql_func_sqlserver_cast3 <--- you need to check thoroughly otherwise there would be an error executing the command below.
Execute this command:
UPDATE myTable
SET NewDate = CAST(OldDate AS datetime)
WHERE (OldDate <> '') AND (OldDate IS NOT NULL) --to make sure you cast only what is needed otherwise there would be an error.
You can now delete the old column i.e. "OldDate".
Finally you can drag and drop the new table you've created to the slot where you just deleted the old column in the table design.
If the field of your column is VARCHAR and stored date as DD-MM-YYYY then we have to convert the date in YYYY-MM-DD format by following PHP code.
$cd = array();
$cd1 = array();
$cdf = array();
$getdata = mysqli_query($link,"SELECT columnname FROM tablename");
while($row=mysqli_fetch_array($getdata))
{
$cd = $row['columnname'];
$cd1 = strtotime($cd);
$cdf = date('Y-m-d',$cd1);
mysqli_query($link,"UPDATE tablename SET columnname =
REPLACE(columnname,'$cd','$cdf')");
}
After running this PHP code, in your MySQL table change the datatype of your column to 'DATE'.
It works for me without losing or truncate data.