SQL Comments Guide
Learn how to write SQL comments, document queries, temporarily disable SQL code, and use comments effectively across different SQL dialects.
SQL comments are pieces of text that are ignored by the database engine when a query is executed. They are useful for explaining complex logic, documenting assumptions, temporarily disabling part of a query, and leaving notes for other developers.
Although comments do not change the result of a query by themselves, they are an important part of writing maintainable SQL. A short explanation can make a complicated JOIN, filtering condition, calculation, or business rule much easier to understand later.
What Are SQL Comments?
An SQL comment is text included in an SQL statement that the database treats as non-executable content. The SQL parser recognizes the comment syntax and ignores the commented text while processing the rest of the statement.
For example, a single-line comment can explain what a query is intended to return:
-- Get all active customers
SELECT *
FROM customers
WHERE status = 'active';The line beginning with -- is not executed. Only the SELECT statement is processed.
Why Use Comments in SQL?
SQL comments are especially useful when a query contains logic that is not immediately obvious from the syntax. Good comments explain why something is being done rather than simply repeating what the code already says.
- Explain complex business rules.
- Document assumptions about data.
- Describe complicated JOIN conditions.
- Explain calculated columns and unusual formulas.
- Temporarily disable SQL code while debugging.
- Separate logical sections of a long query.
- Leave notes for other developers.
- Document migration or maintenance scripts.
- Explain why a particular query structure was chosen.
SQL Single-Line Comments
The most common SQL comment syntax uses two hyphens: --. Everything after the comment marker on that line is treated as a comment.
-- Select active products
SELECT id, name, price
FROM products
WHERE active = true;A single-line comment can also appear after SQL code. In that case, the SQL before the comment is executed normally and the remainder of the line is ignored.
SELECT id, name, price -- Product information
FROM products
WHERE active = true;SQL Multi-Line Comments
SQL also commonly supports block comments using /* and */. Everything between these markers is treated as a comment, even when it spans multiple lines.
/*
Return active customers
with their current order count.
*/
SELECT
c.id,
c.name,
COUNT(o.id) AS order_count
FROM customers AS c
LEFT JOIN orders AS o
ON o.customer_id = c.id
WHERE c.status = 'active'
GROUP BY c.id, c.name;Block comments are useful when an explanation needs several lines or when you want to temporarily disable a larger section of SQL.
Commenting Out SQL Code
One practical use of comments is temporarily disabling part of a query. This is useful when debugging or comparing different versions of a statement.
SELECT
id,
name,
price
/* , cost */
FROM products
WHERE active = true;In this example, the cost column is temporarily excluded without deleting the original code. This can make experimentation faster during development.
You can also comment out a complete condition while testing a query:
SELECT id, name, price
FROM products
WHERE active = true
-- AND category_id = 10
ORDER BY price DESC;Comments Inside Complex Queries
Long SQL queries often contain several logical sections. Comments can make those sections easier to navigate without changing the query itself.
-- Select customer information
SELECT
c.id,
c.name,
c.email,
-- Calculate the total number of completed orders
COUNT(o.id) AS completed_orders,
-- Calculate the total amount spent by the customer
COALESCE(SUM(o.total), 0) AS total_spent
FROM customers AS c
-- Keep customers even when they have no orders
LEFT JOIN orders AS o
ON o.customer_id = c.id
AND o.status = 'completed'
WHERE c.status = 'active'
GROUP BY
c.id,
c.name,
c.email;Notice that the comments explain decisions and intent. The SQL syntax itself already makes it clear that COUNT and SUM are being used, so a comment such as "count orders" would add little value. Explaining why completed orders are filtered or why a LEFT JOIN is used is more useful.
Comments in SELECT Statements
Comments can document individual calculations in the SELECT list, especially when expressions are complicated.
SELECT
id,
price,
quantity,
-- Apply the current discount percentage
price * quantity * (1 - discount_percent / 100.0) AS discounted_total
FROM order_items;This is particularly useful when a calculated value represents a business rule that cannot be understood from the expression alone.
Comments in WHERE Conditions
Filtering logic can become difficult to understand when several conditions are combined. Comments can explain the purpose of an unusual condition or a specific exception.
SELECT id, name
FROM customers
WHERE status = 'active'
-- Exclude test accounts from production reports
AND is_test_account = false
AND created_at >= '2026-01-01';Be especially careful when placing comments around AND and OR conditions. Comments should never make it difficult to see how the conditions are grouped.
Comments in JOIN Conditions
JOIN logic is one of the most useful places for explanatory comments. A query may technically be correct while the reason for a particular JOIN condition remains unclear.
SELECT
p.id,
p.name,
c.name AS category
FROM products AS p
-- Only use categories that are currently visible
LEFT JOIN categories AS c
ON c.id = p.category_id
AND c.is_visible = true;The comment provides context for the additional condition. Without it, another developer might remove the condition while refactoring the query without realizing why it exists.
Comments in GROUP BY and HAVING Queries
Aggregation queries can also benefit from comments when the grouping or filtering logic represents a business requirement.
SELECT
customer_id,
COUNT(*) AS order_count,
SUM(total) AS revenue
FROM orders
WHERE status = 'completed'
GROUP BY customer_id
-- Include only customers with meaningful order activity
HAVING COUNT(*) >= 3;Comments in INSERT, UPDATE, and DELETE Statements
Comments are particularly valuable in data modification statements because the consequences of the query can be significant. A comment can document the purpose and intended scope of an operation.
-- Archive orders older than the retention period
UPDATE orders
SET archived = true
WHERE created_at < '2025-01-01'
AND archived = false;For destructive operations, comments can help document intent, but they are not a safety mechanism. Always verify the WHERE condition and test the affected rows before executing important UPDATE or DELETE statements.
SQL Comments and Readability
Comments should improve readability rather than compensate for unreadable SQL. Before adding a long explanation, consider whether the query itself can be made clearer with better formatting, meaningful aliases, simpler expressions, or a common table expression.
For example, a very long comment explaining an obscure calculation may indicate that the calculation should be extracted into a named CTE or otherwise reorganized.
WITH customer_totals AS (
SELECT
customer_id,
SUM(total) AS total_spent
FROM orders
WHERE status = 'completed'
GROUP BY customer_id
)
SELECT
c.id,
c.name,
ct.total_spent
FROM customers AS c
LEFT JOIN customer_totals AS ct
ON ct.customer_id = c.id;Good SQL Comments vs Bad SQL Comments
Not every comment improves a query. A useful comment provides information that would otherwise be difficult to infer from the SQL itself.
| Comment Type | Example | Usefulness |
|---|---|---|
| Describes obvious syntax | -- Select the name column | Usually unnecessary |
| Explains business logic | -- Exclude test accounts from reports | Useful |
| Documents an exception | -- Keep cancelled orders for audit reporting | Useful |
| Explains a complex calculation | -- Convert the stored amount from cents to currency units | Useful |
| Repeats the code | -- Sort by price descending | Usually unnecessary |
Avoid Over-Commenting
Adding comments to every SQL line can make a query harder to read rather than easier. Developers should not have to read a second explanation for every obvious operation.
-- Select id
SELECT
id,
-- Select name
name,
-- Select price
price
-- From products
FROM products;These comments provide almost no additional information. The SQL already clearly communicates what each line does.
A better approach is to comment the reason or context when there is something worth documenting:
-- Prices are stored in cents and converted to currency units here
SELECT
id,
name,
price / 100.0 AS price
FROM products;Comments and SQL Formatting
Formatting and comments work together. A well-formatted query makes its structure visible, while comments provide additional context where the structure alone is insufficient.
Consistent indentation is particularly important when comments are placed between clauses, JOIN conditions, or groups of expressions.
SELECT
c.id,
c.name,
COUNT(o.id) AS order_count
FROM customers AS c
-- Include completed orders only
LEFT JOIN orders AS o
ON o.customer_id = c.id
AND o.status = 'completed'
WHERE c.status = 'active'
GROUP BY
c.id,
c.name;SQL Comments in Database Scripts
Comments are useful beyond individual queries. Database migration scripts, setup scripts, seed files, stored procedures, and maintenance scripts can all benefit from documentation.
-- Add the column required for the new customer status workflow
ALTER TABLE customers
ADD COLUMN account_status VARCHAR(20);
-- Existing records start with the default active state
UPDATE customers
SET account_status = 'active'
WHERE account_status IS NULL;In scripts that are executed only once, comments can be especially helpful because they preserve the reasoning behind a schema or data change.
SQL Comments and Version Control
Comments are part of the SQL source code and therefore can be stored in Git or another version-control system. This makes them useful for documenting stable decisions that future developers may need to understand.
However, comments should not become a replacement for commit messages, documentation, tickets, or architectural notes. Each type of documentation has a different purpose.
| Information | Good Location |
|---|---|
| Why a query contains an unusual condition | SQL comment |
| Why a database migration was introduced | Migration or project documentation |
| What changed in a version | Git commit or changelog |
| Detailed business requirements | Project documentation |
| Temporary debugging notes | Local SQL or development notes |
SQL Comments and Security
Comments are not private storage. Depending on the database, application, logging configuration, query-monitoring system, or development workflow, SQL text may be recorded or exposed to people who can access query logs or source code.
SQL Comments and Minification
SQL minifiers can remove comments when the goal is to reduce query size or produce compact SQL. This can be useful for generated or transmitted SQL, but it also means comments may disappear from the minified version.
For human-maintained SQL, keep the readable source version as the canonical version and generate a compact version only when there is a specific reason to do so.
Comments Across SQL Dialects
The -- and /* ... */ forms are widely supported across modern SQL database systems, but exact comment behavior can differ between database engines, client tools, and SQL modes.
| Syntax | Typical Use |
|---|---|
| -- comment | Single-line comment |
| /* comment */ | Block or multi-line comment |
Some database systems or tools may support additional comment-related syntax or special conventions. When writing portable SQL, prefer broadly supported syntax and verify behavior against the target database.
Common SQL Comment Mistakes
Comment syntax is simple, but comments can still cause problems when they are placed incorrectly or contain misleading information.
- Forgetting that -- comments continue to the end of the line.
- Using unsupported comment syntax for the target SQL dialect.
- Accidentally commenting out part of a query.
- Leaving obsolete debugging comments in production SQL.
- Writing comments that merely repeat obvious SQL syntax.
- Documenting what the code does while failing to explain why it does it.
- Putting credentials or secrets inside comments.
- Using comments to hide dangerous UPDATE or DELETE statements.
- Allowing comments to become outdated after the query changes.
- Using excessive comments instead of simplifying the SQL.
How to Write Better SQL Comments
Good SQL comments are short, accurate, and focused on information that is not obvious from the query itself.
- Explain why unusual logic exists.
- Document important business rules.
- Explain assumptions about the data.
- Document intentional exceptions.
- Keep comments close to the SQL they describe.
- Use consistent wording and style across a project.
- Update comments when the associated SQL changes.
- Remove temporary debugging comments when they are no longer needed.
- Prefer clear SQL structure over excessive commentary.
- Never store secrets in comments.
A Practical SQL Commenting Workflow
When writing or reviewing a complex SQL query, a simple workflow can help determine where comments are actually needed.
- Format the SQL so its structure is easy to read.
- Identify sections whose purpose is not immediately obvious.
- Add comments explaining business rules, assumptions, or unusual decisions.
- Remove comments that simply describe obvious SQL syntax.
- Validate the query after adding or removing comments.
- Test the query to confirm that commenting or uncommenting code did not change its intended behavior.
- Remove temporary debugging comments before committing production code.
SQL Comments Checklist
Before committing an SQL query, use this checklist to review its comments:
- Are comments explaining intent rather than obvious syntax?
- Are business rules and important assumptions documented?
- Are comments still accurate?
- Have temporary debugging comments been removed?
- Are there any credentials or secrets in the comments?
- Is the SQL itself formatted clearly?
- Would restructuring the query make some comments unnecessary?
- Does the query still validate and execute correctly?
Frequently Asked Questions
What is the syntax for a single-line SQL comment?
The most common syntax is two hyphens followed by the comment text: -- comment. The comment normally continues until the end of the line.
How do you write a multi-line SQL comment?
Use /* to start a block comment and */ to end it. Text between these markers can span multiple lines.
Do SQL comments affect query performance?
Comments are generally removed or ignored during SQL parsing and do not affect the logical result of a query. However, database clients, query tools, or middleware may process SQL text before it reaches the database.
Can SQL comments be used to disable code temporarily?
Yes. Commenting out a condition, column, JOIN, or larger section can be useful during development and debugging. Temporary commented-out code should normally be removed once it is no longer needed.
Should SQL comments explain what the query does?
Usually, comments are more valuable when they explain why the query does something, especially when the reason is not obvious from the SQL itself. Obvious operations generally do not need comments.
Can I put passwords or API keys in SQL comments?
No. Comments should be treated as source code and may be stored in repositories, logs, monitoring systems, or other places where they can be accessed. Never use comments as secret storage.
Are SQL comments the same in every database?
The -- and /* ... */ forms are widely supported, but exact behavior and additional syntax can vary between database systems and client tools. Check the documentation for the database you are targeting when portability matters.
Helpful SQL Tools
Several types of online SQL tools can make working with commented queries easier. SQL formatters can improve indentation and make comments easier to associate with the relevant code. Syntax highlighters can visually distinguish comments from executable SQL. Validators can help confirm that a query remains syntactically correct after temporarily commenting or uncommenting sections. Query explainers can help clarify unfamiliar SQL logic, while minifiers can produce a compact version when comments and formatting are no longer needed.
Conclusion
SQL comments are a simple but useful part of writing maintainable database code. Single-line comments with -- are convenient for short notes, while block comments using /* and */ are useful for longer explanations and temporarily disabling larger sections.
The most effective comments explain intent, business rules, assumptions, and unusual decisions rather than repeating obvious SQL syntax. Keep comments accurate and concise, remove temporary debugging notes when they are no longer needed, and never store sensitive information inside them.