8
14

More than 5 years have passed since last update.

Postgre SQL用 SQLメモ

Last updated at Posted at 2016-05-23

はじめに

PostgreSQLについて調べたりしたことのメモです。

Timestamp型、Date型関連

sample.sql
--現在日時の取得
select current_timestamp;

--現在日付の取得
select current_date;

--現在時刻の取得
select current_time;

--Date型からTimestamp型への変換
select to_timestamp(to_char(current_date, 'YYYY-MM-DD'), 'YYYY-MM-DD hh:mm:ss');

--日時の加算
select current_timestamp + '1 hours 40 minutes';

--日時の減算
select current_timestamp + '-5 days';

--現在月の1日(ついたち)を取得
select date_trunc('month', current_timestamp);

--現在月の末日を取得
select date_trunc('month', current_timestamp) + '1 months -1 seconds';

解説のような何か

current_xxxはSELECT文内でそのまま使用可能。

Date型⇒Timestamp型の変換について

  1. Date型を文字列型に変換
  2. 変換した文字列をTimestamp型に変換

日時の加減算について

  • Timestamp型の値に「 + ’値 単位’」を付記する(上記ソース参照)
  • 値の前に半角マイナス(-)を付けると減算する
  • 単位はyears, months, days, hours, minutes, seconds

1日と末日について

  • date_trunc()で第1引数の単位未満を切捨てる(上記ソースでは「日」以下を切捨てて、1日の00:00:00となる)
  • 末日で-1 secondsとすることで、月末の23:59:59を取得できる。-1 daysとすると00:00:00を取得するのでwebシステム開発などで注意する

文字列型

文字列結合

sample.sql
select 'String1' || 'String2';

解説のような何か

2つの文字列を「||」でつなぐ

8
14
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
8
14