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 3 years have passed since last update.

SQL 関数と演算子について

Posted at

記事内容

  • 算術演算子の種類
  • nullを含む演算
  • 絶対値の取得
  • 四捨五入
  • 文字列の演算
  • 日付と時刻の演算

関数と演算子

算術演算子の種類

算術演算子 意味 算術演算子 意味
+ 足し算 * 掛け算
- 引き算 / 割り算
% 余り
-- 足し算
select 10 + 20;
-- 出力結果
30 

-- 割り算の余り
select 10 % 3;
-- 出力結果
1

nullを含む演算

  • nullとはデータが存在しないことを表す値

nullを含んだ演算結果はすべて null になるので注意

-- nullを足し算した場合
select 10 + null;
-- 出力結果
null

abs関数

  • 絶対値の取得ができる
    • 数値の符号(+, -)を考えない、0からの距離の大きさを表す数値
      • 10の絶対値は10
      • -10の絶対値は10
      • 0の絶対値は0
-- -10の絶対値
select abs(-10);
-- 出力結果
10

round関数

四捨五入ができる

-- 構文
round(対象の数値, 丸めの桁数)

-- 小数第1位で四捨五入
select round(10.55, 0);
-- 出力結果
11

-- 少数第2位で四捨五入
select round(10.55, 1);
-- 出力結果
10.6

-- avg等の関数と組み合わせも可能
round(avg(price), 0);

concat関数

文字列の連結

-- 構文
concat(文字列1,文字列2,文字列3 ...);

-- 氏名の名前と名字を繋げて出力する場合 (' ' = 半角スペース)
select concat('foo', ' ', 'bar', 'さん');
-- 出力結果
foo barさん

日付と時刻の演算

コマンド 意味
current_date 現在の日時
current_timestap 現在の時刻
d + interval n day n日後の日付
d - interval n day n日前の日付
+ interval 'x hour' x時間後の時刻
- interval 'x hour' x時間前の時刻
ectract 日付や時刻の特定部分(年や月)までを取り出す
-- orders = 注文履歴テーブル
-- order_time = 注文日
-- year_month = 年月
-- year = 年

-- 3日後の日付を取得
select current_date() + interval 3 day;

-- 6時間後の時刻を取得
select current_timestamp() + interval 6 hour;

-- 注文日が2021年1月のレコードのみ取得
select * from orders where extract(year_month from order_time) = 202101;

-- 注文日が2021年のレコードのみ取得
select * from orders where extract(year from order_time) = 2021;

参考記事

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?