Welcome!

Welcome! Below you will find our latest published articles.

  How To Use The SQL Statement AS

April 15th, 2006

Many times the name of a column in a table may make perfect sense to you, but to someone not familiar with the structure of your database it could be very confusing. Consequently, when you need to create queries or reports for these people, you can’t use the actual column names. Another example would be where you need to combine the values in multiple columns or perform other operations on them. For the end user, all you want them to see is the result in a single column. This is where the AS statement comes in.

The AS SQL statement allows you to alias a column with another name, or put the result of multiple operations in one result column.

Here’s a simple example. We have a table named CustInfo with a number of columns, and we want to pull the following three columns from the table:

  • CustName - The customer’s name.
  • CustAddress - The customer’s address.
  • CustNum - The customer’s phone number.

CustName and CustAddress seem pretty straightforward, however you will want to rename them for your user into more friendly names. On the other hand, the name CustNum could mean many things to some not familiar with your database structure. We’ll want to rename this to “Customer Phone Number”.

Here’s the query we would use:

SELECT CustName AS [Customer Name], CustAddress AS [Customer Address], CustNum AS [Customer Phone Number] FROM CustInfo

*Note: This syntax is specific to Microsoft Access. The syntax may change depending on what database platform you are using.

After this query is run, the following would be returned:

Microsoft Access Screen Shot

As you can see, the column titles are much friendlier to an end user than the original column names.

Another example occurs when you want to perform an operation on multiple fields and have it come out as one field. For instance, let’s say we have the table below:

Microsoft Access Screen Shot

What if we want to total the two values in each record and return only this total in our query? The query to accomplish this is shown below:

SELECT (num1 + num2) AS Total FROM Table1

This is the result of running this query:

Microsoft Access Screen Shot

The resultant query has returned a clean table back to the end user, without them having to be aware of what’s going on underneath.

Overall, the AS statement is very easy to use, and very powerful. I find it especially useful when you have to create queries where the results can be put directly into a report with little to no manipulation of the result table.

Tags: , , , , , , ,