SQL 最佳实践

  • 使用小写的关键字,SQL 语法 IDE 会处理展示,大写对于人来说是相对比较难理解,需要大脑转换
  • 如果需要换行的话,行开头要以关键字开始,并且关键字的所属区块内容要适当缩进
  • 全部左对其
  • 使用单引号,如果查询内容存在单引号,就使用反引号
  • 使用!=,而不是<>
  • (1, 2, 3)而不是( 1, 2, 3 )
  • 表名、字段名 使用 xxx_xxx_xxx 格式
  • 布尔型字段名案例:is_xxx、has_xxx、do_xxx、……
  • 仅日期型字段名案例:xxx_date、……
  • 日期+时间型字段名案例:xxx_at、created_at、posted_at、……
  • join 语句中 on 后面的查询主体应该是 from 后的表,而不是被 join 的表,例如from a join b on a.id = b.id
  • join 的 on 语句要紧跟其后,不要换行
  • 避免对表进行重命名
  • 在只有一张表时不要 select user.name from user
  • 要重命名所有使用函数得出的列 select count(*) c from user
  • 查询条件要写明确,select id from user where is_dsg应写为select id from user where is_dsg = true
  • 重命名表行时添加 as
  • 使用 CETs,不要使用子查询,在Sql中,with语句指定临时命名结果集,称为公用表表达式(CTE)。它可以用于递归查询,在这种情况下,我们称之为子集或子查询

example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
select 
user.id,
user.age,
user.name,
user.avatar,
user.is_dsg,
user.has_money,
user.created_at,
photo.head,
case
when user.is_dsg = true
then '孤傲独身犬'
when user.is_dsg = false
then '地狱三头狼'
end as nickname
from user
left join photo on
user.id = photo.user_id and
photo.head_photo like '%xxxx%'
where
user.name like '%xxx%' and
user.age between 5 and 10 and
user.avatar is not null
order by user.id desc

CET example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
-- Good
with ordered_details as (

select
user_id,
name,
row_number() over (partition by user_id order by date_updated desc) as details_rank
from billingdaddy.billing_stored_details

),

final as (

select user_id, name
from ordered_details
where details_rank = 1

)

select * from final

-- Bad
select user_id, name
from (
select
user_id,
name,
row_number() over (partition by user_id order by date_updated desc) as details_rank
from billingdaddy.billing_stored_details
) ranked
where details_rank = 1

最佳实践出处:github

◀        
        ▶