How to rename a column name which has been created by a math function in mysql? Using ALTER TABLE is giving ERROR: 1064 (42000)

All we need is an easy explanation of the problem, so here it is.

INPUT:

CREATE TABLE dist
-> SELECT ST_DISTANCE(POINT(x1,y1),POINT(x2,y2))
-> FROM config;

OUTPUT:

+------------------------------------------+
| ST_DISTANCE(POINT(x1,y1) , POINT(x2,y2)) |
+------------------------------------------+
|                        140.0071426749364 |
|                       139.30183056945089 |
|                        138.6001443000692 |
|                       137.90213921473443 |
|                       137.20787149431334 |
+------------------------------------------+

RENAME COLUMN INPUT

> ALTER TABLE dist
-> RENAME COLUMN ST_DISTANCE(POINT(x1,y1),POINT(x2,y2)) TO Values;

ERROR: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘(POINT(x1,y1),POINT(x2,y2)) TO Values’ at line 2

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Besides that Values is a very bad choice for a column name, as are all reserved words

You can give the column a name by creation. like

CREATE TABLE dist (`Values` DECIMAL(12,11))
 SELECT ST_DISTANCE(POINT(x1,y1),POINT(x2,y2)) as 'values'
 FROM config;

Method 2

Use backtics around the expression (which is the column name in the new table.)

ALTER TABLE dist
    RENAME COLUMN `ST_DISTANCE(POINT(x1,y1),POINT(x2,y2))` TO Values;

Note RENAME COLUMN was added in 8.0 and 10.5; if you have an older version, you must use the more verbose CHANGE COLUMN syntax.

(Oh, and be cautious about VALUES; it may be a reserved word.)

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply