LoginSignup
0
0

More than 5 years have passed since last update.

postgew sql

Last updated at Posted at 2019-05-03

アクセス

psql -h hostname -U username -d databasename

基本構文

select カラム
from テーブル
where '条件'
and '追加条件'

nullの対応

is not null
is nullをつける

select カラム
from テーブル
where '条件' is not null 

()

これで、優先順位を変更する

集約関数

一度集計した結果に対して実行する


User.all.count的な感じな気がする


1Userを全て検索
2レコードを計算する

集約関数文法

1 selectの後に関数を
2 複数カラムには、複数関数を入れる

select count(id) , count(email)from users where id = '22' ;
count
sum
avg
max
min

group by


ユーザーが持っているのemailの数を、個別に出すよ

group byで括りたい【カラム】の指定をする必要がある
※下記の場合、id 

select id , count(email) from users group by id;

Having

条件でまとめられる

goup byなし

→全体の平均


elect avg(price) from products;-[ RECORD 1 ]------------
avg | 305898.813892215569

group_by あり

商品タイプごとに

select avg(price) from products group by type;
-[ RECORD 単品]------------
avg | 298057.389503546099
-[ RECORD セット]------------
avg | 348423.461538461538

検索(述語)

%を起点に前か後ろか?

前方

select nam 
  from products
  where name like '単品%'

結果
単品肉
単品肉

後方

where name like '%単品'

結果
肉単品
魚単品

between

where price between 100 and 1000;

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