Module 01 · lesson 8
Comments and formatting SQL
A month later you open your own query and don't remember what it's for. And a colleague won't understand it at all. Code is read more often than it's written.
Why keep it tidy
SQL is written once but read many times — by you a month later, and by your colleagues. So a query should be easy for a human to read. (Right now this may seem unnecessary, since so far the queries have been simple, but they do get more complex.)
Comments
The DBMS ignores comments, but they explain intent:
-- a single-line comment
/* a multi-line
comment */
Formatting
A well-formatted query reads at a glance:
-- Top 5 products by stock
SELECT name, stock
FROM products
ORDER BY stock DESC
LIMIT 5;
-- Top 5 products by stock
select name, stock FROM products
ORDER by stock desc LIMIT 5;
The first query reads more easily than the second, even though they're essentially the same.
Habits that help:
- keywords in uppercase (
SELECT,FROM,ORDER BY); - each major section on a new line;
- indentation for nesting.
The case of keywords doesn't affect how the query runs — it's purely for humans. But uppercase makes the structure stand out.
Your turn
Here's a messy one-line query. Rewrite it cleanly — and add a comment saying what it does.
Summary
--is a single-line comment,/* ... */a multi-line one.- Keywords are
UPPERCASEby convention. - Formatting doesn't change the result — only readability.