SQL编程风格指南

1.使用小写字母

它和使用大写字母的SQL可读性是一样的,此外,你不用再一直按着一个SHIFT键(个人觉得是SQL语法高亮,使得大写/小写字母的SQL可读性一样,不然的话,还是大写SQL可读性更强)。

-- Good
select * from users

-- Bad
SELECT * FROM users

-- Bad
Select * From users

2.单行语句 v.s. 多行语句的查询

只有一种情况,你会把所有的SQL语句都放在一行,那就是你的查询语句只选择一个对象,而且没有额外的条件:

-- Good
select * from users

-- Good
select id from users

-- Good
select count(*) from users

一旦你开始添加更多的对象或者额外的条件,这时候你把SQL语句分成多行可读性会更好:

-- Good
select
    id,
    email,
    created_at
from users

-- Good
select *
from users
where email = 'example@domain.com'

-- Good
select
    user_id,
    count(*) as total_charges
from charges
group by user_id

-- Bad
select id, email, created_at
from users

-- Bad
select id,
    email
from users

3.左对齐SQL关键字

一些IDE提供了自动格式化SQL语句的功能,以便SQL关键字后的空格能够垂直对齐。手动实现这个是很麻烦的,而且在我看来它的可读性也不好,因此我建议直接左对齐所有的SQL关键字。

-- Good
select id, email
from users
where email like '%@gmail.com'

-- Bad
select id, email
  from users
 where email like '%@gmail.com'

4.使用单引号

一些SQL方言比如BigQuery支持双引号,但是对于大多数SQL方言而言,双引号会用来引用列名。因此,单引号更适合:

-- Good
select *
from users
where email = 'example@domain.com'

-- Bad
select *
from users
where email = "example@domain.com"

5.使用!=而不是<>

只是因为!=看起来更像“不等于”

-- Good
select count(*) as paying_users_count
from users
where plan_name != 'free'

6.逗号应该在行尾

-- Good
select
    id,
    email
from users

-- Bad
select
    id
    , email
from users

7.缩进where语句

当只有一个where条件,让它保持在where的同行:

select email
from users
where id = 1234

当有多个where条件时,缩进每一个条件,且比where更深一层。把逻辑运算符放在上一个条件的末尾:

select id, email
from users
where 
    created_at >= '2019-03-01' and 
    vertical = 'work'

8.括号处不使用空格

-- Good
select *
from users
where id in (1, 2)

-- Bad
select *
from users
where id in ( 1, 2 )

9.将in的值列表分解为多个缩进行

-- Good
select *
from users
where email in (
    'user-1@example.com',
    'user-2@example.com',
    'user-3@example.com',
    'user-4@example.com'
)

10.表名使用下划线连接的名词复数形式

-- Good
select * from users
select * from visit_logs

-- Bad
select * from user
select * from visitLog

总结

1.第10点,Table names should be a plural snake case of the noun,不会译

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值