SQL Syntax and Comments: A Clear Beginner Reference

SQL syntax defines how keywords, names, values and punctuation form valid database statements; comments explain a statement without becoming part of its calculation.

Lesson 26 of 102Beginner11 min read

SQL syntax defines how keywords, names, values and punctuation form valid database statements; comments explain a statement without becoming part of its calculation.

A SQL statement is a request to the database. Learning to distinguish its parts makes error messages less mysterious: a missing keyword, a misspelled table and an unfinished string are different problems with different fixes.

This reference adds detail to the main course. You can read it independently: the small database below supplies every table and row used in the examples. Start with the question each query answers, then compare the returned values with the data rather than memorising a line of syntax.

Set up the practice database

Run this setup once in a new practice database, before the examples. It uses four customers and six sales. Ana has two sales, Ben has one, Cara has two, and Dev has none.

Sale 106 has no customer link; sale 104 has an unknown amount. These deliberate test cases expose missing information and unmatched relationships.

SQL
CREATE TABLE customers (
  id INTEGER PRIMARY KEY,
  name VARCHAR(40) NOT NULL,
  city VARCHAR(40),
  manager_id INTEGER
);
CREATE TABLE sales (
  id INTEGER PRIMARY KEY,
  customer_id INTEGER,
  amount DECIMAL(10,2),
  status VARCHAR(20) NOT NULL,
  created_on DATE NOT NULL
);
INSERT INTO customers (id,name,city,manager_id) VALUES
  (1,'Ana','Leeds',NULL),(2,'Ben','Leeds',1),
  (3,'Cara','Porto',1),(4,'Dev',NULL,2);
INSERT INTO sales (id,customer_id,amount,status,created_on) VALUES
  (101,1,10,'paid','2026-01-01'),
  (102,1,30,'pending','2026-01-02'),
  (103,2,20,'paid','2026-01-02'),
  (104,3,NULL,'pending','2026-02-01'),
  (105,3,20,'paid','2026-02-02'),
  (106,NULL,5,'paid','2026-02-03');

An amount of zero would be a known value. The NULL amount here means the value is unknown. A customer with no matching sale differs from a sale whose customer_id is NULL.

The primary keys identify individual records even when amounts or cities repeat. Dates use year-month-day format. The examples specify sorting whenever order matters; insertion order alone does not guarantee display order.

How SQL syntax and comments works

A statement consists of tokens. SELECT and FROM are keywords with a defined role; customers and name are identifiers that refer to your database objects; 'Leeds' is a string literal, meaning a value you wrote directly. Numbers such as 20 are numeric literals. Spaces and line breaks separate these parts, but formatting a clause on a new line does not change its meaning. The semicolon marks the end of a statement, which is especially useful in scripts containing several requests.

Write text values in single quotes. An apostrophe inside a text literal is represented by two apostrophes, as in 'O''Brien'. Do not put ordinary table names inside single quotes: that turns a name into a string value. Quoted identifiers use different punctuation depending on the database. Simple lower-case names without spaces are easiest for a beginner to move between systems. SQL keywords may be written in lower case or upper case; uppercase keywords are a reading convention rather than a requirement.

Line comments and block comments

A line comment begins with two hyphens and continues to the end of that line. Leave a space after the hyphens for portability. A block comment begins with slash-star and ends with star-slash, and can span several lines. Use comments to explain a business rule, such as why a sale is excluded, rather than merely repeating the words of the query. Nesting block comments is not portable, so avoid placing one inside another when sharing a script.

Clause order matters even though indentation does not. A simple reading query writes SELECT, FROM, WHERE, then ORDER BY. Put commas between selected expressions, but not before FROM. Parentheses must balance, and strings must close. When a tool reports an error near a token, inspect both that token and the text immediately before it: an earlier missing quote or comma can make a later keyword appear to be the problem. Execute one complete statement at a time while learning.

MySQL, PostgreSQL, SQL Server and SQLite

The example runs on all four systems. MySQL requires whitespace or a control character after -- to recognise a line comment. MySQL normally quotes identifiers with backticks, PostgreSQL and standard SQL use double quotes, and SQL Server commonly uses brackets. MySQL double-quote behaviour depends on SQL mode; avoid borrowing identifier quoting without checking it.

Check the engine-specific syntax and version requirements in PostgreSQL lexical structure.

Practice task and worked solution

Write a query that returns id and name for the customer named Cara, sorted by id. Add a line comment explaining that this checks the Porto customer in the sample data.

Try the task before reading its worked solution. The supplied rows make the expected answer checkable by hand.

SQL
-- Check the Porto customer in the sample.
SELECT id, name FROM customers
WHERE name = 'Cara' ORDER BY id;
Output
id | name
3  | Cara

The comma separates the two output columns. The string literal Cara is compared with the name column, so exactly one row remains. The comment is ignored during execution. Removing the comment should produce precisely the same result.

Try SELECT id name FROM customers and inspect the returned heading: name can become an alias for id because the comma is absent. Then restore the comma. Add a trailing comment after the semicolon and verify the values stay unchanged. Finally use a literal such as 'O''Brien' in SELECT to practise escaping an apostrophe without changing a stored name.

SQL Syntax and Comments: A Clear Beginner Reference Syntax

SQL syntax and comments

-- Show customers with a known Leeds address.
SELECT id, name
FROM customers
WHERE city = 'Leeds'
ORDER BY id;

SQL Syntax and Comments: A Clear Beginner Reference Summary

  • A statement is built from keywords such as SELECT, identifiers such as customers, literals such as 'Leeds' and punctuation.
  • Single quotes mark text values; unquoted words are read as keywords or names.
  • -- starts a comment to the end of the line, and /* ... */ can span several lines.
  • Comments explain the reason for a rule and never change the result.
  • The semicolon ends a statement, which matters most in scripts with several statements.

SQL Syntax and Comments: A Clear Beginner Reference Examples

Each example shows the code, the output it produces and what each part does.

Example 1

A commented query for Leeds customers

The comment describes the selection rule. SELECT chooses two columns, FROM names the table, WHERE keeps the two Leeds customers and ORDER BY makes the result reproducible. No text from the comment becomes an output column.

SQL
-- Show customers with a known Leeds address.
SELECT id, name
FROM customers
WHERE city = 'Leeds'
ORDER BY id;
Output
id | name
1  | Ana
2  | Ben

Common SQL Syntax and Comments: A Clear Beginner Reference Mistakes

Unquoted text and missing commas

Writing WHERE city = Leeds treats Leeds as an identifier rather than text and usually reports an unknown column. Writing SELECT id name can be parsed as an alias rather than two columns. Use a comma between separate columns and single quotes around string values. A comment that accidentally removes a closing parenthesis can also leave the statement incomplete.

SQL Syntax and Comments: A Clear Beginner Reference in Real Projects

Comments in saved team queries

A support team might keep a saved query for customers in a delivery area. A comment should record the reason for its city filter and who agreed to that rule. When the delivery policy changes, the explanation makes the condition easier to update without confusing a business decision with SQL syntax.

Keep literal quoting separate from identifier naming in saved scripts. If a customer name contains an apostrophe, parameter binding is preferable in application code; in a handwritten teaching literal, doubling the apostrophe preserves the intended character. A comment should explain why a condition exists and must not cut off required punctuation.

SQL Syntax and Comments: A Clear Beginner Reference FAQ

Does every SQL statement need a semicolon?

Many interactive tools accept a single statement without one, but a script with several statements needs a semicolon between them so the database knows where each ends. Using it consistently makes multi-statement scripts clearer and avoids errors when queries are later combined.

Are SQL names case-sensitive?

Keyword case is flexible: SELECT and select are the same. Identifier case and table-name behaviour depend on the database and quoting: PostgreSQL folds unquoted names to lowercase, and MySQL table names can be case-sensitive on Linux. Use a consistent naming convention, such as lowercase snake_case, to avoid surprises.

Can comments hide passwords safely?

No. Saved SQL files, version control and query logs may retain comments exactly as written, and anyone with access to them can read the text. Keep credentials out of scripts and their explanations entirely, and load them from a secure configuration source.

Why does my statement fail with "syntax error near" a word?

The database reached a word it didn't expect at that point. Look just before the reported position: a missing comma between columns, an unclosed quote or bracket, a misspelled keyword or a reserved word used as a name are the usual causes. Fix the first error before worrying about later ones.

Can I use a reserved word such as order as a column name?

Only by quoting it, with double quotes in PostgreSQL and SQLite, backticks in MySQL or square brackets in SQL Server, and then you must quote it everywhere. It's simpler to choose a different name, such as order_status or ordered_on.

SQL Syntax and Comments: A Clear Beginner Reference Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Multiple choicemedium

What does the commented Leeds-customer query return?

SQL Syntax and Comments: A Clear Beginner Reference Quiz

2 questions to check what you learned.

  1. Which text is a string literal?

    • Leeds without quotes
    • The column identifier city
    • 'Leeds'
  2. What does -- followed by a space start?

    • A comment that continues to the end of the line
    • A comment that ends only at a semicolon
    • A text literal that becomes a selected value