別名(エイリアス)

SQL Serverでクエリ性能を改善する

Dean Smith

Founder, Atamai Analytics

別名とは?

  • 次で使用:
    • テーブル
    • サブクエリ
  • 一時的。実行時のみ有効
  • 可読性を向上
  • 必要な場合がある
SQL Serverでクエリ性能を改善する

別名を使う理由

  • 長いテーブル名・列名の反復を回避
  • 結合したテーブルと対応列を識別しやすく
  • 新しい列を識別
  • サブクエリを識別
  • 同名列によるあいまいさを回避
  • 列名を変更
SQL Serverでクエリ性能を改善する

結合時の同名列のあいまいさ

SELECT CountryName, 
       Code2, 
       Capital, 
       Pop2017
FROM Nations
INNER JOIN Cities
  ON Capital = CityName;
-----------------------------------------------
-- エラー: Pop2017 列は
Nations と Cities の両方に存在

Ambiguous column name 'Pop2017'.
SQL Serverでクエリ性能を改善する

結合時のテーブル別名

-- テーブルに別名: Nations を n、Cities を c
SELECT n.CountryName, 
       n.Code2, 
       n.Capital, 
       c.Pop2017 -- 都市の人口
FROM Nations AS n
INNER JOIN Cities AS c
  ON n.Capital = c.CityName;
CountryName Code2 Capital Pop2017
United Kingdom GB London 346774
Canada CA Ottawa 874433
France FR Paris 10437
Reunion RE Saint-Denis 1067
... ... ... ...
SQL Serverでクエリ性能を改善する

列名の変更

-- 列に別名を付与
SELECT n.CountryName AS Country, 
       n.Code2 AS CountryCode, 
       n.Capital, 
       c.Pop2017 AS Population
FROM Nations AS n
INNER JOIN Cities AS c
  ON n.Capital = c.CityName;
Country CountryCode Capital Population
United Kingdom GB London 346774
Canada CA Ottawa 874433
France FR Paris 10437
Reunion RE Saint-Denis 1067
... ... ... ...
SQL Serverでクエリ性能を改善する

新しい列

-- 新しい列に MaxMagnitude の別名
SELECT Country, 
       NearestPop AS City,
       MAX(Magnitude) AS MaxMagnitude
FROM Earthquakes 
GROUP BY Country, NearestPop;
Country City MaxMagnitude
PE Acar 7.1
US Aguadilla 7.7
MX Aguililla 7.2
PW Airai 7.8
PG Aitape 7.6
... ... ...
SQL Serverでクエリ性能を改善する

サブクエリ

SELECT n.CountryName AS Country, 
       n.Capital, 
       e.MaxMagnitude
FROM Nations n
INNER JOIN
        (SELECT Country, NearestPop AS City
                ,MAX(Magnitude) AS MaxMagnitude
        FROM Earthquakes 
        GROUP BY Country, NearestPop) e 
              -- サブクエリに e の別名
    ON n.Code2 = e.Country AND n.Capital = e.City;
Country Capital MaxMagnitude
Fiji Suva 7.9
Guam Hagatna 7.8
Peru Lima 7.6
Turkmenistan Ashgabat 7.3
... ... ...
SQL Serverでクエリ性能を改善する

Ayo berlatih!

SQL Serverでクエリ性能を改善する

Preparing Video For Download...