SQL 可读性:在 select 列表的末尾或开头逗号更好?

SQL readability: commas better at the end or at the beginning of select list?

虽然我认为这可能只是个人品味的问题,但我想知道您更喜欢(以及为什么)在 select 列表中的什么地方使用逗号。

开头:

select first_name
      ,last_name
      ,address
  from people

或最后:

select first_name,
       last_name,
       address
  from people

就我个人而言,我更喜欢在每一行的开头使用逗号,尤其是当我处理比单个列名称更多的 complicated/long 值时。

我觉得这样做更舒服,因为我总是理解 when/where 一个新元素 "starts"。

我很想知道你们是否有任何偏好(或特定场景)以便从多个角度看这个主题。

好吧,我个人更喜欢在行尾使用逗号(并从新行开始所有 select, from, where 语句)。像这样:

select 
  first_name,
  last_name,
  address
from 
  people

也许是习惯了这种格式,但实际上它看起来清晰易读。

最好在开头加上逗号。这样做的原因是它可以更容易地注释掉属性。例如:

select first_name
      ,last_name
      ,address
from people

假设出于某种原因我们需要注释掉 last_name 列

select first_name
   --   ,last_name this is now commented out
        ,address
from people

它实际上确实在人类语言处理方式中很重要。 Joe Celko(SQL for Smarties 等书籍的作者)指出:

But be sure to end the line where the split occurs with language token that lets the reader know that there is more to come. This is why putting a comma at the front of the line is a bad practice; when you see a comma you know there is something coming after it. Likewise, when you see a semi-colon, you know it is a terminator. That lets the reader mentally close up that unit of code, “clear his buffers” and parse the next statement.

hackernoon 的 Felipe Hoffa 对前导逗号的使用进行了深入研究,发现强制使用它们的项目在 GitHub 上既不受欢迎也不​​成功: https://hackernoon.com/winning-arguments-with-data-leading-with-commas-in-sql-672b3b81eac9

在前面使用 SQL 并没有错,但它不受欢迎并且会分散 reader 的注意力,因为它降低了语言的可读性。我不了解其他人,但当任何标点符号(句号、逗号、分号)位于括号或方括号以外的行的开头时,我阅读代码并不容易。

SQL 意味着人类可读,具有自然语言界面,如 Fortran、Cobol 等。因此,分号在行尾。