How to name the columns in a result set
By default, a column in a result set is given the same name as the column in the base table. However, you can specify a different name if you need to. You can also name a column that contains a calculated value. When you do that, the new column name is called a column alias. Figure 3-4 presents two techniques for creating column aliases.
The first technique is to code the column specification followed by the AS keyword and the column alias. This is the ANSI-standard coding technique, and it's illustrated by the first example in this figure. Here, a space is added between the two words in the name of the InvoiceNumber column, the InvoiceDate column is changed to just Date, and the InvoiceTotal column is changed to Total. Notice that because a space is included in the name of the first column, it's enclosed in brackets ([]). As you'll learn in chapter 10, any name that doesn't follow SQL Server's rules for naming objects must be enclosed in either brackets or double quotes. Column aliases can also be enclosed in single quotes.
The second example in this figure illustrates another technique for creating a column alias. Here, the column is assigned to an alias using an equal sign. This technique is only available with SQL Server, not with other types of databases, and is included for compatibility with earlier versions of SQL Server. So although you may see this technique used in older code, I don't recommend it for new statements you write.
The third example in this figure illustrates what happens when you don't assign an alias to a calculated column. Here, no name is assigned to the column, which usually isn't what you want. That's why you usually assign a name to any column that's calculated from other columns in the base table.
Two SELECT statements that name the columns in the result set
A SELECT statement that uses the AS keyword (the preferred technique) SELECT InvoiceNumber AS [Invoice Number], InvoiceDate AS Date, InvoiceTotal AS Total FROM Invoices A SELECT statement that uses the equal operator (an older technique) SELECT [Invoice Number] = InvoiceNumber, Date = InvoiceDate, Total = InvoiceTotal FROM Invoices
The result set for both SELECT statements
A SELECT statement that doesn't provide a name for a calculated column
SELECT InvoiceNumber, InvoiceDate, InvoiceTotal,InvoiceTotal - PaymentTotal - CreditTotalFROM Invoices
Description
Figure 3-4 How to name the columns in a result set