SQL Syntax
SQL · Introduction to SQL
Theory
A SQL statement is a sentence made of keywords (SELECT, FROM, WHERE), identifiers (table and column names), literals ('IT', 72000), operators (=, >, AND) and clauses. Each clause has one job, and clauses must be written in a fixed order: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, then LIMIT/FETCH. A semicolon ends the statement, which matters when you run several at once.
The written order is not the order the engine thinks in. Logically it starts with FROM (which rows exist), then WHERE, GROUP BY, HAVING, SELECT, ORDER BY and finally LIMIT. This explains common surprises, such as why a column alias made in SELECT cannot be used in WHERE. Keywords are case-insensitive, text values go in single quotes, and comments start with -- or sit inside /* */.
Why we use it
Knowing the grammar and the logical order of clauses lets you read any query, place each clause correctly and predict errors before running the query, instead of guessing at syntax messages.
When to use it
Use this mental model every time you write or debug a query. When a query errors out or returns odd rows, first check clause order, quotes (single for text, double or brackets for names) and the logical execution order.
How it works
- FROM: pick the source table(s)
- WHERE: keep rows that pass the condition
- GROUP BY: form groups (if any)
- HAVING: keep groups that pass
- SELECT: compute output columns and aliases
- ORDER BY: sort the result
- LIMIT / FETCH: cut to N rows
Syntax
SELECT column1, column2
FROM table_name
WHERE condition;Example
SELECT name, salary FROM employees WHERE department = 'IT';Key points
- Keywords are case-insensitive; writing them UPPERCASE is a readability convention
- Written order: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT
- Logical order starts at FROM, which is why SELECT aliases fail in WHERE
- Text literals use single quotes: 'IT'; double quotes are for identifiers in standard SQL
- Statements end with a semicolon; comments use -- or /* */