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.
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.
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!
- SELECT (What columns?)
- FROM (Which table?)
- WHERE (Filter rows?)
- GROUP BY (Aggregate?)
- HAVING (Filter groups?)
- 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!"