Back to Blog
SQLDatabaseBackendPerformanceDeveloper Tools

Modern SQL Formatting: Industry Standards, Code Style, and Query Optimization

Written by Dev Toolkit Editorial
•
July 16, 2026
•7 MIN READ

Master modern SQL style guidelines, formatting standards, CTE readability, and query optimization techniques to write maintainable, performant database queries.

SQL is the universal language of data management. Across traditional relational databases (such as PostgreSQL, MySQL, SQLite, and Microsoft SQL Server) and modern cloud data warehouses (such as Snowflake and Google BigQuery), structured queries power everything from high-throughput OLTP web applications to complex analytical OLAP pipelines.

However, despite SQL’s dominance, database code in many engineering organizations suffers from a lack of consistent formatting standards. Monolithic, unformatted 500-line SQL scripts with nested inline subqueries, arbitrary capitalization, and unindented join conditions are difficult to read, prone to logic errors during code reviews, and challenging to optimize.

In this guide, we will explore modern SQL style standards, compare readability patterns like Common Table Expressions (CTEs) against nested subqueries, dive into key query optimization strategies (such as SARGable predicates and query execution plans), and demonstrate how automated tooling can maintain SQL cleanliness across team codebases.


1. Why SQL Formatting Standards Matter

Unlike languages with strict linting ecosystems enforced at compile time, SQL is exceptionally forgiving of whitespace, line breaks, and casing. A query written entirely on a single line with mixed casing will execute just as validly as a perfectly formatted query.

However, in team environments, unformatted SQL introduces substantial hidden costs:

  • Review Fatigue: Reviewing a pull request with unindented 10-table JOIN statements makes identifying missing join conditions or accidental cartesian products (CROSS JOINs) exhausting.
  • Git Diff Noise: When developers edit unformatted SQL blocks, small modifications often reformat entire multi-line strings, creating noisy, unreadable Git diffs.
  • Obscured Execution Plans: Poorly structured queries often conceal inefficient filtering, redundant table scans, and sub-optimal subqueries that degrade query performance.

2. Modern SQL Formatting Standards & Style Guidelines

While individual teams may adopt slight variations, modern SQL style guides—such as those published by GitLab, dbt, and Mozilla—share core formatting conventions that maximize legibility.

Note on Portability: While SQL formatting conventions and style guidelines are largely portable across different SQL dialects, query optimizer behavior, execution strategies, and indexing capabilities vary significantly between database engines.

Rule 1: Capitalize All SQL Reserved Keywords

Always capitalize reserved keywords (SELECT, FROM, WHERE, JOIN, GROUP BY, ORDER BY, WITH, CASE, WHEN) to clearly distinguish language instructions from schema identifiers (tables, columns, aliases).

-- ❌ BAD: Mixed casing and squeezed layout
select u.id, u.email, count(o.id) as total_orders from users u left join orders o on u.id = o.user_id where u.status = 'active' group by u.id, u.email;

-- ✅ GOOD: Capitalized keywords with structured vertical rhythm
SELECT
  users.id,
  users.email,
  COUNT(orders.id) AS total_orders
FROM users
LEFT JOIN orders
  ON users.id = orders.user_id
WHERE users.status = 'active'
GROUP BY
  users.id,
  users.email;

Rule 2: One Column Per Line in SELECT Statements

Placing each selected column or expression on its own line simplifies adding/removing fields during debugging and produces clean, single-line Git diffs.

-- ✅ GOOD: Clean vertical alignment with explicit aliases
SELECT
  o.id AS order_id,
  o.created_at,
  o.total_amount,
  c.first_name,
  c.last_name
FROM orders AS o
JOIN customers AS c
  ON o.customer_id = c.id;

Rule 3: Always Use Explicit AS for Aliases

While SQL permits implicit table and column aliases (FROM users u), using AS (FROM users AS u) consistently improves readability and makes accidental aliasing caused by missing commas much easier to detect during code reviews.

-- ❌ DANGEROUS: Missing comma turns 'last_name' into an alias for 'first_name'!
SELECT
  first_name
  last_name
FROM users;

-- ✅ SAFE: Explicit AS keyword makes intent unambiguous
SELECT
  first_name,
  last_name AS surname
FROM users;

Rule 4: Indent ON Clauses Under Their Corresponding JOIN

Indent ON conditions directly under their respective JOIN statement to visually clarify table relationships, especially in complex queries joining 4 or more tables.

SELECT
  p.product_name,
  c.category_name,
  s.supplier_name
FROM products AS p
INNER JOIN categories AS c
  ON p.category_id = c.id
LEFT JOIN suppliers AS s
  ON p.supplier_id = s.id;

3. CTEs vs. Nested Subqueries: Readability & Performance

Prior to SQL:1999, complex multi-step data transformations relied on nested subqueries in FROM or WHERE clauses. Today, Common Table Expressions (CTEs) defined with the WITH clause are widely used for improving readability and maintainability in complex queries.

The Readability Advantage of CTEs

CTEs allow developers to organize query logic into sequential, self-contained, named blocks that read top-to-bottom for humans, while the underlying database query optimizer independently determines the physical execution plan.

-- ❌ BAD: Hard-to-read nested subquery
SELECT
  user_totals.user_id,
  user_totals.total_spent
FROM (
  SELECT
    orders.user_id,
    SUM(orders.amount) AS total_spent
  FROM orders
  WHERE orders.status = 'completed'
  GROUP BY orders.user_id
) AS user_totals
WHERE user_totals.total_spent > 1000;

-- ✅ GOOD: Clean, modular Common Table Expression (CTE)
WITH completed_order_totals AS (
  SELECT
    orders.user_id,
    SUM(orders.amount) AS total_spent
  FROM orders
  WHERE orders.status = 'completed'
  GROUP BY orders.user_id
)

SELECT
  completed_order_totals.user_id,
  completed_order_totals.total_spent
FROM completed_order_totals
WHERE completed_order_totals.total_spent > 1000;

CTE Performance Considerations

  • Optimizer Variance: Optimizer behavior varies significantly between database engines. Modern query optimizers frequently inline or otherwise optimize non-recursive CTEs when beneficial, treating them similarly to derived tables.
  • Optimization Fences: In older PostgreSQL versions (< 12), CTEs acted as optimization fences that prevented certain planner optimizations (such as predicate pushdown). When working with legacy systems or tuning critical queries across engines, evaluate execution plans to verify planner behavior.

4. Fundamental SQL Query Optimization Strategies

A beautifully formatted query must also be performant. Here are four foundational database optimization practices every developer should apply:

1. Avoid SELECT * in Production

Requesting SELECT * increases I/O overhead, transfers unnecessary data over the network, consumes extra memory during serialization, and may prevent index-only or covering-index access depending on the database engine.

2. Ensure Predicates are SARGable (Search Argument Able)

A query predicate is SARGable if the database engine can utilize an index to efficiently isolate matching rows. Applying a function or scalar manipulation to an indexed column in a WHERE clause prevents index usage and triggers full table scans.

-- ❌ NOT SARGable (MySQL / SQL Server example): Applying YEAR() function to indexed 'created_at' forces a full table scan
SELECT
  orders.id,
  orders.amount
FROM orders
WHERE YEAR(orders.created_at) = 2026;

-- ✅ SARGable: Range query allows database engine to leverage index usage
SELECT
  orders.id,
  orders.amount
FROM orders
WHERE orders.created_at >= '2026-01-01'
  AND orders.created_at < '2027-01-01';

3. Filter Early Before Performing Joins

Filter rows as early as possible in subqueries or CTEs before joining large tables. Reducing the number of rows participating in join operations significantly decreases memory consumption and CPU processing across all join algorithms.

4. Analyze Execution Plans

Never guess why a query is slow. Different database management systems provide dedicated diagnostic utilities to inspect query execution plans—such as EXPLAIN or EXPLAIN ANALYZE in PostgreSQL and MySQL, EXPLAIN QUERY PLAN in SQLite, graphical execution plan viewers in SQL Server, or Query Profiles in cloud data warehouses.

  • Look for full table scans on large tables where index usage should occur.
  • Check for high relative costs, heavy disk or memory usage, or mismatched row count estimates versus actual row counts.

5. Automated Formatting & CI Linting Workflow

Relying on manual code reviews to enforce SQL style is inefficient. Modern engineering teams integrate automated SQL formatters and linters into their development workflow and CI/CD pipelines:

  1. CLI Linters (sqlfluff): sqlfluff is a popular dialect-aware SQL linter that automatically formats SQL files and enforces rule configurations (.sqlfluff) in pre-commit hooks and GitHub Actions.
  2. IDE Formatters: Most modern IDEs and code editors support auto-formatting SQL on file save.

Further Reading & Resources

Interactive Tools

  • /sql-formatter/ – Format, uppercase keywords, and clean SQL queries across multiple dialects.
  • /sql-to-typescript/ – Generate TypeScript interface models from SQL schema definitions.
  • /diff-checker/ – Compare unformatted vs. refactored queries side-by-side with line diffs.

By adhering to consistent formatting standards, leveraging CTEs for structured readability, writing SARGable queries, and incorporating automated formatting into your workflow, you can craft SQL codebases that are both easy to maintain and built for high performance.