SQL Comments and Query Formatting
Learn to document SQL queries with single-line and block comments, apply consistent formatting conventions, organize complex queries, and write maintainable SQL that is easier to debug, review, and share.
In this lesson, you will learn
- ✓Write single-line comments using double dashes (--).
- ✓Write multi-line comments using /* ... */.
- ✓Explain how comments interact with SQL syntax and query strings.
- ✓Apply consistent keyword casing, identifier naming, indentation, and comma placement.
- ✓Format SELECT statements, filters, joins, and sorting clauses for readability.
- ✓Distinguish useful comments from comments that merely repeat the SQL code.
- ✓Identify formatting and commenting mistakes that can cause query errors or unintended behavior.
1. Why SQL Comments Matter
SQL comments are notes written inside SQL code. They help developers explain the purpose of a query, document unusual business rules, identify assumptions, and temporarily disable part of a statement while debugging.
Consider a query that retrieves active customers. The SQL tells us what data is selected, but a comment can explain why inactive customers are excluded. This becomes especially useful when another developer reviews the query months later.
A good comment adds information that is not immediately obvious from the code. Avoid writing comments that simply repeat what the SQL already says.
A Query With a Useful Comment
The comment describes the business reason for the filter. The database query still determines which rows are returned.
2. Single-Line Comments Using --
In PostgreSQL, two consecutive hyphens introduce a single-line comment. Everything after -- is treated as a comment until the end of that line.
The comment can occupy a line by itself or appear after a SQL expression. The SQL statement must still have valid syntax after comments are ignored.
Single-Line Comment Examples
The first comment documents the query's purpose. The inline comments explain individual columns. Neither comment changes the result.
3. Multi-Line Comments Using /* ... */
A block comment begins with /* and ends with */. It can span several lines, making it useful for longer explanations, assumptions, and temporary debugging notes.
Everything between the opening and closing delimiters is treated as a comment. PostgreSQL supports nested block comments, although support for nested comments differs between SQL implementations. For portable SQL, avoid relying on nesting.
A Multi-Line Documentation Block
The block comment records the purpose and business assumption. The SELECT statement performs the actual filtering.
4. Commenting Out SQL During Debugging
Developers sometimes temporarily disable a condition to compare query results. A single-line comment can disable one condition, provided the comment does not accidentally remove other required SQL.
Always review the resulting statement after changing comments. Disabling a filter may expose more records than intended, and disabling a join condition may create a much larger result set.
Temporarily Disable a Filter
The spending condition is commented out. The active-customer filter and ORDER BY clause remain part of the query.
5. An Important Rule: Comments End at the Newline
A single-line comment consumes the rest of its line. This matters when SQL is generated inside a programming-language string or assembled from multiple fragments.
Consider this SQL text:
SELECT customer_id FROM customers -- customer identifier WHERE is_active = TRUE
Everything after -- on that same line is a comment. The WHERE condition is not executed. The query can therefore return inactive customers too.
In application code, preserve actual line breaks when using -- comments. If you need a comment inside a single-line SQL string, a block comment may be appropriate, provided the SQL syntax and comment delimiters remain valid.
Unsafe Versus Safe SQL Text
The location of the newline changes which SQL text is treated as a comment. Always inspect generated SQL when debugging application queries.
6. The CodeNivo SQL Style Guide
A style guide defines how a team writes and formats SQL. Different organizations choose different conventions. The following rules form a consistent beginner-friendly standard for CodeNivo.
These are readability conventions rather than mandatory SQL syntax rules. A correctly written lowercase SELECT can work just as well as uppercase SELECT.
| Element | Recommended style | Example |
|---|---|---|
| SQL keywords | UPPERCASE | SELECT, FROM, WHERE, ORDER BY |
| Table names | lowercase snake_case | customer_orders |
| Column names | lowercase snake_case | created_at, first_name |
| Major clauses | One clause per line | FROM on its own line |
| Indentation | Two spaces per nesting level | AND is_active = TRUE |
| Column lists | One column per line for long lists | customer_id, then full_name |
| JOIN conditions | Indent ON beneath JOIN | ON o.customer_id = c.customer_id |
| Statement endings | Use semicolons consistently | SELECT 1; |
| Aliases | Use short, meaningful names | orders AS o |
| Comments | Explain purpose or non-obvious rules | -- Exclude test accounts |
7. Uppercase Keywords and Identifier Naming
SQL keywords are often written in uppercase so that they stand out from table and column names. Identifiers name database objects, such as tables, columns, and aliases.
For PostgreSQL, unquoted identifiers are folded to lowercase. For example, CUSTOMER_ID and customer_id refer to the same unquoted identifier. Quoted identifiers preserve case and must generally be referenced with the same case and quotation marks.
Prefer ordinary lowercase snake_case identifiers for new projects unless an existing schema uses another standard.
Consistent Naming and Casing
Keywords are uppercase, while identifiers use lowercase snake_case. This makes the statement easier to scan.
8. One Column Per Line
Short queries can fit comfortably on one line. Longer queries are usually easier to read when each selected column has its own line. This also makes it easier to add, remove, or compare columns during code review.
Choose either trailing commas or a consistent leading-comma style. This lesson uses trailing commas, which are familiar to many beginners.
Readable SELECT Lists
Each selected column appears on its own line, and the comma placement makes the list structure clear.
9. Formatting WHERE Conditions
When a query has multiple conditions, place AND and OR conditions on separate indented lines. Use parentheses when combining AND and OR if they make the intended logic clearer.
Formatting cannot fix incorrect logic by itself. Review the condition order and grouping as well as the indentation.
Readable Filtering Conditions
Each condition is visually separated, so the filter is easier to understand and modify.
10. Formatting JOINs for Code Review
JOIN statements connect related tables. Indenting the ON condition beneath the JOIN makes the relationship between tables easy to identify.
Use meaningful aliases and qualify columns with aliases when the query references multiple tables. This prevents ambiguity when different tables contain columns with the same name.
A Readable Multi-Table Query
The table aliases are short and consistent. The JOIN relationship, filter, sort, and row limit are visually distinct.
11. Formatting a More Complex Query
A well-formatted query helps reviewers verify which records are selected, how tables are related, and how the results are sorted. The following example combines a JOIN, multiple conditions, and ordering.
The example assumes that the orders and customers tables contain the referenced columns.
Production-Style Query
The date literal, business filters, join condition, and tie-breaking sort key are all easy to identify. The specific results depend on the database contents.
12. Useful Comments Versus Unnecessary Comments
Comments should explain intent, assumptions, exceptions, and business rules. They should not create noise by describing every obvious operation.
For example, a comment that says 'Select customer ID' above SELECT customer_id adds little information. A comment that explains why certain customers must be excluded may preserve important business context.
| Comment | Assessment | Reason |
|---|---|---|
| -- Get customer ID | Usually unnecessary | The SQL already shows this. |
| -- Exclude test accounts from revenue reports. | Useful | Explains a business rule. |
| -- Temporary workaround until archived orders are migrated. | Useful if maintained | Documents a dependency and reason. |
| -- This query always returns correct results. | Avoid | An unsupported claim does not explain the logic. |
| -- Password is example123 | Unsafe | Comments are not a place for secrets. |
13. SQL Comments and Performance
Comments are generally not part of the logical operations performed by a SQL query. A comment does not change which rows a valid SELECT statement matches when it is added without changing the statement's meaning.
However, avoid making the absolute claim that comments can never affect performance. Database clients and drivers may process query text, and some database systems or monitoring tools interpret special comment forms as hints or metadata. PostgreSQL also has special considerations for planner hints supplied through extensions.
For ordinary PostgreSQL comments, focus on correctness and maintainability. Query performance is primarily influenced by the query, schema, indexes, data distribution, execution plan, and database workload.
Comments Do Not Replace Query Optimization
The comment explains the query. It does not create an index, guarantee a particular execution plan, or make an inefficient query efficient.
14. Comments Are Not a Security Mechanism
Never put passwords, access tokens, private customer information, or other secrets in SQL comments. Comments are part of the query text before they are interpreted by the database. They may be retained in source code, logs, monitoring systems, tickets, or debugging output.
Comments also do not protect a query from SQL injection. Applications should use parameterized queries or prepared statements rather than building SQL by directly concatenating untrusted user input.
Document a Parameterized Query
This illustrates PostgreSQL parameter syntax used by many drivers and prepared statements. The exact binding API depends on the programming language and driver.
15. Formatting in Application Code
SQL can be embedded in JavaScript, Python, Go, and other languages. Keep the SQL readable inside the string, and use the language's multiline-string syntax when available.
The important rule is to preserve line breaks when using -- comments. A language may concatenate adjacent string fragments or construct SQL dynamically, so inspect the final query text if a filter appears to be missing.
Use parameters for data values. Do not concatenate raw user input into a query simply to make the SQL string easier to construct.
Readable Multiline SQL Text
This is the SQL text an application might send to PostgreSQL. The application must bind a value to $1 using its database driver.
16. Common Formatting Errors
Formatting mistakes can make SQL harder to review, and comment mistakes can change which parts of a query are executed. Before running a query, check the statement's delimiters, line breaks, clause order, and semicolon placement.
A semicolon ends a SQL statement; it does not end a -- comment. The newline ends that comment. A block comment, on the other hand, ends only when its closing */ delimiter appears.
Correct the Comment Placement
The first statement treats the filter as a comment. The second puts the condition on its own line.
17. Formatting Checklist
Before sharing SQL with a teammate or committing it to a project, check the following:
- SQL keywords use a consistent case.
- Table and column names follow the project's naming convention.
- Major clauses appear on separate lines.
- Long column lists are easy to scan.
- JOIN conditions are clearly indented.
- Multiple filters are separated onto readable lines.
- Parentheses make complex logical conditions clear.
- Comments explain purpose, business rules, or non-obvious decisions.
- Single-line comments do not accidentally hide later SQL clauses.
- No credentials or sensitive values appear in comments.
- The query has been tested against the intended schema and data.
A formatting checklist improves consistency, but it does not replace SQL testing or review of the business logic.
18. Multiple-Choice Questions
Choose the best answer for each question. Answers and explanations follow the questions.
19. Guided Practice
Complete these tasks using the customers and orders tables described in the examples. If your local schema uses different column names, adapt the statements to match it.
Task 1: Write a query that retrieves active customers and includes a single-line comment explaining why the filter exists.
Task 2: Write a query that retrieves order_id, customer_id, order_date, and total_amount from orders. Put each column on its own line and add a useful block comment above the query.
Task 3: Format a query joining orders and customers. Return order ID, customer name, and total amount. Include only completed orders and sort by total amount in descending order.
Task 4: Explain why this SQL may be incorrect when sent as one line: SELECT customer_id FROM customers -- identifier WHERE is_active = TRUE;
20. Guided Practice Solutions
Compare your work with these solutions. The exact rows returned depend on your database contents.
Task 1: Active Customers
The comment explains the business purpose of the filter.
21. More Practice Solutions
The remaining solutions demonstrate block comments, readable column lists, JOIN formatting, and the single-line comment rule.
Task 2: Order Details
The block comment documents the purpose and schema assumption.
22. JOIN Practice Solution
Use clear aliases and indentation to make the table relationship and filter easy to identify.
Task 3: Completed Orders
The ON clause describes the relationship between tables, while WHERE filters the joined rows.
23. Debugging Practice Solution
The fourth task illustrates why comment boundaries must be understood when writing SQL inside application strings.
Task 4: Restore the Filter
In the original one-line statement, WHERE is_active = TRUE comes after -- and is therefore part of the comment. Moving the condition to a new line restores the filter.
24. SQL Interview Questions and Answers
Q1. What is a SQL comment?
A: A comment is explanatory text that is not treated as ordinary SQL syntax in the statement.
Q2. How do you write a single-line comment in PostgreSQL?
A: Start it with two hyphens: --.
Q3. How do you write a block comment?
A: Start with /* and close with */.
Q4. What is the difference between a single-line and block comment?
A: A -- comment ends at the newline, while a block comment ends at its closing delimiter.
Q5. Can a comment appear after a SQL expression?
A: Yes. For example, SELECT customer_id -- identifier, provided the remaining SQL is structured correctly.
Q6. Why do developers use uppercase keywords?
A: It is a readability convention that helps distinguish SQL syntax from identifiers.
Q7. Is uppercase SQL mandatory?
A: No. SQL keywords are generally case-insensitive, subject to dialect-specific rules and contexts.
Q8. What is snake_case?
A: A naming style that uses lowercase words separated by underscores, such as customer_orders.
Q9. Why is consistent indentation important?
A: It makes clauses, conditions, and nested logic easier to understand and review.
Q10. What makes a comment useful?
A: It explains intent, business rules, assumptions, exceptions, or non-obvious decisions.
Q11. Why should comments not repeat every SQL operation?
A: Redundant comments create noise and can become inaccurate when code changes.
Q12. Can a comment change which rows a query returns?
A: A correctly placed ordinary comment does not change query logic, but incorrectly placed comments can hide part of a statement.
Q13. Why can -- be dangerous in a generated one-line query?
A: Everything after it on that line is treated as a comment, potentially hiding filters or other clauses.
Q14. Are comments a reliable way to hide passwords?
A: No. Comments may be stored in source code, logs, or monitoring tools. Secrets should not be included in query comments.
Q15. Do comments prevent SQL injection?
A: No. Applications should use parameterized queries and avoid concatenating untrusted input into SQL.
Q16. Do comments automatically improve query performance?
A: No. Their primary purpose is documentation. Performance depends on the query plan, schema, indexes, data, and workload.
Q17. Why should JOIN conditions be indented?
A: It visually separates the table relationship from filters and other clauses.
Q18. Should every query have a comment?
A: Not necessarily. Add comments when they convey meaningful context; do not add redundant notes merely to meet a quota.
Q19. Why use meaningful table aliases?
A: They reduce repetition and help identify which table a column belongs to, particularly in multi-table queries.
Q20. What should you check before sharing a formatted query?
A: Confirm the syntax, comment boundaries, schema references, intended business logic, and behavior against representative data.
25. Lesson Summary
You have learned how to document and format SQL statements using practical conventions.
- Use -- for single-line comments.
- Use /* ... */ for block comments.
- Remember that -- comments continue until the newline, not merely until the semicolon.
- Use consistent keyword casing, identifier naming, indentation, and comma placement.
- Format JOIN conditions and WHERE filters so their relationships are clear.
- Write comments that explain intent and non-obvious business rules.
- Never place secrets in comments or rely on comments for SQL injection protection.
- Use parameterized queries for application-supplied values.
- Treat formatting as a maintainability practice, not a substitute for correctness testing or performance analysis.
26. Common Mistakes
Review these mistakes before moving to the next lesson.
Ready for hands-on challenges?
Test your skills with shuffled coding challenges in the Practice Arena.
Key takeaways
- A single-line comment begins with -- and continues to the end of the line.
- A block comment begins with /* and ends with */.
- Comments explain why a query exists or why a particular decision was made.
- Consistent formatting improves readability without changing the logical meaning of a correctly formatted query.
- Uppercase SQL keywords and lowercase snake_case identifiers are conventions, not universal SQL requirements.
- SQL string literals use single quotes, while double quotes are commonly used for delimited identifiers in PostgreSQL.
- Comments should not be treated as a security mechanism for hiding sensitive information.
- Formatting tools can improve consistency, but they cannot determine whether a query expresses the correct business requirement.