Chapter 1 of ?
Database 11 min read •
Sanjay
Written by Sanjay

SQL Tutorial for Beginners — Chapter 4: SQL Syntax, Semicolons & Comments

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.

Curriculum
Module 1: Foundations (Ch 4 of 82)
Estimated Time
12 mins read & practice
Prerequisites
Chapter 3: SQL Editor
Practice Engine
SQLite WASM (In-Browser)

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.

Clause

A major building block introduced by a keyword (e.g., SELECT, FROM, WHERE).

Keyword

A reserved word with predefined meaning (e.g., SELECT, FROM, ORDER BY).

Identifier

The unique name of an entity, such as a table (Customers) or a column (City).

Literal

A constant value written in the query, such as text ('India') or a number (1500).

Operator

A symbol used for comparisons or math (e.g., =, >, AND, OR).

Terminator (;)

A semicolon punctuation mark signaling the end of one statement and separating it from the next.

Anatomy of a SQL Statement Diagram showing the breakdown of a SQL SELECT statement into clauses, keywords, identifiers, operators, literals, and semicolon. Anatomy: SELECT CustomerName, City FROM Customers WHERE Country = 'India'; SELECT CustomerName, City FROM Customers WHERE Country = 'India'; SELECT Clause FROM Clause WHERE Clause KEYWORD Command IDENTIFIERS Column Names IDENTIFIER Table Name OPERATOR Comparison (=) LITERAL Text ('India') TERMINATOR Semicolon (;)
Figure 4.1: Anatomy of a SQL Statement — clauses, reserved keywords, identifiers, comparison operators, string literals, and statement terminator.

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:

Messy (Hard to Read)
select customername,city,country from customers where country='India';
Formatted (Professional)
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.
Logical Query Execution Order Pipeline Interactive diagram illustrating the 7 stages of query execution: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, and LIMIT with data transformation table. Query Engine Pipeline: Logical Execution Flow 1. FROM 2. WHERE 3. GROUP BY 4. HAVING 5. SELECT 6. ORDER BY 7. LIMIT ▶ Active Clause: FROM Orders Source Table: 8 Total Rows Loaded OrderID CustomerID ProductID Quantity OrderDate 1011 (Aarav)212026-01-05 1022 (Priya)122026-01-09 1033 (Liam)412026-01-12 1045 (Rohan)312026-02-02 1051 (Aarav)532026-02-14 1066 (Emma)612026-03-01 1074 (Sofia)212026-03-18 1082 (Priya)412026-04-03
Step 1: FROM Orders loads the base dataset of 6 customer orders from disk into memory.
Figure 4.2: Interactive 7-Stage Query Execution Order Pipeline (Pattern B).

4.6 Common Syntax Mistakes & How to Fix Them

Learn to identify and resolve four frequent syntax errors:

1. Missing Semicolon

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;
2. Unmatched Single Quote

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';
3. Double Quotes for Text

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';
4. SELECT Alias in WHERE

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):

SQL Interactive Sandbox (SQLite WASM) Database Ready
Ctrl + Enter to execute
Result Output: Ready
Click "Run SQL" to execute the query.

4.8 Hands-On Practice Exercises

Test what you have learned! Write queries in the sandbox above, or inspect the solution drawers:

Exercise 1: Format a Messy Query

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;
Exercise 2: Fix an Unmatched Quote

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';
Exercise 3: Fix a SELECT Alias in WHERE

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 UPPERCASE is 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 FROM first, WHERE second, and SELECT fifth — aliases are unavailable in WHERE clauses.

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.

Sanjay
Tutorial Author
Sanjay · Full-Stack Developer & AI Enthusiast
Pursuing MCA at Manipal University Jaipur. Founder of AICodeLab.
Done with this chapter?
Mark it complete to track your progress and unlock your certificate.
Next Up
—

Learner Reviews

Write a Review
Share your experience to help other learners.
Your Rating *
★ ★ ★ ★ ★