SQL is read far more often than it is written. A query that is clear to the author today will be incomprehensible to the author's teammates — or to the author in six months — without consistent formatting and naming. This guide covers the practices that make SQL genuinely maintainable at scale.
Formatting & Style
1. Uppercase keywords, lowercase names
This convention has been standard in SQL for decades. It immediately distinguishes keywords from identifiers when scanning a query.
-- Good
SELECT employee_id, first_name, last_name
FROM employees
WHERE department_id = 5
AND hire_date > '2024-01-01'
ORDER BY last_name, first_name;
-- Bad — hard to distinguish keywords from identifiers
select employee_id, first_name, last_name
from employees
where department_id = 5; 2. One clause per line, keywords aligned
Line up AND/OR with the WHERE keyword for clear visual grouping of conditions. Break complex WHERE clauses into parenthesized groups.
-- Good — conditions are grouped and readable
SELECT o.order_id, o.total
FROM orders o
JOIN customers c ON o.customer_id = c.id
WHERE c.region = 'West'
AND o.status IN ('pending', 'processing')
AND o.created_at > DATEADD(day, -30, GETDATE());
-- Bad — one long line is unreadable
WHERE c.region = 'West' AND o.status IN ('pending', 'processing')
AND o.created_at > DATEADD(day, -30, GETDATE()); 3. Always use table aliases with meaningful abbreviations
Aliases make queries shorter and are required for self-joins. Use meaningful abbreviations (o for orders, c for customers) consistent across your codebase.
-- Good — aliases are clear and consistent
SELECT o.order_id, c.customer_name
FROM orders o
JOIN customers c ON o.customer_id = c.id;
-- Bad — no aliases forces full table names everywhere
SELECT orders.order_id, customers.customer_name
FROM orders
JOIN customers ON orders.customer_id = customers.id; Naming Conventions
4. Consistent naming patterns
Pick a convention and apply it consistently across the entire database.
-- Table names: plural, snake_case
-- Columns: singular, snake_case
-- Primary keys: table_singular_id (employee_id)
-- Foreign keys: referenced_table_singular_id (department_id)
-- Indexes: idx_table_column(s) (idx_employees_department_id)
-- Tables
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR(100) NOT NULL,
last_name VARCHAR(100) NOT NULL,
department_id INT,
created_at DATETIME DEFAULT GETDATE(),
CONSTRAINT fk_employees_department
FOREIGN KEY (department_id) REFERENCES departments(department_id)
);
-- Indexes
CREATE INDEX idx_employees_department_id ON employees(department_id);
CREATE INDEX idx_employees_name ON employees(last_name, first_name); 5. Avoid reserved words as column names
Columns named date, order, group, user,
and level cause quoting issues in some databases and confusion everywhere.
Prefix with the entity name.
-- Good
order_date -- not "date"
order_number -- not "order"
user_name -- not "user"
-- Bad
date -- reserved word in most SQL dialects
user -- reserved in many systems Security
6. Always use parameterized queries — never concatenate user input
SQL injection is the most dangerous and preventable web vulnerability. Parameterized queries separate SQL logic from data, making injection impossible.
-- GOOD — parameters are safe
const query = `
SELECT * FROM users
WHERE email = @Email AND status = @Status
`;
await db.query(query, { Email: userEmail, Status: 'active' });
-- BAD — string concatenation creates injection vulnerability
const query = `
SELECT * FROM users
WHERE email = '${userEmail}' AND status = 'active'
`;
-- If userEmail = "' OR '1'='1", this returns all users 7. Apply the principle of least privilege
Application database accounts should have only the permissions they need —
not db_owner. Use separate read-only accounts for reporting queries.
-- Application account: read + write, no DDL
GRANT SELECT, INSERT, UPDATE, DELETE ON SCHEMA::dbo TO app_user;
DENY ALTER ON SCHEMA::dbo TO app_user;
-- Reporting account: read only
GRANT SELECT ON SCHEMA::dbo TO report_reader; Performance
8. Filter before you join
Apply WHERE conditions early to reduce the number of rows before joins. This reduces the amount of data the database must process.
-- Good — filter first, then join (fewer rows to join)
SELECT o.order_id, c.customer_name
FROM orders o
JOIN customers c ON o.customer_id = c.id
WHERE o.status = 'pending'
AND c.region = 'West';
-- Less efficient — joins first, then filters
SELECT o.order_id, c.customer_name
FROM orders o
JOIN customers c ON o.customer_id = c.id
WHERE c.region = 'West'; 9. Avoid functions on indexed columns in WHERE clauses
Wrapping a column in a function prevents the optimizer from using an index. Rewrite to put the function on the comparison value instead.
-- Bad — function on column prevents index use
WHERE YEAR(created_at) = 2025
WHERE LOWER(email) = 'john@example.com'
-- Good — function on the constant, column is raw
WHERE created_at >= '2025-01-01' AND created_at < '2026-01-01'
WHERE email = 'john@example.com' 10. Use EXISTS instead of IN for subqueries when possible
EXISTS stops as soon as it finds one match. IN must
collect all matching values first. For large subqueries, this is a significant difference.
-- Better: EXISTS stops at first match
SELECT e.name
FROM employees e
WHERE EXISTS (
SELECT 1 FROM departments d WHERE d.id = e.dept_id AND d.active = 1
);
-- IN collects all matching values first (can be slower)
SELECT e.name
FROM employees e
WHERE e.dept_id IN (
SELECT id FROM departments WHERE active = 1
); 11. Select only what you need — never use SELECT *
Listing specific columns reduces network transfer, allows better index usage, and makes your queries self-documenting.
-- Good — explicit columns, predictable
SELECT order_id, customer_id, total, status, created_at
FROM orders
WHERE status = 'pending';
-- Bad — returns all columns (including potentially sensitive ones)
SELECT * FROM orders WHERE status = 'pending'; Maintainability
12. Use CTEs for complex logic — not deeply nested subqueries
CTEs (Common Table Expressions) named with WITH read top-to-bottom,
making multi-step logic much easier to follow than nested subqueries.
-- Good — readable, named steps
WITH active_customers AS (
SELECT id, name, region
FROM customers
WHERE status = 'active'
),
recent_orders AS (
SELECT customer_id, MAX(order_date) AS last_order_date
FROM orders
GROUP BY customer_id
)
SELECT
c.name,
c.region,
o.last_order_date,
DATEDIFF(day, o.last_order_date, GETDATE()) AS days_since_order
FROM active_customers c
JOIN recent_orders o ON c.id = o.customer_id
WHERE DATEDIFF(day, o.last_order_date, GETDATE()) > 90; 13. Comment the why, not the what
Good SQL comments explain business logic, unusual requirements, or why a non-obvious approach was chosen — not what the code does (that is obvious from the code).
-- Good: explains business reasoning
-- Using 30-day window per contract terms (SLA section 4.2)
-- Excluding cancelled orders per Q3 revenue reporting policy
WHERE order_date >= DATEADD(day, -30, GETDATE())
AND status != 'cancelled'
-- Bad: just restates the code
-- Get orders from the last 30 days
WHERE order_date >= DATEADD(day, -30, GETDATE()) 14. Handle NULLs explicitly — do not rely on defaults
NULL comparisons always return NULL (unknown), not true or false. Use
IS NULL/IS NOT NULL explicitly and wrap potentially
NULL columns with COALESCE at the output boundary.
-- Explicit NULL check
WHERE manager_id IS NOT NULL
-- Provide default at output boundary (not in WHERE)
SELECT
employee_name,
COALESCE(manager_name, '(no manager)') AS manager_name
FROM employees;
-- Be explicit about NULL behavior in comparisons
-- = NULL never matches, use IS NULL instead
WHERE department_id = 5
WHERE department_id IS NULL Frequently Asked Questions
- Should I use SELECT * or list specific columns?
- Always list specific columns. SELECT * retrieves unnecessary data, breaks when columns are added/removed/reordered, exposes sensitive columns unintentionally, and makes intent unclear. It also prevents the database from using covering indexes effectively.
- How do I prevent SQL injection?
- Always use parameterized queries or prepared statements. Never concatenate user input directly into SQL strings. Most ORMs and database drivers provide parameterized query APIs — use them exclusively. Input validation is a secondary defense, not a primary one.
- When should I add an index?
- Add an index when: (1) the column is frequently used in WHERE, JOIN, or ORDER BY clauses, (2) the table is large and the query returns a small percentage of rows, and (3) the column has high cardinality (many distinct values). Do not over-index — each index slows down INSERT/UPDATE/DELETE operations. See the full indexing guide for composite indexes, covering indexes, and execution plan analysis.
- What is the most important query optimization technique?
- Write queries that match your indexes. The most impactful optimizations are: (1) filter early with WHERE clauses before joins, (2) use indexed columns in JOIN and WHERE conditions, (3) avoid functions on indexed columns in WHERE, and (4) use covering indexes for frequently-run queries.