Writing clean and readable SQL is just as important as writing efficient queries. Whether you’re collaborating with a team, debugging a complex report, or revisiting your own code months later, good formatting can make all the difference. In this post, we’ll walk through essential SQL formatting best practices that not only improve readability but also help you write queries that are easier to understand, maintain, and scale. Let’s dive in and make your SQL cleaner and more professional!
Table of Content
1. SQL Keywords in UPPERCASE
2. Use Proper Indentation
3. Align JOINs Properly
4. Use Aliases Consistently
5. Use Meaningful Aliases
6. Use Proper Spacing
7. Use CTEs Instead of Subqueries (For Complex Queries)
8. Use Comments Wisely
9. Avoid Using SELECT * (Use Specific Columns)
10. Format CASE Statements Properly
Final Summary
1. SQL Keywords in UPPERCASE
Using SQL keywords in uppercase is a widely accepted formatting best practice that improves the readability and structure of your queries. Keywords like SELECT, FROM, WHERE, and JOIN stand out clearly when written in uppercase, making it easier to distinguish them from table names, column names, and other elements. This visual separation helps both you and others quickly understand the logic of a query, especially when scanning through longer scripts. Consistently capitalizing SQL commands also promotes a professional and standardized coding style across teams and projects.
Without uppercase (bad example):
select customer_id, first_name, last_name from customers where active = 1 order by last_name;
With uppercase (good example):
SELECT customer_id, first_name, last_name
FROM customers
WHERE active = 1
ORDER BY last_name;
2. Use Proper Indentation
Proper indentation in SQL is essential for writing clean, readable, and maintainable queries. By placing each clause—such as SELECT, FROM, WHERE, and JOIN—on its own line and indenting sub-elements like column names or conditions, you create a clear visual structure that makes the logic of the query easy to follow. This becomes especially important in longer or more complex queries, where poor formatting can quickly lead to confusion. Consistent indentation also helps with debugging and reviewing code, whether you’re working alone or collaborating with others.
Without proper indentation (bad example):
SELECT customer_id, first_name, last_name FROM customers WHERE active = 1 ORDER BY last_name;
With proper indentation (good example):
SELECT
customer_id,
first_name,
last_name
FROM customers
WHERE active = 1
ORDER BY last_name;
3. Align JOINs Properly
Aligning JOINs properly in SQL helps clarify how tables are connected and improves the overall structure of your query. Each JOIN clause should be placed on a new line, ideally with the JOIN keyword, table name, and ON condition clearly separated. This formatting makes it easy to see which tables are being joined and what relationships exist between them. In more complex queries involving multiple joins, proper alignment prevents confusion and reduces the chance of introducing logic errors. It also enhances readability for both the original author and anyone reviewing the code later.
Bad example:
SELECT c.customer_id, c.first_name, c.last_name, o.order_id, o.total_amount FROM customers c JOIN orders o ON c.customer_id = o.customer_id WHERE o.total_amount > 100 ORDER BY o.order_date DESC;
Good example:
SELECT
c.customer_id,
c.first_name,
c.last_name,
o.order_id,
o.total_amount
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id
WHERE o.total_amount > 100
ORDER BY o.order_date DESC;
4. Use Aliases Consistently
Using aliases consistently in SQL ensures your queries remain concise, readable, and easy to maintain. Aliases help shorten long table or column names, making the query cleaner, especially when working with joins or complex subqueries. Consistent aliasing means using the same abbreviation style throughout your query, such as c for customers or o for orders, which avoids confusion and improves clarity. It’s important to define aliases clearly and stick to them, as inconsistent use can lead to misunderstandings or errors, particularly in collaborative environments.
Bad example:
SELECT
customers.customer_id,
first_name,
orders.order_id,
orders.total_amount
FROM customers
JOIN orders ON customers.customer_id = orders.customer_id;
Good example:
SELECT
c.customer_id,
c.first_name,
o.order_id,
o.total_amount
FROM customers AS c
JOIN orders AS o ON c.customer_id = o.customer_id;
5. Use Meaningful Aliases
Using meaningful aliases in SQL helps make your queries more self-explanatory and easier to understand. Instead of using vague or overly short aliases like a, b, or x, choose abbreviations that reflect the table or column’s purpose, such as cust for customers or ord for orders. This practice improves clarity, especially in complex queries with multiple tables or subqueries. Meaningful aliases reduce the cognitive load for anyone reading the query, making it easier to follow the data flow and logic, and they are especially valuable when working in teams or revisiting code after some time.
Bad example:
SELECT
c.id AS cid,
c.name AS cname,
o.id AS oid
FROM customers AS c
JOIN orders AS o ON c.id = o.cid;
Good example:
SELECT
c.id AS customer_id,
c.name AS customer_name,
o.id AS order_id
FROM customers AS c
JOIN orders AS o ON c.id = o.customer_id;
6. Use Proper Spacing
Using proper spacing in SQL enhances the readability and professional appearance of your queries. Adding spaces around commas, operators like =, >, and AND, and between clauses prevents the code from looking cluttered or difficult to parse. Well-spaced SQL allows the reader to quickly scan and understand the logic without getting lost in dense lines of text. Consistent spacing also reduces the chances of syntax errors and makes your queries easier to debug and maintain over time. It’s a small habit that makes a big difference in writing clean, effective SQL.
Bad example:
SELECT first_name,last_name FROM customers WHERE active=1;
Good example:
SELECT first_name, last_name
FROM customers
WHERE active = 1;
7. Use CTEs Instead of Subqueries (For Complex Queries)
Using Common Table Expressions (CTEs) instead of subqueries in complex SQL queries improves both readability and maintainability. CTEs allow you to break down a large query into smaller, named building blocks, making it easier to understand the logic step by step. Unlike nested subqueries, which can become hard to follow and debug, CTEs keep your SQL organized and modular. They also allow you to reuse the same temporary result set multiple times within the same query, reducing repetition. Overall, CTEs offer a cleaner and more scalable way to handle complex data transformations or business logic.
Bad example:
SELECT * FROM (
SELECT customer_id, first_name, last_name
FROM customers
WHERE active = 1
) AS ActiveCustomers;
Good example:
WITH ActiveCustomers AS (
SELECT customer_id, first_name, last_name
FROM customers
WHERE active = 1
)
SELECT * FROM ActiveCustomers;
8. Use Comments Wisely
Using comments wisely in SQL helps make your queries easier to understand, especially for others who may read or maintain your code later. Good comments explain the purpose or logic behind complex sections without restating obvious code. They should be clear, concise, and placed on their own lines above the relevant query parts—not crammed at the end of a line. Avoid over-commenting or adding unnecessary notes that clutter the script. Thoughtful, well-placed comments can save time during debugging, make onboarding easier for new team members, and serve as helpful reminders when revisiting old queries.
Bad example:
SELECT customer_id, first_name, last_name FROM customers WHERE active = 1; # Get active customers
Good example:
# Get active customers only
SELECT customer_id, first_name, last_name
FROM customers
WHERE active = 1;
9. Avoid Using SELECT * (Use Specific Columns)
Avoiding SELECT * and using specific columns in your SQL queries is a best practice that improves performance, clarity, and maintainability. When you explicitly list only the columns you need, you reduce the amount of data transferred and processed, which can significantly enhance query efficiency—especially on large tables. It also makes the structure of your results predictable and easier to understand. Additionally, using SELECT * can introduce problems if the table structure changes, such as added or reordered columns. Being intentional with column selection ensures your queries remain stable, efficient, and easier to debug or review.
Bad example:
SELECT * FROM customers;
Good example:
SELECT first_name, last_name, email FROM customers;
10. Format CASE Statements Properly
Properly formatting CASE statements in SQL makes your queries more readable and easier to understand, especially when dealing with multiple conditions. Each part of the CASE block—WHEN, THEN, ELSE, and END—should be placed on its own line and indented to clearly show the logical flow. This structure helps separate each condition visually, reducing errors and making it easier for others to follow your logic. Well-formatted CASE statements are particularly useful in reports, conditional calculations, or when transforming data directly in queries. Clean formatting here contributes to more maintainable and professional-looking SQL code.
Bad example:
SELECT customer_id, first_name, last_name,
CASE WHEN active = 1 THEN 'Active' ELSE 'Inactive' END AS status FROM customers;
Good example:
SELECT
customer_id,
first_name,
last_name,
CASE
WHEN active = 1 THEN 'Active'
ELSE 'Inactive'
END AS status
FROM customers;
Final Summary
Using good practices and writing sophisticated SQL is essential for anyone aiming to be a professional in data work. Clean, well-structured queries not only reflect your attention to detail but also demonstrate your ability to communicate clearly through code. In real-world environments, SQL scripts are often shared, reused, or modified by others, so writing readable and maintainable queries shows respect for team collaboration and future maintenance. Good formatting also reduces the risk of errors, improves debugging efficiency, and helps you scale your work as projects become more complex. Ultimately, disciplined SQL writing is a hallmark of professionalism and a key part of building trust in your technical skills. Knowing the correct sintax is a basic skill we all need to practice, just as SQL formatting.
Rule | Best Practice |
---|---|
Keywords in UPPERCASE | SELECT, FROM, WHERE in uppercase |
Indentation | Each clause on a new line |
Align JOINs | Each table on a new line |
Use Aliases Consistently | Short, clear names (c for customers ) |
Use Meaningful Aliases | customer_id instead of cid |
Proper Spacing | Add spaces around operators (= , , , AND ) |
Use CTEs for Complex Queries | WITH temp_table AS (...) |
Use Comments Wisely | Keep them separate from code |
Avoid SELECT * | Select only necessary columns |
Format CASE Statements | Use multi-line formatting |
If you have any questions about SQL formatting, or you just want to chat, don’t hesitate to contact me!