SQL — Comments
Single-Line Comments
Use -- for single-line comments:
-- This query retrieves all active users
SELECT * FROM users WHERE status = 'active';
SELECT
name, -- employee name
salary, -- annual salary
department -- department name
FROM employees;
Multi-Line Comments
Use /* ... */ for comments that span multiple lines:
/*
This report shows monthly revenue
for each product category.
Run monthly on the 1st.
*/
SELECT
category,
SUM(amount) AS revenue
FROM orders
GROUP BY category;
Inline Comments
Mix comments with code on the same line:
SELECT name, salary
FROM employees
WHERE salary > 50000 -- only well-paid
AND department = 'IT'; -- tech team only
Commenting Out Code
Temporarily disable a line or block without deleting it:
SELECT * FROM users
WHERE status = 'active';
-- WHERE status = 'inactive'; -- disabled temporarily
/*
SELECT * FROM users
WHERE status = 'pending';
*/
Use Cases
Documenting complex queries
-- Step 1: Get total sales per region
-- Step 2: Filter to regions with > 100 orders
-- Step 3: Rank by revenue
WITH regional_sales AS (
SELECT
region,
COUNT(*) AS order_count,
SUM(amount) AS total_revenue
FROM orders
GROUP BY region
HAVING COUNT(*) > 100
)
SELECT *,
RANK() OVER (ORDER BY total_revenue DESC) AS revenue_rank
FROM regional_sales;
Marking authorship and dates
-- Author: Krishna
-- Date: 2025-06-15
-- Purpose: Monthly KPI report
-- Last modified: 2025-07-01
SELECT COUNT(*) AS new_users
FROM users
WHERE created_at >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH);
Best Practices
- Write comments that explain why, not what
- Keep comments up to date — remove stale comments
- Use comments to mark TODOs and FIXMEs
- Don't over-comment obvious code
- Use block comments for file-level documentation
Practice
- Add inline comments explaining each column in a
SELECTquery - Write a block comment documenting a complex
JOINquery - Comment out a
WHEREclause temporarily for testing
Related Topics
Frequently Asked Questions about Comments
What is Comments in SQL?
Comments is a fundamental concept in SQL. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Comments?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Comments.
Why is Comments important in SQL?
Comments is essential for SQL development. Understanding this concept will help you write better code and solve real-world problems more effectively.