Questions tagged [alias]

Within a query, tables or subqueries may be aliased for readability and so that the same table can be referenced more than once in the query with different join conditions.

Tables and nested subqueries may be aliased within a SQL query, helping with readability, and allowing a table to be referenced more than once with different join conditions. An example of a query with sub-query and table aliases below.

select a.foo
      ,b.bar
      ,b.BarCount
  from (select b.bar
              ,count (*) as BarCount
          from BarTable b
          join OtherTable o
            on b.OtherTableID = o.OtherTableID
         group by b.bar) b
  join Foobar a
    on a.bar = b.bar

Table Foobar is aliased as a, and the nested subquery has an alias b. A nested subquery has a separate name-space for aliases as can be seen in the use of the alias b in both the parent and child queries to note different things. Note that this is possible, but not necessarily recommended as it can be confusing to people reading the code. It may also be desirable to use more meaningful aliases.

SQL statements may have an optional AS statement for aliasing, e.g.

select [...]
  from Foo       as a
  join Bar       as b
    on a.BarID = b.BarID

Aliases are necessary if a table is to be included more than once with different join conditions in the same query. A common example of this is a self-join such as the query below.

select par.BusinessUnitName    as ParentBusinessUnit
      ,chl.BusinessUnitName    as ChileBusinessUnit
  from BusinessUnit par
  join BusinessUnit chl
    on chl.ParentBusinessUnitID = par.BusinessUnitID

In this case the table BusinessUnit cannot be specified for both sides of the join without disambiguating which side a given expression is referring to. Aliases allow this to be specified.

81 questions
5
votes
1 answer

Two joins on same table in SQL

I've got 2 SQL tables: NAMES and RELATIONSHIPS Currently NAMES just has 2 columns: name and name_id. The other is a list of relationships between people in the NAMES table. It has 3 columns: primaryperson_id, relatedperson_id, and relationship_id.…
WebUserLearner
  • 153
  • 1
  • 3
0
votes
0 answers

Using Alias in Calculations

I know that this Problem was addressed before but my SQL knowledge is not that good to figure it out. Maybe you can help me. select ProductionLine, Product, POId, BatchNumber, Sum(Prime) as Prime, Sum(Offspec) as…
Pascal Sparla
  • 3
  • 1
  • 1
  • 2
-1
votes
2 answers

For a query can you have a two word alias

What I want to do is SELECT COUNT(CustomerID) as CC as 'Customer Count', Country FROM Customers GROUP BY Country HAVING CC > 5 ORDER BY CC DESC; Which is wrong. What is the right way? From: W3schools.com
David King
  • 1
  • 1
  • 1
  • 2