【PostgreSQL】カジュアルにSQLに変数を定義する雰囲気

2020-10-21 14:14:02

rubyによるイメージ

begin
   a = 'aaa'
   b =  'bbb'
   User.where(a: a, b: b)
end

Rubyのブロックやjavascriptの即時関数みたいな間隔で、ブロック内で変数を定義してその中では安全な感じで実行したい。

withを使うのがよさそう?

WITH prepare_diff (diff) AS (
  values('2020-10-10'::DATE - '2020-10-12')
),
before_from_to (before_from, before_to) AS (
  VALUES (
    (SELECT ('2020-10-10'::DATE - (diff || 'days')::interval)::DATE FROM prepare_diff AS aaa),
    (SELECT ('2020-10-1'::DATE - (diff || 'days')::interval)::DATE FROM prepare_diff AS bbb)
  )
)
SELECT diff, before_from, before_to FROM prepare_diff, before_from_to;

-- 結果 -2,"2020-10-12","2020-10-03"

参考

sql - Declare a variable in a PostgreSQL query - Stack Overflow

sql - How do you use variables in a simple PostgreSQL script? - Stack Overflow

sql - Is there a way to define a named constant in a PostgreSQL query? - Stack Overflow