SQL Functions Cheat Sheet
1. **ROUND()** - Round numbers to specified decimal places:
- ROUND(value, decimal_places)
- Rounds to the nearest whole number or decimal place.
Example: ROUND(123.4567, 2) = 123.46
ROUND(9876, -3) = 10000 (round to nearest thousand)
2. **CAST() / FORMAT()** - Convert numbers or strings, or format them:
- CAST(value AS DECIMAL(10, 2)) - Convert to decimal with 2 places.
- FORMAT(value, 2) - Show value with 2 decimal places (works in MySQL).
Example: CAST(1000 AS DECIMAL(10, 2)) = 1000.00
3. **LIKE and %** - Pattern matching in text columns:
- LIKE 'pattern%' - Match anything starting with "pattern".
Example: WHERE name LIKE 'United%' finds 'United States', 'United Kingdom'.
4. **IN and NOT IN** - Filter using multiple values:
- WHERE column IN ('val1', 'val2', 'val3') - Matches any value in the list.
Example: WHERE name IN ('India', 'USA')
5. **IS NULL / IS NOT NULL** - Handle missing data:
- WHERE column IS NULL or WHERE column IS NOT NULL
Example: WHERE gdp IS NULL finds countries with no GDP.
6. **GROUP BY & HAVING** - Group and filter aggregated data:
- GROUP BY column to group data.
- HAVING filters groups, like WHERE but for aggregated data.
Example: SELECT continent, SUM(population) FROM world GROUP BY continent HAVING
SUM(population) > 500000000
7. **CASE WHEN** - Conditional logic inside a query:
- CASE WHEN condition THEN result ELSE default END
Example: SELECT name, CASE WHEN population > 1000000000 THEN 'Large' ELSE 'Small'
END AS size FROM world
8. **Joins (LEFT JOIN, INNER JOIN)** - Combine data from multiple tables:
- LEFT JOIN: Keep all records from the left table.
- INNER JOIN: Only include records with matching values in both tables.
Example: SELECT students.name, marks.score FROM students LEFT JOIN marks ON
students.id = marks.student_id
9. **Subqueries** - A query inside another query to filter results or perform calculations.
Example: SELECT name FROM world WHERE population > (SELECT AVG(population) FROM
world)
10. **Window Functions** (e.g., `ROW_NUMBER()`, `RANK()`, `LEAD()`) - Advanced analytical
functions to perform calculations across rows related to the current row.
Example: SELECT name, population, RANK() OVER (ORDER BY population DESC) AS rank
FROM world
11. **LEFT()** - Extract a specified number of characters from the left side of a string:
Example: SELECT LEFT(name, 1) FROM world (gives the first character of each country)