Chapter 4: SQL Syntax, Semicolons & Comments
SQL is a declarative language with simple, elegant grammar rules. Master statement structure, reserved keywords, semicolon rules, comments, case sensitivity conventions, and the logical order in which database engines execute queries.
Grammar Rules
Clauses & Identifiers
Statements are built from clauses, keywords, table/column identifiers, and literals terminated by semicolons.
Case Insensitive
Keywords in CAPS
Keywords are case-insensitive. Writing UPPERCASE keywords is the universal professional standard.
SQL Comments
Documentation & Debugging
Use -- for single-line notes and /* ... */ to document logic or disable clauses during testing.
Execution Order
7-Stage Pipeline
Engines execute FROM first, then WHERE, and SELECT fifth—explaining alias limitations.
4.1 What is a SQL Statement?
Just as an English sentence communicates a complete thought, a SQL statement is a complete instruction sent to a relational database engine. When you execute a statement, the database parses your request, checks its grammar, retrieves or alters the requested records, and returns the result.
A major building block introduced by a keyword (e.g., SELECT, FROM, WHERE).
A reserved word with predefined meaning (e.g., SELECT, FROM, ORDER BY).
The unique name of an entity, such as a table (Customers) or a column (City).
A constant value written in the query, such as text ('India') or a number (1500).
A symbol used for comparisons or math (e.g., =, >, AND, OR).
A semicolon punctuation mark signaling the end of one statement and separating it from the next.
4.2 The Basic Rules of SQL Syntax
Relational database engines adhere to five core syntactic rules when parsing queries:
1. Statements End with a Semicolon (;)
The semicolon is the universal statement terminator in SQL. While some single-statement queries run without it, it is strictly required when executing multi-statement scripts:
SELECT * FROM Customers; SELECT * FROM Products;
2. Keywords Are Case-Insensitive
The SQL parser treats SELECT, select, and Select identically. However, writing keywords in UPPERCASE is the universal professional standard to clearly separate commands from table/column names.
3. Whitespace and Line Breaks Do Not Change Meaning
SQL is free-form: extra spaces, tabs, and newlines are treated as equivalent separators. A messy single-line query returns the exact same dataset as a neatly formatted query:
select customername,city,country from customers where country='India';
SELECT CustomerName, City, Country FROM Customers WHERE Country = 'India';
4. Text Values Require Single Quotes
Text literals must always be enclosed in single quotes ('Mumbai', 'Audio'). Numbers do not require quotes (1500). To include an apostrophe inside text, double the single quote:
-- Double the single quote to escape it: SELECT * FROM Customers WHERE CustomerName = 'O''Connor';
5. Names with Spaces Require Delimiters
If an identifier contains spaces, escape it with the dialect-specific delimiter:
| Dialect | Delimiter | Example Syntax |
|---|---|---|
| ANSI SQL & PostgreSQL | Standard Double Quotes (" ") |
SELECT "First Name" FROM "Customer Orders"; |
| SQLite | Double Quotes, Backticks, or Brackets | SELECT "First Name" FROM Customers; |
| MySQL / MariaDB | Backticks (` `) |
SELECT `First Name` FROM `Orders`; |
| SQL Server (T-SQL) | Square Brackets ([ ]) |
SELECT [First Name] FROM [Customers]; |
4.3 Case Sensitivity: What Is and Isn't Sensitive
Case sensitivity in SQL depends on the type of component:
Keywords
Always Insensitive: SELECT, select, and Select are identical in all databases.
Tables & Columns
Engine-Dependent: Insensitive in SQLite, PostgreSQL, and SQL Server. Sensitive in MySQL on Linux.
Text Comparisons
Collation-Dependent: Case-sensitive in SQLite & PostgreSQL; case-insensitive by default in MySQL & SQL Server.
In the Editor (SQLite)
In SQLite, text comparison is case-sensitive by default: WHERE Country = 'India' returns 4 customers, but WHERE Country = 'india' returns 0 rows. To perform case-insensitive comparison, add COLLATE NOCASE: WHERE Country = 'india' COLLATE NOCASE;.
4.4 SQL Comments: Single-Line & Multi-Line
Comments are human notes embedded in SQL code that the engine ignores. Use them for documentation and debugging:
Single-Line Comments (--)
Begins with --. Everything until the end of that line is ignored.
-- Retrieve high-value orders SELECT * FROM Orders WHERE TotalAmount > 5000; -- VIP filter
Multi-Line Comments (/* */)
Enclosed in /* ... */. Can span multiple lines or disable clauses.
SELECT ProductName, Price FROM Products /* Temporarily disabled: WHERE Category = 'Audio' */ ORDER BY Price DESC;
4.5 Logical Query Execution Order
The order in which you write a query is not the order in which the database executes it:
| Written Order | Execution Step | Pipeline Stage | Engine Action |
|---|---|---|---|
1. SELECT |
Step 5 | SELECT & Aliases | Computes columns, expressions, and alias names. |
2. FROM |
Step 1 | FROM & JOINs | Identifies and joins the source tables into working memory. |
3. WHERE |
Step 2 | WHERE Filtering | Filters raw rows before any grouping occurs. |
4. GROUP BY |
Step 3 | GROUP BY | Collapses rows into aggregate buckets. |
5. HAVING |
Step 4 | HAVING | Filters grouped buckets by aggregate conditions. |
6. ORDER BY |
Step 6 | ORDER BY | Sorts the final records in ASC or DESC sequence. |
7. LIMIT |
Step 7 | LIMIT / OFFSET | Restricts output to the specified row count. |
4.6 Common Syntax Mistakes & How to Fix Them
Learn to identify and resolve four frequent syntax errors:
Running two queries without a semicolon separator causes a parse error.
-- ❌ Error: near "SELECT": syntax error SELECT * FROM Customers SELECT * FROM Orders;
-- ✅ Fixed: SELECT * FROM Customers; SELECT * FROM Orders;
An unclosed single quote breaks parsing through the end of the query.
-- ❌ Error: unrecognized token: "'Mumbai;" SELECT * FROM Customers WHERE City = 'Mumbai;
-- ✅ Fixed: SELECT * FROM Customers WHERE City = 'Mumbai';
Standard SQL treats double quotes as column identifiers, not string literals.
-- ❌ Error: column "Electronics" does not exist SELECT * FROM Products WHERE Category = "Electronics";
-- ✅ Fixed: SELECT * FROM Products WHERE Category = 'Electronics';
WHERE runs at Step 2; SELECT aliases only exist starting at Step 5.
-- ❌ Error: no such column: discounted SELECT Price * 0.8 AS discounted FROM Products WHERE discounted < 1500;
-- ✅ Fixed: SELECT Price * 0.8 AS discounted FROM Products WHERE (Price * 0.8) < 1500;
4.7 Interactive Practice: Try It Yourself
Test queries against our sample "AICodeLab Shop" SQLite database (22 records):
4.8 Hands-On Practice Exercises
Test what you have learned! Write queries in the sandbox above, or inspect the solution drawers:
Format this query across multiple lines with uppercase keywords and a comment: select productname,price from products where price<1500;
-- Retrieve affordable products priced under 1,500 rupees
SELECT ProductName, Price
FROM Products
WHERE Price < 1500;
Fix the syntax error in: SELECT CustomerName, City FROM Customers WHERE City = 'Mumbai;
-- Fixed: Close the single quote string delimiter
SELECT CustomerName, City
FROM Customers
WHERE City = 'Mumbai';
Fix the query: SELECT ProductName, (Price * 0.82) AS discounted_price FROM Products WHERE discounted_price < 2000;
-- Fix: Repeat calculation because WHERE executes before SELECT
SELECT ProductName, (Price * 0.82) AS discounted_price
FROM Products
WHERE (Price * 0.82) < 2000;
4.10 Key Takeaways
Core Rules Summary
- Semicolon Terminator: Semicolons terminate and separate statements in scripts.
- Keyword Conventions: Keywords are case-insensitive, but writing them in
UPPERCASEis standard practice. - String Literals: Wrap text in single quotes (
'Mumbai') and double apostrophes inside text ('It''s'). - Whitespace Freedom: Break clauses across multiple lines with clean indentation for maintainability.
- Execution Pipeline: Engines run
FROMfirst,WHEREsecond, andSELECTfifth — aliases are unavailable inWHEREclauses.
4.11 Frequently Asked Questions
Is the semicolon (;) always mandatory in SQL?
In standard ANSI SQL, the semicolon is the required statement terminator. While some tools allow omitting it for a single isolated query, it is strictly required when executing multi-statement scripts.
Are SQL keywords case-sensitive?
No, SQL keywords (like SELECT, FROM, WHERE) are case-insensitive across all relational engines. Writing keywords in UPPERCASE is the universal industry standard for code readability.
How do I include an apostrophe inside text in SQL?
Double the single quote. For example, to write It's, write 'It''s'. The first quote escapes the second.
Why can't I use a SELECT column alias in a WHERE clause?
Because of logical query execution order: the database engine executes the WHERE filter at Step 2, whereas SELECT aliases are only created at Step 5. The alias does not exist yet when WHERE runs.
Is text comparison case-sensitive in SQLite?
In SQLite (and this editor), text comparisons using the equals operator (=) are case-sensitive by default for ASCII text, unless the column is configured with COLLATE NOCASE.