Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to alias a field or column in MySQL?

I'm trying to do something like this. But I get an unknown column error:

SELECT SUM(field1 + field2) AS col1, col1 + field3 AS col3 from core 

Basically, I want to just use the alias so that I won't need to perform the operations performed earlier. Is this possible in mysql?

like image 998
user225269 Avatar asked May 21 '11 11:05

user225269


People also ask

What is column alias in MySQL?

SQL aliases are used to give a table, or a column in a table, a temporary name. Aliases are often used to make column names more readable. An alias only exists for the duration of that query. An alias is created with the AS keyword.

How do I specify a column alias?

The basic syntax of a table alias is as follows. SELECT column1, column2.... FROM table_name AS alias_name WHERE [condition]; The basic syntax of a column alias is as follows.

What is the benefit of using an alias in MySQL?

Advantages of MySQL AliasesIt makes the column or table name more readable. It is useful when you use the function in the query. It can also allow us to combines two or more columns. It is also useful when the column names are big or not readable.

How do I rename a column in MySQL?

Rename MySQL Column with the CHANGE Statement Enter the following command in your MySQL client shell to change the name of the column and its definition: ALTER TABLE table_name CHANGE old_column_name new_col_name Data Type; You can change the data type of the column or keep the existing one.


1 Answers

select @code:= SUM(field1 + field2), @code+1 from abc;

But, please be aware of the following (from the MySQL 5.6 docs):

As a general rule, other than in SET statements, you should never assign a value to a user variable and read the value within the same statement. For example, to increment a variable, this is okay:

SET @a = @a + 1; 

For other statements, such as SELECT, you might get the results you expect, but this is not guaranteed. In the following statement, you might think that MySQL will evaluate @a first and then do an assignment second:

SELECT @a, @a:=@a+1, ...; 

However, the order of evaluation for expressions involving user variables is undefined.

So, use at your own risk.

like image 99
Ravi Parekh Avatar answered Sep 16 '22 23:09

Ravi Parekh