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?

【PostgreSQL】前日差分だけを安全に抽出するSQLパターン

0
Posted at

日次バッチで「前日分だけ取得したい」とき、書き方を間違えるとデータ欠損や重複が発生します。

この書き方は「半開区間」と呼ばれます。

WHERE update_dt >= CURRENT_DATE - 1
  AND update_dt < CURRENT_DATE
  • 開始:含む(>=)
  • 終了:含まない(<)

この形にすることで、時刻付きデータでも安全に扱うことができます。また、日付境界でズレることがなく、再実行しても同じ結果になるため冪等性も保たれます。

NG例

WHERE update_dt = CURRENT_DATE - 1

update_dtに時刻が含まれている場合は一致せず、データが取得できなくなります。

まとめ

日次差分は「>= と <」で切るのが基本です。
このパターンをテンプレート化することで、バッチ処理の安定性が大きく向上します。

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?