Cheatsheet -- SQL
SQL Cheatsheet
Section titled “SQL Cheatsheet”Query Anatomy
Section titled “Query Anatomy”SELECT DISTINCT column_name AS alias, AGG_FUNC(col)FROM table_nameJOIN other_table ON table_name.id = other_table.foreign_idWHERE conditionGROUP BY column_nameHAVING agg_conditionORDER BY column_name ASC/DESCLIMIT number OFFSET number;Order of Execution
Section titled “Order of Execution”FROM&JOINWHEREGROUP BYHAVINGSELECTDISTINCTORDER BYLIMIT
Filtering Operators
Section titled “Filtering Operators”| Operator | Syntax | Notes |
|---|---|---|
| Range | BETWEEN x AND y | Inclusive |
| List | IN (a, b, c) | Acts like multiple ORs |
| Pattern | LIKE 'A%' | % = any length, _ = single char |
| Nulls | IS NULL / IS NOT NULL | Never use = NULL |
| Type | Diagram Logic | Result |
|---|---|---|
INNER | ( A ∩ B ) | Only matches |
LEFT | ( A ) ∪ ( A ∩ B ) | All Left + Matches |
RIGHT | ( B ) ∪ ( A ∩ B ) | All Right + Matches |
FULL | ( A ∪ B ) | Everything |
Aggregation
Section titled “Aggregation”| Function | Usage |
|---|---|
COUNT(*) | Rows in group |
SUM(col) | Total of col |
AVG(col) | Average of col |
MIN(col) | Min of col |
MAX(col) | Max of col |
Data Types (Common)
Section titled “Data Types (Common)”| Type | Description |
|---|---|
INT / INTEGER | Whole numbers |
FLOAT / REAL | Decimals |
VARCHAR(n) | String with max length n |
TEXT | Long text strings |
BOOLEAN | True/False (or 1/0) |
DATE | YYYY-MM-DD |
TIMESTAMP | Date + Time |
Table Constraints
Section titled “Table Constraints”PRIMARY KEY: Unique ID for row.FOREIGN KEY: Links to another table’s PK.UNIQUE: No duplicates allowed.NOT NULL: Cannot be empty.DEFAULT: Value if none provided.CHECK: Validates data (e.g.,CHECK (price > 0)).