SQL Style Guide & Formatting Rules
Clean, consistent, and readable conventions for production SQL queries
Keyword Casing & Capitalization
Make SQL reserved words distinct from database objects
UPPERCASE for all SQL keywordsUse UPPERCASE for SELECT, FROM, WHERE, JOIN, GROUP BY, HAVING, ORDER BY, LIMIT.
SELECT id, full_name, email
FROM users
WHERE status = 'active'
ORDER BY created_at DESC;lowercase snake_case for tables and columnsAvoid camelCase or PascalCase in database object names.
SELECT u.first_name, o.order_total
FROM customer_orders o
JOIN user_accounts u ON u.id = o.user_id;Clause Indentation & Line Breaks
One major clause per line with consistent 2-space indentation
Clause layout
SELECT
u.id,
u.username,
COUNT(o.id) AS total_orders,
SUM(o.amount) AS lifetime_value
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
WHERE u.created_at >= '2025-01-01'
GROUP BY
u.id,
u.username
HAVING COUNT(o.id) > 5
ORDER BY lifetime_value DESC
LIMIT 50;JOIN Formatting Standards
Explicit join types and aligned ON conditions
Always write explicit JOIN types
-- Good: Clear intent
FROM users u
INNER JOIN memberships m ON m.user_id = u.id
LEFT JOIN teams t ON t.id = m.team_id
-- Avoid: Implicit comma joins
FROM users u, memberships m WHERE u.id = m.user_idPut ON conditions on the same or next line
FROM payments p
INNER JOIN subscriptions s
ON s.id = p.subscription_id
AND s.is_active = TRUECommon Table Expressions (CTEs)
Use CTEs instead of deep nested subqueries
WITH Clause Pattern
WITH monthly_revenue AS (
SELECT
DATE_TRUNC('month', created_at) AS order_month,
SUM(total_amount) AS revenue
FROM orders
WHERE status = 'completed'
GROUP BY 1
)
SELECT
order_month,
revenue,
LAG(revenue) OVER (ORDER BY order_month) AS prior_month_revenue
FROM monthly_revenue
ORDER BY order_month DESC;