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,不会译