SQL comments

Here is a clean, practical guide to writing SQL comments, with syntax and best-practice examples for all major SQL databases.


✅ What Are SQL Comments?

SQL comments allow you to add notes, explanations, or disable parts of code without affecting execution.

They are ignored by the SQL engine.


🔹 1. Single-Line Comments

Style A: -- (ANSI Standard)

✔ Works in PostgreSQL, SQL Server, Oracle, SQLite
✔ Supported in MySQL (unless sql_mode=ansi is off)

-- This selects all users
SELECT * FROM users;

Style B: # (MySQL Only)

# MySQL single-line comment
SELECT * FROM customers;

🔹 2. Multi-Line Comments (Block Comments)

✔ Works in MySQL, PostgreSQL, SQL Server, Oracle

/*
This is a multi-line comment
Useful for longer explanations
*/

SELECT * FROM orders;

🔥 Comment Out Code Blocks

/*
SELECT * FROM users;
SELECT * FROM orders;
*/

SELECT * FROM products;

🔥 Inline Comments

SELECT price, quantity /* calculate total */
FROM sales;

🔧 Using Comments for Debugging Queries

Temporarily disable conditions:

SELECT *
FROM employees
WHERE department = 'Sales'
/* AND salary > 50000 */
;

🧠 Best Practices

✔ Use comments to explain why, not what
✔ Avoid over-commenting obvious SQL
✔ Use block comments when disabling multiple lines
✔ Keep comments updated when queries change
✔ In production stored procedures, document logic heavily


✔ Real-World Examples

Documenting business rules

-- Only count active subscriptions
SELECT COUNT(*)
FROM subscriptions
WHERE status = 'active';

Explaining calculations

SELECT
amount,
tax_rate,
/* final price = amount + (amount * tax_rate) */
amount + (amount * tax_rate) AS final_price
FROM invoices;

Annotating JOIN logic

SELECT u.id, u.name, o.total
FROM users u
LEFT JOIN orders o
ON u.id = o.user_id -- match orders to users
WHERE u.is_active = 1;

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *