MySQL の ORDER BY や GROUP BY に position を渡せるのを知って驚いたけど deprecated だった

ほぼタイトルママなんだけど

SELECT DATE(created_at), COUNT(1)
  FROM users
  GROUP BY 1;

ってクエリを見つけて、 GROUP BY 1 ってなんぞ……?という話。

MySQL のドキュメント には

[GROUP BY {col_name | expr | position}, ... [WITH ROLLUP]]

 

[ORDER BY {col_name | expr | position}

 

Columns selected for output can be referred to in ORDER BY and GROUP BY clauses using column names, column aliases, or column positions. Column positions are integers and begin with 1:

とあり、ORDER BY, GROUP BY は position を受け付ける。

これは SELECT 句に書いた列番号で指定できるってヤツなんだけど、なので最初の例で言うと GROUP BY DATE(created_at) と書く代わりに GROUP BY 1 と書けて便利。

でも

Use of column positions is deprecated because the syntax has been removed from the SQL standard.

とも書いてあって、はいナルホド〜

ので SQL99 で消えたのかな?知らんけど。

遠慮無く「やめましょう!」ってレビューできました。

Athena だと逆に推奨している

Top 10 Performance Tuning Tips for Amazon Athena | AWS Big Data Blog

  1. Optimize GROUP BY

...

sql SELECT state, gender, count(*) FROM census GROUP BY state, gender;

One other optimization is to use numbers instead of strings, if possible, within the GROUP BY clause. Numbers require less memory to store and are faster to compare than strings. The numbers represent the location of the grouped column name in the SELECT statement; for example:

sql SELECT state, gender, count(*) FROM census GROUP BY 1, 2;

RDBMS の実装に合わせて使い分けるということになるんだろうなぁ。