SQL Cookbook Lesson
How to comment in SQL
Learn how to comment in SQL with examples and explanations from SQLPad.
Problem
You are writing a SQL query and you want to add comments to your code to make it easier for others to understand. How do you add comments in SQL?
Sample Data
This is a sample SQL query where we want to add comments:
SELECT * FROM employees WHERE name = 'John Doe'
MySQL Solution
-- This is a single line comment
SELECT * FROM employees -- Select all fields from employees table
WHERE name = 'John Doe' -- Only for records where name is 'John Doe'
Or for multiple lines comment:
/*
This is a multiple
lines comment
*/
SELECT * FROM employees
WHERE name = 'John Doe'
PostgreSQL Solution
-- This is a single line comment
SELECT * FROM employees -- Select all fields from employees table
WHERE name = 'John Doe' -- Only for records where name is 'John Doe'
Or for multiple lines comment:
/*
This is a multiple
lines comment
*/
SELECT * FROM employees
WHERE name = 'John Doe'
Explanation
Comments in SQL are used to explain parts of SQL statements, or to prevent execution of SQL statements.
In MySQL and PostgreSQL, we can create a single line comment by using two hyphens (--). The SQL engine will ignore anything that comes after the -- on the same line.
For multiple lines comments, we can use / to start the comment and / to close the comment. Everything between these two symbols will be treated as a comment.
It's important to note that the way to comment in SQL is standard across not just MySQL and PostgreSQL, but virtually all SQL databases.