How to use an Alias in MySQL calculations?

MySQLMySQLi Database

Let us first create table. The query to create a table is as follows −

mysql> create table AliasDemo
   −> (
   −> Id int
   −> );
Query OK, 0 rows affected (0.52 sec)

Insert some records in the table with the help of insert command. The following is the query to insert records −

mysql> insert into AliasDemo values(20);
Query OK, 1 row affected (0.45 sec)

mysql> insert into AliasDemo values(30);
Query OK, 1 row affected (0.20 sec)

mysql> insert into AliasDemo values(40);
Query OK, 1 row affected (0.83 sec)

Now you can display all records with the help of select statement −

mysql> select *from AliasDemo;

The following is the output −

+------+
| Id   |
+------+
|   20 |
|   30 |
|   40 |
+------+
3 rows in set (0.00 sec)

Here is the query to set alias in calculation −

mysql> select Id,100 as MyNumber ,(select MyNumber)*Id as MultiplyWith100 from AliasDemo;

The following is the output −

+------+----------+-----------------+
| Id   | MyNumber | MultiplyWith100 |
+------+----------+-----------------+
|   20 |      100 |            2000 |
|   30 |      100 |            3000 |
|   40 |      100 |            4000 |
+------+----------+-----------------+
3 rows in set (0.00 sec)

You can implement it in single execution. The query is as follows −

mysql> select 100 as MyNumber,(select MyNumber)*10 as MultiplyWith100;

The following is the output −

+----------+-----------------+
| MyNumber | MultiplyWith100 |
+----------+-----------------+
|      100 |            1000 |
+----------+-----------------+
1 row in set (0.00 sec)
raja
Published on 11-Jan-2019 08:28:28
Advertisements