Tutorials SQL SQL Syntax & Rules
Ch 5 / 69
Advertisement
📢 Ad space · 728 × 90 · Replace slot ID above
Chapter 5 Beginner 5 min read SQL

SQL Syntax & Rules

Before you can write powerful SQL queries, you need to know the grammar. SQL has a small but precise set of rules — around semicolons, case, whitespace, identifiers, and comments — that every database engine enforces. Master these rules once and every SQL statement you ever write will be structured correctly.

What you'll learn
The anatomy of an SQL statement
Why semicolons and whitespace matter
Case sensitivity rules for keywords vs data
How to name tables, columns, and aliases
Single-line and multi-line SQL comments
The correct order of SQL clauses
Common syntax mistakes beginners make

Anatomy of an SQL Statement

Every SQL statement is built from clauses. A clause starts with a keyword (like SELECT or WHERE) and is followed by one or more expressions — column names, values, operators, or conditions. Together, the clauses form a complete instruction that the database engine can parse and execute.

Anatomy of a SELECT Statement
SELECT name, salary FROM employees WHERE salary > 50000 ;
SELECT Clause
Column list
FROM Clause
Table name
WHERE Clause
Condition
Terminator

The key insight: SQL is declarative. You describe what you want (all employees earning more than 50,000), not how to find it. The database engine figures out the most efficient route to that answer.

Advertisement
📢 Ad space · 728 × 90 · Replace slot ID above

The 6 Core SQL Syntax Rules

These six rules govern every valid SQL statement. Violate any one of them and the database will throw a syntax error before executing a single byte.

Semicolons end statements
A semicolon ; marks the end of a complete SQL statement. Most database clients require it. Without one, they wait for more input or throw an error.
Keywords are case-insensitive
SELECT, select, and Select all mean the same thing. Convention is UPPERCASE for readability. Never mix cases randomly.
String values use single quotes
Text values are wrapped in single quotes: 'Alice', 'New York'. Double quotes are reserved for identifiers in standard SQL. Never use them for string data.
Whitespace is ignored
Extra spaces, tabs, and newlines between tokens are completely invisible to the parser. Use them freely to keep your queries readable.
Identifiers follow naming rules
Table and column names must start with a letter or underscore, contain only letters, digits, and underscores, and must not clash with reserved SQL keywords.
Clauses follow a fixed order
SQL clauses must appear in a specific sequence: SELECT → FROM → WHERE → GROUP BY → HAVING → ORDER BY → LIMIT.

Case Sensitivity — Keywords vs Data

SQL has a split personality when it comes to case: SQL keywords are always case-insensitive, but string data may or may not be, depending on the database and its collation settings.

What Case-sensitive? Example Notes
SQL keywords ❌ No select = SELECT = Select All identical to the parser
Table / column names ⚠️ Depends employees ≠ Employees (Linux MySQL) Linux file system is case-sensitive; Windows is not
String data values ⚠️ Depends on collation 'alice' = 'Alice' (MySQL utf8_general_ci) _ci = case-insensitive; _cs = case-sensitive
Quoted identifiers ✅ Yes "Name" ≠ "name" Backticks in MySQL, double quotes in PostgreSQL
Best Practice
Write all SQL keywords in UPPERCASE and all identifiers in lowercase_with_underscores. This is the most universally readable convention and is what you'll see in professional codebases and documentation.
✅ DO — clear and conventional
SELECT first_name, last_name
FROM   employees
WHERE  department_id = 10
ORDER BY last_name;
❌ DON'T — inconsistent casing
select First_Name, LAST_NAME
From Employees
where Department_ID = 10
order by last_name;

Semicolons & Whitespace

Semicolons

The semicolon ; is the statement terminator. It tells the database engine "this statement is complete — go execute it."

  • 1
    Required in scripts with multiple statements Without semicolons, the parser cannot tell where one statement ends and the next begins.
  • 2
    Optional for single statements in some clients MySQL Workbench and many GUI tools add one automatically. The command-line client requires it.
  • 3
    Always add it — it never hurts Make the semicolon a habit from day one. It's always safe to include, never safe to omit in scripts.
SQL — Multi-statement script (semicolons required)
CREATE TABLE products (id INT PRIMARY KEY, name VARCHAR(100)); INSERT INTO products (id, name) VALUES (1, 'Laptop'), (2, 'Mouse'); SELECT * FROM products;

Whitespace

SQL is completely whitespace-agnostic between tokens. Spaces, tabs, and newlines are treated identically by the parser — use them to make your query readable, not for correctness.

✅ Multi-line — easiest to read
SELECT
    e.first_name,
    e.last_name,
    d.department_name
FROM
    employees e
    JOIN departments d ON e.dept_id = d.id
WHERE
    e.salary > 50000
ORDER BY
    e.last_name ASC;
✅ Single-line — valid but cramped
SELECT e.first_name, e.last_name, d.department_name FROM employees e JOIN departments d ON e.dept_id = d.id WHERE e.salary > 50000 ORDER BY e.last_name ASC;
Watch out
Whitespace inside string literals does matter. 'New York' ≠ 'NewYork' ≠ 'New York'. Only whitespace outside quotes is ignored.
📊
Free Resource
Download our SQL Cheat Sheet
All essential commands, clauses and functions — one printable page.
Get Sheet

Identifiers & Naming Rules

An identifier is any name you give to a database object — a table, column, index, view, alias, or schema. Identifiers must follow these rules to be valid:

  • A
    Start with a letter or underscore Valid: employee_id, _temp. Invalid: 1employee, -name.
  • B
    Only letters, digits, and underscores after that No hyphens, spaces, or special characters (unless the identifier is quoted).
  • C
    Must not be a reserved word (unquoted) Words like SELECT, FROM, WHERE, ORDER are reserved — using them as column names without quotes causes errors.
  • D
    No length limit in practice, but keep them short MySQL allows up to 64 characters. SQL Server allows up to 128. Be descriptive but concise.

Naming Convention Comparison

Convention Example Common in Recommended?
snake_case employee_id, first_name PostgreSQL, MySQL, standard SQL ✅ Yes — most universal
PascalCase EmployeeId, FirstName SQL Server, .NET environments ✅ Acceptable in SQL Server
camelCase employeeId, firstName Rarely, usually from ORM output ⚠️ Avoid — requires quoting
Spaces / hyphens "first name", "emp-id" Accidental / legacy ❌ No — always requires quoting
ALL_CAPS EMPLOYEE_ID, FIRST_NAME Oracle legacy ⚠️ Outdated — hard to distinguish from keywords

Quoting Identifiers

If you must use reserved words or special characters as identifiers, wrap them in the database-specific quote character:

✅ MySQL — backticks
SELECT `name`, `order`
FROM `user-data`;
✅ PostgreSQL / Standard SQL — double quotes
SELECT "name", "order"
FROM "user-data";
Tip
The best identifier is one that never needs quoting. Choose snake_case names that are descriptive, avoid reserved words, and your queries will be portable across every SQL database.
Advertisement
📢 Ad space · 728 × 90 · Replace slot ID above

SQL Comments

Comments let you annotate your SQL without affecting execution. The database parser skips everything inside a comment. SQL supports two comment styles:

Single-line comment --
-- Retrieve all active customers
SELECT customer_id, full_name
FROM   customers
WHERE  status = 'active'; -- inline comment
Multi-line comment /* … */
/*
  Author:  K2infocom
  Purpose: Monthly sales summary
  Updated: 2025-01-15
*/
SELECT
    MONTH(order_date) AS month,
    SUM(total) AS revenue
FROM orders;
Note
-- comments extend to the end of the line. Everything after the double dash on that line is ignored. /* … */ comments span multiple lines and can be placed anywhere — even in the middle of a statement. Use -- for quick notes and /* */ for headers and multi-line explanations.

Required Clause Order in SELECT

The clauses of a SELECT statement must appear in a fixed sequence. The parser will throw an error if you put WHERE after GROUP BY, for example. Memorise this order — it becomes second nature.

SELECT Clause Order
Required
SELECT  col1, col2, …
↓
Required
FROM  table_name
↓
Optional
JOIN  other_table ON …
↓
Optional
WHERE  condition
↓
Optional
GROUP BY  col
↓
Optional
HAVING  condition
↓
Optional
ORDER BY  col ASC|DESC
↓
Optional
LIMIT  n OFFSET  m
Memory tip
Remember the mnemonic: "Select From Where Group Having Order Limit" → S-F-W-G-H-O-L. Read it as: "Somewhere From Where Groups Have Orders Listed."

Common SQL Syntax Mistakes

These are the errors beginners hit most often. Recognise them now and save yourself hours of head-scratching later.

1. Using double quotes for string values

❌ Wrong — double quotes for strings
SELECT * FROM users WHERE name = "Alice";
✅ Correct — single quotes for strings
SELECT * FROM users WHERE name = 'Alice';

In MySQL, double quotes can work in some modes, but in standard SQL (PostgreSQL, Oracle) double quotes are reserved for identifiers. Always use single quotes for string data.

2. Missing the FROM clause

❌ Wrong — no FROM
SELECT name, salary WHERE salary > 50000;
✅ Correct — FROM required
SELECT name, salary
FROM   employees
WHERE  salary > 50000;

3. Using WHERE with aggregate functions

❌ Wrong — WHERE can't filter aggregates
SELECT dept_id, AVG(salary)
FROM   employees
WHERE  AVG(salary) > 60000
GROUP BY dept_id;
✅ Correct — use HAVING for aggregates
SELECT dept_id, AVG(salary)
FROM   employees
GROUP BY dept_id
HAVING AVG(salary) > 60000;

4. Wrong clause order

❌ Wrong — ORDER BY before WHERE
SELECT name FROM employees
ORDER BY name
WHERE salary > 40000;
✅ Correct — WHERE comes before ORDER BY
SELECT name FROM employees
WHERE  salary > 40000
ORDER BY name;

5. Using = for NULL comparison

❌ Wrong — = doesn't work with NULL
SELECT * FROM employees WHERE manager_id = NULL;
✅ Correct — use IS NULL
SELECT * FROM employees WHERE manager_id IS NULL;

NULL means "unknown value." In SQL, NULL = NULL evaluates to NULL (not TRUE), so the equals operator never matches NULL. Always use IS NULL or IS NOT NULL.

Try It Yourself — SQL Syntax Playground

Practice the syntax rules you just learned using the in-browser runner below. The sample database includes an employees table. Try experimenting with different queries.

Try a sample:
SQL Syntax Runner Live
In-browser demo · Tables: employees · Press Ctrl + Enter to run
Results will appear here after you run a query
Quick Check — Chapter 5

Which of the following is the correct way to filter rows where a column is NULL in SQL?

Chapter Summary
  • An SQL statement is made of clauses — each starting with a keyword like SELECT, FROM, or WHERE — followed by expressions.
  • SQL is declarative: you describe what data you want, not how to find it.
  • SQL keywords are case-insensitive; string data case sensitivity depends on the database collation. Convention: UPPERCASE keywords, lowercase identifiers.
  • Always use single quotes for string values ('Alice') and reserve double quotes / backticks for identifiers.
  • The semicolon ; terminates a statement — always include it, especially in scripts with multiple statements.
  • Whitespace outside string literals is completely ignored by the parser — use it freely for readability.
  • Identifiers must start with a letter or underscore, contain only alphanumeric characters and underscores, and must not clash with reserved words.
  • Use -- for single-line comments and /* … */ for multi-line comments.
  • Clauses in a SELECT must follow the fixed order: SELECT → FROM → JOIN → WHERE → GROUP BY → HAVING → ORDER BY → LIMIT.
  • The most common mistakes: double quotes for strings, = for NULL comparisons, WHERE with aggregates instead of HAVING, and wrong clause order.
Advertisement
📢 Ad space · 728 × 90 · Replace slot ID above

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel