Maria DB : Alter a field to a PERSISTENT Calculated - mysql

I have created a table and I wish to make a Computed Column from the concatenated values of three other fields in the table.
I want this Computed Field to take place at INSERT or UPDATE, so I am specifying PERSISTENT
I have tried the following code (in various ways) in phpMyAdmin but always get errors, which seem to be referencing immediately after ALTER table
I did not see a way of doing this when adding the field in phpMyAdmin, so I hoped I could ALTER it.
Alter TABLE 'tlImages'
CHANGE COLUMN tlImageQuery
AS CONCAT(tlImgTitle,"~",tlImgDescrip,"~",tlImgWhereWhen) PERSISTENT;
MariaDB version 10.0.29-MariaDB-cll-lve - MariaDB Server
phpMyAdmin . Version information: 4.0.10.18

First, lose single quotes around the table name, they are not suitable for this purpose. Use backticks or nothing.
You will still get a syntax error further in the statement, because AS clause should be in brackets. Add them.
You will still get a syntax error because you are missing column type before the AS (...) clause, add it.
You will still get a syntax error because CHANGE COLUMN needs two column names, old and new, use MODIFY instead.
Alter TABLE `tlImages`
MODIFY COLUMN tlImageQuery VARCHAR(128)
AS (CONCAT(tlImgTitle,"~",tlImgDescrip,"~",tlImgWhereWhen)) PERSISTENT
;
(Type VARCHAR(128) is given just as an example).

Related

Error when adding column with numeric name

I currently have a MariaDB database with columns named after dates : 20200105, 20200914 etc.
If I try to add a column using ALTER TABLE dates ADD COLUMN IF NOT EXISTS (test VARCHAR(255));, it works and the test column is created.
If I type ALTER TABLE dates ADD COLUMN IF NOT EXISTS (20201205 VARCHAR(255));, though (so, with a number replacing "test"), the creation does not work anymore and MariaDB tells me that there is an error with my SQL syntax.
I have tried to put quotes around the column name, but that does not work (not even with "test").
Is there something obvious I am missing ?
Use backticks to escape the column name:
ALTER TABLE dates ADD COLUMN IF NOT EXISTS (`20201205` VARCHAR(255));
But really best practice frowns upon the use of naming your database objects with mandatory backticks. The reason for using a name like 20201205 as a column name is that you will forever be needing to escape it using backticks. Also, from a data design point of view, your data should grow with new dates in terms of increasing the number of records, not columns.

Adding a calculated date column to a MySQL dataset

I have a column dateTime which consists of dates of the format "MM-DD-YYYY, hh-mm-ss" and I need to create a STORED column on the same table to get rid of the time element. I've tried:
ALTER TABLE table ADD COLUMN startOfDay AS(date(dateTime)) STORED;
but this gives a wrong syntax error. How do I make it work? I think the error is due to the AS part.
First when asking a question and you tell that you have a error, always show the error message in your post.
Secondly to use STORED columns you need MySQL 5.7 instance or higher.
At the moment I only have a 5.6 instance running so I can't test the query. But looking at the MySQL documentation I would suggest the following query syntax:
ALTER TABLE <table-name> ADD COLUMN <column-name> DATE GENERATED ALWAYS AS (DATE_FORMAT(<name-of-datetime-column>, `%Y-%m-%d`)) STORED COMMENT '<description>';
Just replace the placeholders with the names you have. To be sure and learn how things work, always check the MySQL reference manual on the subject.
See: https://dev.mysql.com/doc/refman/5.7/en/create-table-generated-columns.html

Alter ignore table add column if not exists using the SQL statement

i want to add a new column to a mysql table, but i want to ignore the adding of column, if the column already exists
i am currently using
ALTER IGNORE TABLE `db`.`tablename` ADD COLUMN `column_name` text NULL;
but this is throwing an error saying : "ERROR 1060 (42S21): Duplicate column name 'column_name'"
even though i am using the IGNORE, this is not working
i want this to work using the normal SQL statement, instead of a stored procedure
According to the documentation:
IGNORE is a MySQL extension to standard SQL. It controls how ALTER
TABLE works if there are duplicates on unique keys in the new table or
if warnings occur when strict mode is enabled. If IGNORE is not
specified, the copy is aborted and rolled back if duplicate-key errors
occur. If IGNORE is specified, only one row is used of rows with
duplicates on a unique key. The other conflicting rows are deleted.
Incorrect values are truncated to the closest matching acceptable
value.
That is, it is used for a different purpose, not all errors. What you want is something like ALTER TABLE ADD IF NOT EXISTS, and that syntax doesn't exist.
In a stored procedure, you can use an if statement to see if the column already exists (using INFORMATION_SCHEMA.COLUMNS).
Here is a SQL Fiddle that shows the same problem.

how to remove special characters from mysql field name

After importing an Excel table that contained some special characters (like carriage returns or line feeds) in the headers row, it seems that the phpMyAdmin utility handled this situation silently by inserting those chars in the field's name.
The problem arose later when I tried to import the table into other environments/tools like data integrators, etc. For example, the column "Date Start" was imported into the table as "Date\nStart", with a LINE FEED in the middle.
The field rename operation through phpMyAdmin fails with this error:
**\#1054 - Unknown column 'Date Start' in 'mytable'**
The obvious workaround would be to edit the original Excel file by hand (removing LF's) then reimporting the table in MySql as before, but I'm in the position of needing to refresh the schema while preserving the data in the table.
Next I tried this from an SQL panel in phpMyAdmin (note the \n in the field name, VARCHAR(16) is just an example, DATETIME or INT should work as well):
ALTER TABLE mytable CHANGE `Date\nStart` `Date Start` VARCHAR(16)
but again it gives error #1054 - Unknown column 'Date\nStart' in 'mytable'
I also checked the INFORMATION_SCHEMA db, but as #Steve stated below, it's a read-only database.
I'm using MySql 5.5.32 and phpMyAdmin 4.0.4.1 with a Win7 desktop. Any suggestions?
First of all, by reading the MySql manual you can appreciate (or hate) the extreme flexibility allowed by the naming rules, details on the special characters that are/aren't allowed in a table and column names can be found in this manual page:
https://dev.mysql.com/doc/refman/5.5/en/identifiers.html
After several attempts escaping the CR character I've found a solution that works from the phpMyAdmin SQL pane, I think it should work on command-line sessions as well (didn't try that).
In case you inadvertently created or imported columns with CR's in the name, it is possible to fix it by typing the ENTER key within the column name, inside the SQL ALTER TABLE statement (you MUST enclose names in backticks for this trick to work).
Example: To replace the unwanted 'Date\nStart' column name with 'Date Start' you should type this (please note, the CR/Enter at the end of the first line!):
ALTER TABLE mybuggytable CHANGE `Date
Start` `Date Start` VARCHAR(16)
As explained above, you can spot columns with CR's embedded with this statement:
USE INFORMATION_SCHEMA; SELECT * FROM COLUMNS WHERE COLUMN_NAME like '%\n%'
I typed the ALTER TABLE command in the my phpMyAdmin SQL pane, and it just worked fine.
I thought you couldn't write to INFORMATION_SCHEMA because of a permission issue, but after reading the MySQL Manual I realise this is expected behavior as the manual states:
Although you can select INFORMATION_SCHEMA as the default database with a USE statement, you can only read the contents of tables, not perform INSERT, UPDATE, or DELETE operations on them.
To achieve a table rename by using the RENAME TABLE command, first run a select query to find all the tables that need changing and then rename them replacing the carnage return with a space character.
To rename just a column from within a table the ALTER TABLE command can be used with the CHANGE COLUMN parameters, for example:
ALTER TABLE table_name CHANGE COLUMN 'Date\nStart' 'Date Start' DATETIME
I know you've already said that is the command you need, so I've tested this myself by firstly selecting the tables and then running the ALTER TABLE command and it worked fine. I was using the command line interface, so maybe the problem lies with phpMyAdmin - can you confirm it isn't encoding or escaping \n?
Here is what I tested via the command line and worked OK:
SELECT COLUMN_NAME
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE TABLE_SCHEMA = 'test_345'
AND TABLE_NAME LIKE '%\n%';
ALTER TABLE test_table1 CHANGE COLUMN 'Date\nStart' 'Date Start' DATETIME;
Either of these could be wrapped up into a routine should you think this would be useful in the future.

How do you change an autoincremented columns starting value through liquibase?

I am using MySql for my database. I have found how to set a column's starting autoincrement value when creating a table, but I need to know how to set a new starting value for an existing column. What does the liquibase script look like to do that?
The MySQL syntax is pretty straightforward:
ALTER TABLE mytable AUTO_INCREMENT = val ;
(Note that this is really a table attribute, not a column attribute. There can be only one column in a table declared to be AUTO_INCREMENT.)
This syntax isn't supported in SQL Server or Oracle; Oracle doesn't even have a concept of an "auto_increment" column, apart from a SEQUENCE object and a TRIGGER. SQL Server calls it an IDENTITY property. So I don't know how this statement would be represented in "liquibase" syntax, other than specifying that this statement is native MySQL syntax.
You can use addAutoIncrement (http://www.liquibase.org/documentation/changes/add_auto_increment.html) to change your existing AUTO_INCREMENT column.
Don't forget to specify columnDataType in the addAutoIncrement.
I used this yesterday for our project and it worked (for MySQL).