Skip to content

SQL Syntax & Keywords 📝

Mentor's Note: Every language has grammar. English has periods and capital letters; SQL has semicolons and keywords. Get the grammar right, and the database will understand you perfectly every time. 💡


🌟 The Scenario: The Robot Translator 🤖

Imagine you are giving instructions to a very literal robot.

  • Bad Grammar: "pick up box red." -> Robot confuses "box" and "red". 😕
  • Good Grammar: "PICK UP the RED BOX." -> Robot executes perfectly. ✅

SQL is that robot. It needs specific words in a specific order.


🎨 Visual Logic: The Anatomy of a Query

graph LR
    A[SELECT] -- "Keyword (Action)" --> B[column_name]
    B -- "Identifier (Target)" --> C[FROM]
    C -- "Keyword (Source)" --> D[table_name]
    D -- "Identifier (Location)" --> E[;]
    E -- "Terminator (End)" --> F[Result]

💻 1. Important Syntax Rules

A. Keywords (The "Verbs")

Keywords are reserved words that tell the database what to do. - Examples: SELECT, FROM, WHERE, CREATE, TABLE. - Rule: You cannot use these as names for your tables or columns (unless you quote them, but don't do that!). - Style: We write keywords in UPPERCASE to make them stand out, though SQL is technically case-insensitive.

-- ✅ Good Style
SELECT name FROM students;

-- ⚠️ Valid but Messy
select name from students;

B. Case Sensitivity

  • Keywords: Not case sensitive (SELECT = select).
  • Table/Column Names: Usually not case sensitive (depends on OS), but stick to snake_case (e.g., first_name).
  • Data: VERY Case Sensitive! 'Apple' is NOT 'apple'.

C. Semicolons (;)

The Semicolon is the standard way to separate each SQL statement. - Oracle/PostgreSQL: Strictly required. - SQL Server: Optional but recommended. - MySQL: Required if running multiple commands.

SELECT * FROM students; -- Statement 1
SELECT * FROM teachers; -- Statement 2

D. Comments (Notes to Self)

Comments are parts of the code the database ignores. Use them to explain why you wrote a query.

-- This is a single-line comment

/*
   This is a multi-line comment.
   Use this for long explanations.
*/
SELECT * FROM employees;

💻 2. The SQL Order of Operations (Lexical Order)

When you write SQL, you must follow this order. You can't put FROM before SELECT!

  1. SELECT (What columns?)
  2. FROM (Which table?)
  3. WHERE (Filter rows?)
  4. GROUP BY (Aggregate?)
  5. HAVING (Filter groups?)
  6. ORDER BY (Sort?)

(Note: The database executes them in a different order internally, but you must write them in this order).


💡 Pro Tip

"Consistency is key. Decide on a casing style (e.g., UPPECASE keywords, lowercase identifiers) and stick to it. Your future self will thank you when reading 100 lines of code!"


📈 Learning Path