0
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 1 year has passed since last update.

【PL/pgSQL】SELECT INTOと$$(備忘録)

Posted at

postgresのストアド完全初心者なのですが、本日読む機会がありまして。

SELECT INTO

問題の部分

SELECT INTO alphaIds, betaIds array_agg(alphaId), array_agg(betaId) FROM TBL;

このSELECT INTOというものがよくわからず困っていました。
調べてみてもSELECT (*|columns...) INTO val1, val2 FROM TBL;のようなものは見かけたのですが、ちょっと違う。と詳しく読むと、INTOの位置はSELECTの直後でもよいとのこと。

タプルのようなものと理解しました。

(alphaIds, betaIds) <- (array_agg(alphaId), array_agg(betaId))

INTOの位置を書き換えると以下のような感じ(この方が分かりやすいと思う)。

SELECT array_agg(alphaId), array_agg(betaId) INTO alphaIds, betaIds FROM TBL;

なお、PL/pgSQL以外でのSELECT INTOはSELECT結果をもとにしてテーブルを作る構文だそうです。

array_agg(xxx)

集約関数で、複数行の結果を配列にしてくれるもの。
SQLServerなどで同じことをするのは結構大変だった記憶があり、こういった便利な関数があるのはいいですね。

$$

単なる区切り文字。
シングルクォートを使うと、内部でエスケープしなければいけないので$$を使うのが一般的、らしい。

array_length(arr, 1)の第二引数

配列のどの次元の長さを出すか。

0
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
0
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?