Neil
Neil

Reputation: 485

Alias Column Names at the Database Level [MySQL]

"Alias" is probably the wrong word, since that's used in the context of referencing column/table names as something else in a Query.

What I'm interested in is if there's a way to give a column two names in the database. If I were to print such a table, it would look like this:

mysql> SELECT * FROM User;
+--------------------------+-----------------+
| id | username | uname    | password | pswd |
+----+---------------------+-----------------+
|  0 | [email protected] |    some_pw_hash | 
|  1 | [email protected] |    some_pw_hash |
+--------------------------------------------+ 

In this case, username and uname would be synonymous in query statements, as would password and pswd.

So the following statements would have the same output:

mysql> SELECT id, username FROM User;
...
mysql> SELECT id, uname FROM User;
...

I would like to avoid having to do something like

mysql> SELECT id, username AS uname FROM User;

So, does a feature like this exist?

Cheers, Neil

Upvotes: 2

Views: 1235

Answers (2)

Ken White
Ken White

Reputation: 125748

No, this is not possible. To do so, you'd have to add a new, actual second column and use triggers to keep them in sync, which would be silly.

Just write your SQL properly to use the proper column names.

Upvotes: 7

mdahlman
mdahlman

Reputation: 9400

If you don't mind selecting from V_User instead of User, then views can get you what you need.

CREATE VIEW V_User AS
SELECT username as username,
       username as uname
FROM User;

Then these 2 queries have the same result:

mysql> SELECT id, username FROM V_User;
...
mysql> SELECT id, uname FROM V_User;
...

As Ken points out, this is not precisely what was asked. But depending on the precise context, it might be just what's needed.

Upvotes: 3

Related Questions