5

I have a mysql table with the a column name of count that I need to rename. It was a bad choice for a column name in the early stages of the development. However, simply renaming has huge regression issues - several older versions of the app will still be referencing count, so I can't just simply or easily change the column name to something else.

Is there any method or technique I can use that will allow me to permanently alias the that column to something else? So eventually when the older app versions phase out we can then just drop the original name and make the alias the permanent name.

If an alias won't work or isn't possible, can someone suggest another idea? We really need to move the column away from being called count

Looking for something like:

// I don't think anything like this exists
alter table tableName change column count set alias countAlias ;   

ORIG:  SELECT * FROM tableName WHERE count=?
NEW: SELECT * FROM tableName WHERE countAlias=?

But where count and countAlias are the same column, so the query would work the same.

Sample Table:

create table user_data(user_id int, cDate date, count int);

mysql> select * from user_data;
+---------+--------+--------+
| user_id | cDate  | count  |
+---------+--------+--------+
1
  • 1
    You can probably use a generated column (check your server version supports it). In any case, count is annoying because it needs to be quoted every time but it's a valid name anyway. Commented Feb 16, 2021 at 15:33

2 Answers 2

5

You can create a generated column . . . which is a synonym for the column:

alter table tableName add countAlias int
    generated always as (count) virtual;

This makes the column part of the table. It is "calculated" when the value is referenced in a query.

3
  • i like this. And did not know you could do this. I added a sample table to the OP, could you append your answer to show what the new table would look like and what an INSERT would look like? Much appreciated.
    – rolinger
    Commented Feb 16, 2021 at 17:27
  • 2
    @rolinger . . . The INSERT doesn't change. You don't insert into generated columns. Commented Feb 16, 2021 at 18:05
  • This is not a useful solution because you cannot write to a generated column using INSERT or UPDATE. A virtual column would only work if you did nothing but read the column from your scripts. Commented Feb 10 at 21:22
2

you could create a vew

create view my_view 
select col1, ..coln, countAlias 
from your_table  

then you can query the view

Select * from my_view 
where countAlias= ?

Not the answer you're looking for? Browse other questions tagged or ask your own question.