SQL Standards¶
SQL is often written once and read many times. Optimise for clarity.
Principles¶
- Avoid
SELECT *— be explicit about the columns you need - Use descriptive aliases —
cis not a useful alias forcustomers - Document complex logic with inline comments
- Consistent casing — pick a convention and stick to it
Suggested Tooling¶
| Tool | Purpose |
|---|---|
sqlfluff |
SQL linting and formatting, supports multiple dialects |
dbt |
Transformation framework with built-in testing |
Enforce linting in CI so style issues are caught before review.
Formatting Guidance¶
- One clause per line (
SELECT,FROM,WHERE,GROUP BY) - Indent continuation lines consistently
- Use CTEs over nested subqueries for readability
WITH active_customers AS (
SELECT
customer_id,
name,
created_at
FROM customers
WHERE status = 'active'
)
SELECT
customer_id,
COUNT(*) AS order_count
FROM orders
JOIN active_customers USING (customer_id)
GROUP BY customer_id
dbt-Specific¶
- Write schema tests for every model (not null, unique, relationships)
- Document models and columns in
.ymlfiles - Use
dbt docsto generate and share documentation