SQL Syntax & Keywords πΒΆ
Prerequisites: Introduction to SQL
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!"