Aliases


At this point, we should discuss the concept of column and table aliasing.

We have the ability to rename columns or expressions in a SELECT statement, and the new name will be what is shown in the output. For example, we can use the following query:

 
 select name as employeeName from employee; 

Here, we have renamed the column name as employeeName just within the context of this query. The results of running this query on the employee database are as shown here:

 
 +---------------+  employeeName   +---------------+  Ajay Patel      Nora Edwards    Candy Burnett   Ben Smith      +---------------+ 4 rows in set (0.01 sec) 

You can see that in the results, the contents of the name column are now listed under the heading employeeName .

The identifier employeeName is known as an alias . There are some rules about what we can and cannot do with aliases, and we will cover these as we come to them.

This specific example of an alias is not particularly useful. As we begin to write more complex queries and queries that involve calculation, you should see its power.

We can also use aliases for tables, like this:

 
 select e.name from employee as e; 

This will give the same result as if we had written the query not using aliases. This notation will become useful when we begin running queries over multiple tables in the next chapter.

In the last two examples, the keyword AS is optional. We could simply have written

 
 select name employeeName from employee; 

and

 
 select e.name from employee e; 

You may choose to write the queries either way. It is simply a matter of style. As you can see here and in many other places in the book, there are many ways to write the same SQL query. Individual programming style in SQL varies as it does in other languages.



MySQL Tutorial
MySQL Tutorial
ISBN: 0672325845
EAN: 2147483647
Year: 2003
Pages: 261

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net