缩进
没有被广泛接受的标准。每个人都同意的是,将所有内容压缩成一行是不好的:
SELECT d.Name, COUNT(*) AS Employees FROM Departments AS d JOIN Employees AS e ON d.ID = e.DepartmentID WHERE d.Name != 'HR' HAVING COUNT(*) > 10 ORDER BY COUNT(*) DESC;
至少,将每个子句放入一个新行,如果它们变得太长则拆分行:
SELECT d.Name,
COUNT(*) AS Employees
FROM Departments AS d
JOIN Employees AS e ON d.ID = e.DepartmentID
WHERE d.Name != 'HR'
HAVING COUNT(*) > 10
ORDER BY COUNT(*) DESC;
有时,引入子句的 SQL 关键字之后的所有内容都缩进到同一列:
SELECT d.Name,
COUNT(*) AS Employees
FROM Departments AS d
JOIN Employees AS e ON d.ID = e.DepartmentID
WHERE d.Name != 'HR'
HAVING COUNT(*) > 10
ORDER BY COUNT(*) DESC;
(这也可以在正确对齐 SQL 关键字时完成。)
另一种常见的风格是将重要的关键字放在他们自己的行上:
SELECT
d.Name,
COUNT(*) AS Employees
FROM
Departments AS d
JOIN
Employees AS e
ON d.ID = e.DepartmentID
WHERE
d.Name != 'HR'
HAVING
COUNT(*) > 10
ORDER BY
COUNT(*) DESC;
垂直对齐多个相似表达式可提高可读性:
SELECT Model,
EmployeeID
FROM Cars
WHERE CustomerID = 42
AND Status = 'READY';
使用多行会使 SQL 命令更难嵌入到其他编程语言中。但是,许多语言都有多线字符串的机制,例如 C#中的 @"..."
,Python 中的 """..."""
或 C++中的 R"(...)"
。