Databases

How to Format SQL Queries

Learn standard SQL indentation, keyword capitalization conventions, CTE structures, and alignment rules to make database queries readable and maintainable.

## Why Consistent SQL Formatting Matters SQL is a declarative language, which often tempts developers to write queries as run-on sentences. As queries grow with multiple `JOIN` statements, aggregate functions, and nested subqueries, unformatted SQL becomes a major source of bugs, performance bottlenecks, and painful peer reviews. --- ## Core SQL Formatting Conventions ### 1. Capitalize All Reserved SQL Keywords Reserved words like `SELECT`, `FROM`, `WHERE`, `JOIN`, `GROUP BY`, and `ORDER BY` should always be written in **UPPERCASE**. This creates immediate visual distinction between SQL syntax and database identifiers (table and column names). ```sql -- Poor Practice select u.id, u.email from users u where u.status = 'active'; -- Recommended Practice SELECT u.id, u.email FROM users u WHERE u.status = 'active'; ``` ### 2. Put Each Major Clause on a New Line Never chain `FROM`, `WHERE`, and `HAVING` clauses on the same line. Splitting them onto new lines drastically improves readability and Git diff clarity. ### 3. Align and Indent Subqueries and JOINs Explicitly specify the type of join (`INNER JOIN`, `LEFT JOIN`) and indent the `ON` condition on the following line. ```sql SELECT o.id AS order_id, c.company_name, SUM(oi.quantity * oi.unit_price) AS total_revenue FROM orders o INNER JOIN customers c ON o.customer_id = c.id INNER JOIN order_items oi ON o.id = oi.order_id WHERE o.created_at >= '2026-01-01' GROUP BY o.id, c.company_name HAVING SUM(oi.quantity * oi.unit_price) > 5000 ORDER BY total_revenue DESC; ``` ### 4. Leverage Common Table Expressions (CTEs) Instead of nesting deeply indented subqueries, use `WITH` clauses (CTEs) to make query logic flow sequentially from top to bottom. --- ## Automated SQL Formatting Formatting complex queries by hand is tedious. Use the [LABSTACK SQL Formatter](/tools/sql-formatter) to instantly clean up messy queries with customizable indentation and automatic keyword capitalization.