Always Get Better

Archive for June, 2008

Optimize SQL Queries by Using Aliases

Monday, June 30th, 2008

When joining tables in SQL, we often use aliases to shorten table names. Consider this query joining order lines (details) with orders inside the database:

[source:sql]
SELECT O.OrderID, FirstName, LastName, ItemName, Quantity
FROM Orders O
INNER JOIN OrderDetails OD
ON O.OrderID = OD.OrderID;
[/source]

The above may work, but behind the scenes the database’s query analyzer has to associate each of the selected columns with their respective tables. Although this is a fast process, it can be skipped entirely by simply fleshing out the query like this:

[source:sql]
SELECT O.OrderID, O.FirstName, O.LastName, OD.ItemName, OD.Quantity
FROM Orders O
INNER JOIN OrderDetails OD
ON O.OrderID = OD.OrderID;
[/source]