SQL Syntax
SQL statements read almost like English. Each one ends with a semicolon and is built from a handful of clauses that always appear in the same order.
The shape of a SELECT
SQL
SELECT <columns> FROM <table> WHERE <condition> GROUP BY <columns> HAVING <condition> ORDER BY <columns> LIMIT <n>;
Clauses, top to bottom
| Clause | What it does |
|---|---|
SELECT | Which columns to return. |
FROM | Which table (or join) to read from. |
WHERE | Filter rows before grouping. |
GROUP BY | Collapse rows into groups for aggregation. |
HAVING | Filter groups (after aggregation). |
ORDER BY | Sort the result. |
LIMIT / TOP | Cap the number of rows returned. |
Case & whitespace
- Keywords are case-insensitive —
SELECTandselectwork the same. Most teams use UPPERCASE for keywords as a convention. - Identifiers (table and column names) are usually case-insensitive on Windows and MS SQL Server, but case-sensitive in PostgreSQL.
- You can break a statement across as many lines as you like — only the final
;ends it.
Tip: Format long queries one clause per line. It makes diffs in code review readable and helps you spot a misplaced comma instantly.
Example
Exercise
End every SQL statement with this character.
SELECT 1
A single punctuation mark.
Discussion
Loading…