LoginSignup
1
0

More than 5 years have passed since last update.

読みやすいSQL

Last updated at Posted at 2018-07-06

圧倒的我流なんであれなんですけど

・全部小文字(shift押すの面倒だから)
・キーワードは全部左寄せ、中身はインデント揃える 
・短いなら1行で、長くなるなら改行
・joinの条件も改行してインデント
・条件式は基本的に1行1つ
・接続詞は前に持ってくる、演算子を前に持ってくるのといっしょ

select id from user where id = 1;
select
    u.id,
    u.name,
    case
        when u.gender = 1 then 'male'
        when u.gender = 2 then 'female'
        else 'unknown' end as gender,
    coalesce(g.name, 'free') as group_name,
    array_to_string(array((
        select name
        from product
        where user_id = u.id
    ), ',') as product_names,
    (
        select sum(sales)
        from product
        where user_id = u.id
    ) as total_sales
from
    user u
    left outer join group g
        on g.id = u.group_id
        and g.is_deleted = false
where
    id = 1
    and u.is_deleted = false
order by
    u.created_at desc
limit 10
1
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
1
0