Always Get Better

Optimize SQL Queries by Using Aliases

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]

Tags: ,

Leave a Reply