Tuesday, 26 July 2016

AS clause



AS clause is used to give different names to column headers.

mysql> DESC employee;
+--------+---------------+------+-----+---------+-------+
| Field  | Type          | Null | Key | Default | Extra |
+--------+---------------+------+-----+---------+-------+
| id     | int(11)       | NO   | PRI | NULL    |       |
| name   | varchar(25)   | YES  |     | NULL    |       |
| age    | int(11)       | YES  |     | NULL    |       |
| salary | decimal(10,4) | YES  |     | NULL    |       |
| mailId | varchar(25)   | YES  |     | NULL    |       |
| city   | varchar(10)   | YES  |     | NULL    |       |
+--------+---------------+------+-----+---------+-------+
6 rows in set (0.00 sec)  


mysql> SELECT * FROM employee;
+----+---------+------+-------------+---------------------+------------+
| id | name    | age  | salary      | mailId              | city       |
+----+---------+------+-------------+---------------------+------------+
|  1 | Hari    |   28 |  12345.6700 | hari@hari.com       | Bangalore  |
|  2 | Sandesh |   30 | 119345.0000 | sandesh@sandesh.com | Trivendram |
|  3 | Hari    |   33 |  12345.6700 | phalgun@hari.com    | Hyderabad  |
|  4 | Manju   |   30 |  87645.6700 | manju@sandesh.com   | Bangalore  |
|  5 | Rakesh  |   26 |  12345.0000 | rakesh@hari.com     | Bangalore  |
|  6 | Hari    |   38 |  87645.6700 | sankalp@sankalp.com | Chenai     |
|  7 | Vadiraj |   28 |  12345.6700 | vadi@hari.com       | Bangalore  |
|  8 | Sandesh |   28 |  87645.6700 | prasob@sandesh.com  | Trivendram |
|  9 | Kesav   | NULL | 123457.8900 | NULL                | NULL       |
| 10 | Hari    |   25 | 198345.0000 | hari@krishna.com    | Trivendram |
| 11 | Sandesh |   23 | 119345.6700 | phalgun@p.com       | Hyderabad  |
+----+---------+------+-------------+---------------------+------------+
11 rows in set (0.00 sec)



Suppose, you want to display name as Title, salary as ‘my income’, your query should looks like below.

mysql> SELECT name AS Title, salary AS 'My income' FROM employee;
+---------+-------------+
| Title   | My income   |
+---------+-------------+
| Hari    |  12345.6700 |
| Sandesh | 119345.0000 |
| Hari    |  12345.6700 |
| Manju   |  87645.6700 |
| Rakesh  |  12345.0000 |
| Hari    |  87645.6700 |
| Vadiraj |  12345.6700 |
| Sandesh |  87645.6700 |
| Kesav   | 123457.8900 |
| Hari    | 198345.0000 |
| Sandesh | 119345.6700 |
+---------+-------------+
11 rows in set (0.00 sec)


AS clause is also used in joins, I am going to explain about this in my next post





Previous                                                 Next                                                 Home

No comments:

Post a Comment