SQL - Comments
SQL - Comments
Section titled “SQL - Comments”A comment is a piece of text within a program or script that is ignored by the compiler or interpreter. In SQL, comments serve two main purposes: to explain complex sections of code for human readers, and to temporarily disable parts of a statement during debugging.
Single-Line Comments
Section titled “Single-Line Comments”A single-line comment starts with two consecutive hyphens (--) and extends to the end of the line. Any text after the hyphens on that line will not be executed.
MySQL also supports the hash symbol (#) for single-line comments.
Syntax
Section titled “Syntax”-- This is a single-line comment.Example: Explaining a Query
Section titled “Example: Explaining a Query”-- Retrieve all active users who registered in the last 90 daysSELECT UserID, EmailFROM UsersWHERE IsActive = TRUE AND CreatedAt >= CURRENT_DATE - INTERVAL '90 days';Example: Disabling Code
Section titled “Example: Disabling Code”Here, we can temporarily disable the ORDER BY clause to test the query’s behavior without sorting.
SELECT * FROM CustomersWHERE City = 'New York'-- ORDER BY LastName ASC;Multi-Line Comments
Section titled “Multi-Line Comments”A multi-line comment is used to comment out a block of SQL code. It starts with /* and ends with */. All text between these delimiters will be ignored.
Syntax
Section titled “Syntax”/* This is a multi-line comment. It can span several lines.*/Example: Explaining a Complex Join
Section titled “Example: Explaining a Complex Join”/* This query calculates the total sales for each product category. It joins three tables: - Categories: to get the category name. - Products: to link categories and order items. - OrderItems: to get the quantity and price for each sale.*/SELECT c.CategoryName, SUM(oi.Quantity * oi.UnitPrice) AS TotalSalesFROM Categories cJOIN Products p ON c.CategoryID = p.CategoryIDJOIN OrderItems oi ON p.ProductID = oi.ProductIDGROUP BY c.CategoryName;Example: Disabling a Block of Code
Section titled “Example: Disabling a Block of Code”Multi-line comments are also useful for disabling a part of a WHERE clause during debugging.
SELECT * FROM ProductsWHERE CategoryID = 1/* AND IsAvailable = TRUE AND Price < 100.00*/