1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

SQLのクセにfor文が使えるとは・・

Last updated at Posted at 2021-07-20

はじめに

長らくプログラムで飯を食ってますが、SQLでfor文のような繰り返しができることを初めて知って衝撃を受けたので投稿します。
入れ子for文のサンプルとして九九を例に実際に使ってみましょう。

プログラミング言語で九九を出力

とりあえずjavascriptだとこんな感じのことをSQLでやってみます。

for (let x = 1; x <= 9; x++) {
    for (let y = 1; y <= 9; y++) {
        console.log(`${x} x ${y} = ${x * y}`);
    }
}

結果

1 x 1 = 1
1 x 2 = 2
...
9 x 9 = 81

SQLで九九を出力

for文的繰り返しは、WITH RECURSIVEを使って実現できます。
PostgreSQLで実行しました。

WITH RECURSIVE wx(x) AS (
    VALUES (1)
    UNION
    SELECT x + 1 FROM wx WHERE x < 9
), wy(y) AS (
    VALUES (1)
    UNION
    SELECT y + 1 FROM wy WHERE y < 9
)
SELECT x, y, x * y AS z FROM wx, wy;

結果

x y z
1 1 1
1 2 2
... ... ...
9 9 81

おわりに

すっかり生SQLを書くことも少なくなってきましたが、SQLもちゃんと進化しているんですね。
まあ癖が強い?からこんな簡単な例でも書かないと、初見だとなんじゃこりゃ??ってなりますね。。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?