SQL comments

SQL Tutorial

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?

It allows 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


Explaining calculations


Annotating JOIN logic


 

You may also like...