SQL Cheat Sheet
SQL Cheat Sheet
SQL Basics
SELECT col FROM table WHERE condition GROUP BY col HAVING agg_condition ORDER BY col LIMIT n;
- WHERE: filter rows | HAVING: filter aggregates
- ORDER: ASC (default), DESC
- LIMIT: restrict # of rows
Aggregates
SUM(col), COUNT(*), AVG(col), MIN(col), MAX(col)
- COUNT(col) excludes NULLs
- Use GROUP BY to aggregate by category
- Use HAVING for conditions on aggregates
Joins
INNER JOIN: match in both tables
LEFT JOIN: all from left + matches from right
RIGHT JOIN: all from right + matches from left
FULL OUTER JOIN (simulate in MySQL using UNION)
Subqueries
Non-correlated: independent of outer query
Correlated: depends on outer query (e.g., WHERE x > (SELECT ... WHERE x = outer.x))
Window Functions
OVER (PARTITION BY x ORDER BY y)
- ROW_NUMBER(), RANK(), DENSE_RANK()
- LAG(), LEAD(), SUM(), AVG() OVER windows
- Useful for running totals, rankings
CTEs (WITH)
WITH cte AS (SELECT ...) SELECT ... FROM cte;
- Helps break complex queries into readable blocks
CASE Statements
CASE WHEN cond THEN val ELSE val END
- Used for categorizing or conditional logic
- Common in SELECT or ORDER BY
Date Functions
CURDATE(), NOW(), YEAR(d), MONTH(d), DATE_FORMAT(d, '%Y-%m')
DATE_ADD(d, INTERVAL n DAY), DATEDIFF(d1, d2), TIMESTAMPDIFF(unit, d1, d2)
Analytics Patterns
- % of Total: SUM(x)/SUM(x) OVER()
- Running Total: SUM(x) OVER (ORDER BY date)
- Funnel: filter stepwise or use CASE counts
- Cohort: TIMESTAMPDIFF for retention lag
- Rolling Avg: AVG(x) OVER (ORDER BY d ROWS N PRECEDING)